@pairdraw/web-capture 0.18.0 → 0.19.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.
@@ -135,6 +135,10 @@ const CAPTURED_STYLE_PROPERTIES = [
135
135
  "align-self",
136
136
  "aspect-ratio",
137
137
  "background-color",
138
+ "background-image",
139
+ "background-position",
140
+ "background-repeat",
141
+ "background-size",
138
142
  "border-bottom-color",
139
143
  "border-bottom-left-radius",
140
144
  "border-bottom-right-radius",
@@ -221,6 +225,10 @@ const IMPLIED_VALUES = {
221
225
  "align-self": ["auto"],
222
226
  "aspect-ratio": ["auto"],
223
227
  "background-color": ["rgba(0, 0, 0, 0)", "transparent"],
228
+ "background-image": ["none"],
229
+ "background-position": ["0% 0%"],
230
+ "background-repeat": ["repeat"],
231
+ "background-size": ["auto"],
224
232
  "box-shadow": ["none"],
225
233
  "column-gap": ["normal"],
226
234
  "flex-direction": ["row"],
@@ -314,7 +322,7 @@ const captureHeaderSchema = v.looseObject({
314
322
  format: v.literal(WEB_CAPTURE_FORMAT),
315
323
  version: v.number()
316
324
  });
317
- /** Attributes a layer can use: names, links, images, and accessible labels. */
325
+ /** Attributes a layer can use: names, links, images, control kinds, and accessible labels. */
318
326
  const KEPT_ATTRIBUTES = /* @__PURE__ */ new Set([
319
327
  "id",
320
328
  "class",
@@ -322,6 +330,7 @@ const KEPT_ATTRIBUTES = /* @__PURE__ */ new Set([
322
330
  "src",
323
331
  "alt",
324
332
  "title",
333
+ "type",
325
334
  "role",
326
335
  "aria-label",
327
336
  "lang",
@@ -380,8 +389,54 @@ function keptAttributes(attrs, base) {
380
389
  }
381
390
  return kept;
382
391
  }
383
- function keptStyle(style) {
384
- return Object.fromEntries(Object.entries(style).filter(([property]) => isCapturedStyleProperty(property)));
392
+ /** The `url(...)` sources of a value, with the spans they occupy. */
393
+ const BACKGROUND_URL = /url\(\s*(['"]?)(.*?)\1\s*\)/g;
394
+ /**
395
+ * A `background-image` list with every `url(...)` source limited to what an image layer may
396
+ * keep; a layer whose source is unsafe is dropped, and a list left empty paints nothing.
397
+ * Gradient layers carry no address and pass through as written.
398
+ */
399
+ function keptBackgroundImage(value, base) {
400
+ const layers = [];
401
+ let cursor = 0;
402
+ let dropped = false;
403
+ for (const match of value.matchAll(BACKGROUND_URL)) {
404
+ const source = safeImageSource(match[2], base);
405
+ if (source) layers.push(value.slice(cursor, match.index) + `url("${source}")`);
406
+ else dropped = true;
407
+ cursor = match.index + match[0].length;
408
+ }
409
+ if (cursor === 0 && !dropped) return value;
410
+ layers.push(value.slice(cursor));
411
+ const kept = [];
412
+ let depth = 0;
413
+ let current = "";
414
+ for (const character of layers.join("")) {
415
+ if (character === "(") depth++;
416
+ else if (character === ")") depth--;
417
+ if (character === "," && depth === 0) {
418
+ kept.push(current);
419
+ current = "";
420
+ continue;
421
+ }
422
+ current += character;
423
+ }
424
+ kept.push(current);
425
+ const painted = kept.map((layer) => layer.trim()).filter((layer) => layer.length > 0 && layer !== "none");
426
+ return painted.length > 0 ? painted.join(", ") : null;
427
+ }
428
+ function keptStyle(style, base) {
429
+ const kept = {};
430
+ for (const [property, value] of Object.entries(style)) {
431
+ if (!isCapturedStyleProperty(property)) continue;
432
+ if (property === "background-image") {
433
+ const image = keptBackgroundImage(value, base);
434
+ if (image) kept[property] = image;
435
+ continue;
436
+ }
437
+ kept[property] = value;
438
+ }
439
+ return kept;
385
440
  }
386
441
  function normalizeElement(element, base, depth, budget) {
387
442
  const children = [];
@@ -402,8 +457,8 @@ function normalizeElement(element, base, depth, budget) {
402
457
  type: "element",
403
458
  tagName: element.tagName,
404
459
  attrs: keptAttributes(element.attrs, base),
405
- computedStyle: keptStyle(element.computedStyle),
406
460
  ...element.box ? { box: element.box } : {},
461
+ computedStyle: keptStyle(element.computedStyle, base),
407
462
  children
408
463
  };
409
464
  }
@@ -1 +1 @@
1
- {"version":3,"file":"clipboard.js","names":[],"sources":["../../../src/record.ts","../../../src/html.ts","../../../src/limits.ts","../../../src/schema.ts","../../../src/styles.ts","../../../src/urls.ts","../../../src/parse.ts","../../../src/clipboard.ts","../../../src/capturer/clipboard.ts"],"sourcesContent":["/**\n * The value a style or attribute record sets for `key`, or undefined when it sets none. Records\n * are typed as setting every key, which they do not.\n */\nexport function ownValue(\n record: Readonly<Record<string, string>>,\n key: string\n): string | undefined {\n return Object.hasOwn(record, key) ? record[key] : undefined\n}\n","import { escapeAttribute, escapeText } from 'entities'\n\nimport type { WebCapture } from './format'\nimport { ownValue } from './record'\nimport type { WebCaptureElement, WebCaptureNode } from './types'\n\nconst VOID_TAGS = new Set(['area', 'br', 'col', 'hr', 'img', 'input', 'source', 'wbr'])\n\nexport interface WebCaptureHTMLOptions {\n /** Keep inlined images; without them an image keeps only its size and description. */\n images?: boolean\n}\n\nfunction styleAttribute(style: Record<string, string>): string {\n return Object.entries(style)\n .map(([property, value]) => `${property}: ${value}`)\n .join('; ')\n}\n\nfunction attributes(element: WebCaptureElement, options: WebCaptureHTMLOptions): string {\n const attrs: Record<string, string> = { ...element.attrs }\n if (options.images === false && ownValue(attrs, 'src')?.startsWith('data:')) delete attrs.src\n const style = styleAttribute(element.computedStyle)\n if (style) attrs.style = style\n return Object.entries(attrs)\n .map(([name, value]) => ` ${name}=\"${escapeAttribute(value)}\"`)\n .join('')\n}\n\nfunction serialize(node: WebCaptureNode, options: WebCaptureHTMLOptions): string {\n if (node.type === 'text') return escapeText(node.text)\n const open = `<${node.tagName}${attributes(node, options)}>`\n if (VOID_TAGS.has(node.tagName)) return open\n const children = node.children.map((child) => serialize(child, options)).join('')\n return `${open}${children}</${node.tagName}>`\n}\n\n/**\n * The capture as static HTML whose elements carry their computed styles inline, for\n * applications that read clipboard HTML but not the capture itself.\n */\nexport function webCaptureToHTML(capture: WebCapture, options: WebCaptureHTMLOptions = {}): string {\n return serialize(capture.root, options)\n}\n","/** The capture format identifier that clipboard payloads and files carry. */\nexport const WEB_CAPTURE_FORMAT = 'pairdraw/web-capture'\n\n/** The capture format version this package writes and reads. */\nexport const WEB_CAPTURE_VERSION = 1\n\n/** Elements one capture holds at most; a capturer stops descending once it reaches this. */\nexport const MAX_CAPTURE_ELEMENTS = 20_000\n\n/** How deep a capture nests; deeper elements are left out, as browsers rarely draw them. */\nexport const MAX_CAPTURE_DEPTH = 256\n\n/** Bytes one inlined image may take; a larger image stays a link the importer records. */\nexport const MAX_CAPTURE_IMAGE_BYTES = 8 * 1024 * 1024\n\n/** Bytes all inlined images of a capture take together. */\nexport const MAX_CAPTURE_IMAGES_BYTES = 48 * 1024 * 1024\n\n/** Characters of serialized capture JSON a reader accepts, images included. */\nexport const MAX_CAPTURE_JSON_LENGTH = 96 * 1024 * 1024\n\n/** Characters of plain web HTML a paste styles; a larger fragment is refused. */\nexport const MAX_WEB_HTML_LENGTH = 8 * 1024 * 1024\n","import * as v from 'valibot'\n\nimport { MAX_CAPTURE_JSON_LENGTH, WEB_CAPTURE_FORMAT, WEB_CAPTURE_VERSION } from './limits'\nimport type { WebCaptureElement, WebCaptureNode } from './types'\n\nconst finiteSchema = v.pipe(v.number(), v.finite())\nconst sizeSchema = v.pipe(v.number(), v.finite(), v.minValue(0))\nconst shortStringSchema = v.pipe(v.string(), v.maxLength(4096))\n\nconst webCaptureBoxSchema = v.object({\n x: finiteSchema,\n y: finiteSchema,\n width: sizeSchema,\n height: sizeSchema\n})\n\nconst webCaptureTextSchema = v.object({\n type: v.literal('text'),\n text: v.pipe(v.string(), v.maxLength(1_000_000))\n})\n\n/** HTML and SVG tag names, lowercase as a capturer writes them. */\nconst tagNameSchema = v.pipe(v.string(), v.regex(/^[a-z][a-z0-9-]{0,63}$/))\n/** Attribute names; which of them an import keeps is decided when a capture is read. */\nconst attributeNameSchema = v.pipe(v.string(), v.regex(/^[a-z][a-z0-9:_-]{0,63}$/))\n/** Attribute values hold inlined images as data URLs, so they may be large. */\nconst attributeValueSchema = v.pipe(v.string(), v.maxLength(MAX_CAPTURE_JSON_LENGTH))\nconst propertyNameSchema = v.pipe(v.string(), v.regex(/^-?[a-z][a-z-]{0,63}$/))\n\nconst webCaptureElementSchema: v.GenericSchema<unknown, WebCaptureElement> = v.object({\n type: v.literal('element'),\n tagName: tagNameSchema,\n attrs: v.record(attributeNameSchema, attributeValueSchema),\n computedStyle: v.record(propertyNameSchema, shortStringSchema),\n box: v.optional(webCaptureBoxSchema),\n children: v.array(v.lazy(() => webCaptureNodeSchema))\n})\n\nconst webCaptureNodeSchema: v.GenericSchema<unknown, WebCaptureNode> = v.union([\n webCaptureTextSchema,\n webCaptureElementSchema\n])\n\nexport const webCaptureFontSchema = v.object({\n family: shortStringSchema,\n weight: shortStringSchema,\n style: shortStringSchema\n})\n\nexport const webCaptureViewportSchema = v.object({\n width: sizeSchema,\n height: sizeSchema,\n devicePixelRatio: v.pipe(v.number(), v.finite(), v.minValue(0))\n})\n\nconst webCaptureSourceSchema = v.object({\n url: v.optional(shortStringSchema),\n title: v.optional(shortStringSchema)\n})\n\n/** A page or element captured with the styles the browser computed for it. */\nexport const webCaptureSchema = v.object({\n format: v.literal(WEB_CAPTURE_FORMAT),\n version: v.literal(WEB_CAPTURE_VERSION),\n /** Whether a whole page or one element of it was captured. */\n scope: v.picklist(['page', 'element']),\n source: webCaptureSourceSchema,\n /** When the capture was made, as an ISO 8601 timestamp. */\n capturedAt: shortStringSchema,\n viewport: webCaptureViewportSchema,\n root: webCaptureElementSchema,\n fonts: v.array(webCaptureFontSchema),\n /** Whether the capturer stopped at its element limit, leaving later content out. */\n truncated: v.boolean()\n})\n","import { ownValue } from './record'\n\n/**\n * The computed properties a capture keeps for each element: those `@pairdraw/dom-css` builds\n * layers from, plus margins, which a capture turns into spacing when it is imported.\n */\nexport const CAPTURED_STYLE_PROPERTIES = [\n 'align-items',\n 'align-self',\n 'aspect-ratio',\n 'background-color',\n 'border-bottom-color',\n 'border-bottom-left-radius',\n 'border-bottom-right-radius',\n 'border-bottom-style',\n 'border-bottom-width',\n 'border-left-color',\n 'border-left-style',\n 'border-left-width',\n 'border-right-color',\n 'border-right-style',\n 'border-right-width',\n 'border-top-color',\n 'border-top-left-radius',\n 'border-top-right-radius',\n 'border-top-style',\n 'border-top-width',\n 'bottom',\n 'box-shadow',\n 'box-sizing',\n 'color',\n 'column-gap',\n 'display',\n 'flex-direction',\n 'flex-wrap',\n 'font-family',\n 'font-size',\n 'font-style',\n 'font-weight',\n 'gap',\n 'height',\n 'justify-content',\n 'left',\n 'letter-spacing',\n 'line-height',\n 'margin-bottom',\n 'margin-left',\n 'margin-right',\n 'margin-top',\n 'max-height',\n 'max-width',\n 'min-height',\n 'min-width',\n 'object-fit',\n 'opacity',\n 'overflow',\n 'padding-bottom',\n 'padding-left',\n 'padding-right',\n 'padding-top',\n 'position',\n 'right',\n 'row-gap',\n 'text-align',\n 'text-decoration-color',\n 'text-decoration-line',\n 'text-decoration-style',\n 'text-decoration-thickness',\n 'text-indent',\n 'text-shadow',\n 'text-transform',\n 'text-underline-offset',\n 'top',\n 'white-space',\n 'width'\n] as const\n\nexport type CapturedStyleProperty = (typeof CAPTURED_STYLE_PROPERTIES)[number]\n\nconst CAPTURED = new Set<string>(CAPTURED_STYLE_PROPERTIES)\n\n/** Whether a capture keeps this property; others are dropped when a capture is read. */\nexport function isCapturedStyleProperty(property: string): property is CapturedStyleProperty {\n return CAPTURED.has(property)\n}\n\nconst SIDES = ['top', 'right', 'bottom', 'left'] as const\n\n/**\n * Values the importer reads exactly as it reads a missing property, so leaving them out only\n * makes the capture smaller. Inherited text properties are always kept: a nested run reads\n * a missing one from its parent, which differs from the value the page computed.\n */\nconst IMPLIED_VALUES: Partial<Record<CapturedStyleProperty, readonly string[]>> = {\n 'align-items': ['normal'],\n 'align-self': ['auto'],\n 'aspect-ratio': ['auto'],\n 'background-color': ['rgba(0, 0, 0, 0)', 'transparent'],\n 'box-shadow': ['none'],\n 'column-gap': ['normal'],\n 'flex-direction': ['row'],\n 'flex-wrap': ['nowrap'],\n gap: ['normal'],\n height: ['auto'],\n 'justify-content': ['normal'],\n 'max-height': ['none'],\n 'max-width': ['none'],\n 'min-height': ['auto', '0px'],\n 'min-width': ['auto', '0px'],\n 'object-fit': ['fill'],\n opacity: ['1'],\n overflow: ['visible'],\n 'row-gap': ['normal'],\n 'text-indent': ['0px'],\n width: ['auto']\n}\n\nconst ZERO_LENGTH_PROPERTIES = [\n 'border-bottom-left-radius',\n 'border-bottom-right-radius',\n 'border-top-left-radius',\n 'border-top-right-radius',\n ...SIDES.map((side) => `padding-${side}` as const),\n ...SIDES.map((side) => `margin-${side}` as const)\n]\n\nconst TEXT_DECORATION_DETAILS = [\n 'text-decoration-color',\n 'text-decoration-style',\n 'text-decoration-thickness',\n 'text-underline-offset'\n]\n\n/**\n * The style without values that change nothing on import: defaults, borders without a style,\n * offsets of boxes in normal flow, and decoration details of undecorated text.\n */\nexport function withoutImpliedValues(style: Record<string, string>): Record<string, string> {\n const dropped = new Set<string>()\n for (const [property, values] of Object.entries(IMPLIED_VALUES)) {\n if (values.includes(ownValue(style, property) ?? '')) dropped.add(property)\n }\n for (const property of ZERO_LENGTH_PROPERTIES) {\n if (style[property] === '0px') dropped.add(property)\n }\n for (const side of SIDES) {\n const borderStyle = ownValue(style, `border-${side}-style`)\n if (borderStyle !== undefined && borderStyle !== 'none' && borderStyle !== 'hidden') continue\n for (const part of ['style', 'width', 'color']) dropped.add(`border-${side}-${part}`)\n }\n // Sticky boxes sit in normal flow until the page scrolls, which a still capture never does.\n const position = ownValue(style, 'position')\n const inFlow = position === undefined || position === 'static' || position === 'sticky'\n if (inFlow) dropped.add('position')\n for (const side of SIDES) {\n if (inFlow || style[side] === 'auto') dropped.add(side)\n }\n const decoration = ownValue(style, 'text-decoration-line')\n if (decoration === undefined || decoration === 'none') {\n for (const property of TEXT_DECORATION_DETAILS) dropped.add(property)\n }\n return Object.fromEntries(Object.entries(style).filter(([property]) => !dropped.has(property)))\n}\n","const LINK_PROTOCOLS = new Set(['http:', 'https:', 'mailto:'])\nconst IMAGE_PROTOCOLS = new Set(['http:', 'https:'])\n/** Raster images the canvas decodes; SVG is rasterized by the capturer instead. */\nconst DATA_IMAGE =\n /^data:image\\/(?:png|jpeg|gif|webp|avif|bmp|x-icon|vnd\\.microsoft\\.icon);base64,/i\n\nfunction resolve(value: string, base: string | undefined): URL | null {\n try {\n return new URL(value.trim(), base)\n } catch {\n return null\n }\n}\n\n/** A link a layer may keep: http, https, or mailto, resolved against the page; never script. */\nexport function safeLinkURL(value: string, base?: string): string | null {\n const url = resolve(value, base)\n return url && LINK_PROTOCOLS.has(url.protocol) ? url.href : null\n}\n\n/** An image source a layer may keep: an inlined raster image, or an http(s) address. */\nexport function safeImageSource(value: string, base?: string): string | null {\n const trimmed = value.trim()\n if (DATA_IMAGE.test(trimmed)) return trimmed\n const url = resolve(trimmed, base)\n return url && IMAGE_PROTOCOLS.has(url.protocol) ? url.href : null\n}\n","import * as v from 'valibot'\n\nimport type { WebCapture, WebCaptureReadResult } from './format'\nimport {\n MAX_CAPTURE_DEPTH,\n MAX_CAPTURE_ELEMENTS,\n MAX_CAPTURE_JSON_LENGTH,\n WEB_CAPTURE_FORMAT,\n WEB_CAPTURE_VERSION\n} from './limits'\nimport { webCaptureSchema } from './schema'\nimport { isCapturedStyleProperty } from './styles'\nimport type { WebCaptureElement, WebCaptureNode } from './types'\nimport { safeImageSource, safeLinkURL } from './urls'\n\n/** Read first, so a capture from a newer capturer is told apart from a damaged one. */\nconst captureHeaderSchema = v.looseObject({\n format: v.literal(WEB_CAPTURE_FORMAT),\n version: v.number()\n})\n\n/** Attributes a layer can use: names, links, images, and accessible labels. */\nconst KEPT_ATTRIBUTES = new Set([\n 'id',\n 'class',\n 'href',\n 'src',\n 'alt',\n 'title',\n 'role',\n 'aria-label',\n 'lang',\n 'dir'\n])\n\n/** Elements that never draw, whatever a capture claims. */\nconst DROPPED_TAGS = new Set([\n 'script',\n 'style',\n 'link',\n 'meta',\n 'head',\n 'title',\n 'template',\n 'noscript',\n 'iframe',\n 'frame',\n 'object',\n 'embed',\n 'base'\n])\n\n/**\n * JSON nesting a capture within `MAX_CAPTURE_DEPTH` takes: an object and a `children` array per\n * element, the capture around the root, and the records of the deepest element, with room to\n * spare. Deeper values are refused before validation, whose recursion they could overflow.\n */\nconst MAX_JSON_NESTING = 2 * MAX_CAPTURE_DEPTH + 16\n\n/** Whether a value nests deeper than `limit`, walked without recursion; a cycle counts as deep. */\nfunction nestsDeeperThan(value: unknown, limit: number): boolean {\n const pending: { value: unknown; depth: number }[] = [{ value, depth: 0 }]\n for (let next = pending.pop(); next; next = pending.pop()) {\n if (typeof next.value !== 'object' || next.value === null) continue\n if (next.depth >= limit) return true\n const depth = next.depth + 1\n for (const child of Object.values(next.value)) pending.push({ value: child, depth })\n }\n return false\n}\n\ninterface Budget {\n elements: number\n truncated: boolean\n}\n\nfunction keptAttributes(\n attrs: Record<string, string>,\n base: string | undefined\n): Record<string, string> {\n const kept: Record<string, string> = {}\n for (const [name, value] of Object.entries(attrs)) {\n if (!KEPT_ATTRIBUTES.has(name)) continue\n if (name === 'href') {\n const href = safeLinkURL(value, base)\n if (href) kept.href = href\n } else if (name === 'src') {\n const src = safeImageSource(value, base)\n if (src) kept.src = src\n } else {\n kept[name] = value\n }\n }\n return kept\n}\n\nfunction keptStyle(style: Record<string, string>): Record<string, string> {\n return Object.fromEntries(\n Object.entries(style).filter(([property]) => isCapturedStyleProperty(property))\n )\n}\n\nfunction normalizeElement(\n element: WebCaptureElement,\n base: string | undefined,\n depth: number,\n budget: Budget\n): WebCaptureElement {\n const children: WebCaptureNode[] = []\n for (const child of element.children) {\n if (child.type === 'text') {\n children.push(child)\n continue\n }\n if (DROPPED_TAGS.has(child.tagName)) continue\n if (depth + 1 > MAX_CAPTURE_DEPTH || budget.elements >= MAX_CAPTURE_ELEMENTS) {\n budget.truncated = true\n continue\n }\n budget.elements++\n children.push(normalizeElement(child, base, depth + 1, budget))\n }\n return {\n type: 'element',\n tagName: element.tagName,\n attrs: keptAttributes(element.attrs, base),\n computedStyle: keptStyle(element.computedStyle),\n ...(element.box ? { box: element.box } : {}),\n children\n }\n}\n\n/**\n * A capture as an import may use it: only the attributes and properties layers read, links\n * limited to http, https, and mailto, images limited to raster data URLs and http(s) addresses,\n * and at most `MAX_CAPTURE_ELEMENTS` elements. Captures come from any page, so every reader\n * goes through this.\n */\nexport function normalizeWebCapture(capture: WebCapture): WebCapture {\n const budget: Budget = { elements: 1, truncated: false }\n const base = capture.source.url\n const root = normalizeElement(capture.root, base, 0, budget)\n return { ...capture, root, truncated: capture.truncated || budget.truncated }\n}\n\n/** Reads a capture that is already a value, such as one a capturer handed over. */\nexport function readWebCapture(value: unknown): WebCaptureReadResult {\n if (nestsDeeperThan(value, MAX_JSON_NESTING)) return { ok: false, error: 'invalid' }\n const header = v.safeParse(captureHeaderSchema, value)\n if (!header.success) return { ok: false, error: 'invalid' }\n if (header.output.version !== WEB_CAPTURE_VERSION) {\n return { ok: false, error: 'unsupported-version' }\n }\n const parsed = v.safeParse(webCaptureSchema, value)\n if (!parsed.success) return { ok: false, error: 'invalid' }\n return { ok: true, capture: normalizeWebCapture(parsed.output) }\n}\n\n/** Reads a capture serialized as JSON, as files and clipboard payloads hold it. */\nexport function parseWebCapture(text: string): WebCaptureReadResult {\n if (text.length > MAX_CAPTURE_JSON_LENGTH) return { ok: false, error: 'too-large' }\n const json = v.safeParse(v.pipe(v.string(), v.parseJson()), text)\n if (!json.success) return { ok: false, error: 'invalid' }\n return readWebCapture(json.output)\n}\n","import { compact } from 'es-toolkit'\nimport { Inflate, deflateSync, strToU8 } from 'fflate'\nimport { fromUint8Array, isValid, toUint8Array } from 'js-base64'\n\nimport type { WebCapture, WebCaptureReadResult } from './format'\nimport { webCaptureToHTML } from './html'\nimport { MAX_CAPTURE_JSON_LENGTH } from './limits'\nimport { normalizeWebCapture, parseWebCapture } from './parse'\n\n/**\n * Clipboard HTML carries a capture between these markers, as Base64 of the DEFLATE-compressed\n * JSON, the way Figma and Pairdraw carry their layers in an HTML comment.\n */\nexport const WEB_CAPTURE_CLIPBOARD_START = '<!--(pairdraw-web-capture)'\nexport const WEB_CAPTURE_CLIPBOARD_END = '(/pairdraw-web-capture)-->'\n\n/** Compressed bytes inflated per step, so an oversized payload stops early. */\nconst INFLATE_STEP = 16 * 1024\n\nexport interface WebCaptureClipboardPayload {\n /** The capture in markers, followed by its content as styled HTML for other applications. */\n html: string\n /** The page's title and address, for applications that only read text. */\n text: string\n}\n\n/** What the clipboard holds after copying a capture: the capture itself and a readable copy. */\nexport function encodeWebCaptureClipboard(captured: WebCapture): WebCaptureClipboardPayload {\n const capture = normalizeWebCapture(captured)\n const compressed = deflateSync(strToU8(JSON.stringify(capture)), { level: 6 })\n const marker = `${WEB_CAPTURE_CLIPBOARD_START}${fromUint8Array(compressed)}${WEB_CAPTURE_CLIPBOARD_END}`\n const html = `<meta charset=\"utf-8\">${marker}${webCaptureToHTML(capture, { images: false })}`\n const text = compact([capture.source.title, capture.source.url]).join('\\n')\n return { html, text }\n}\n\nfunction markedPayload(html: string): string | null {\n const start = html.indexOf(WEB_CAPTURE_CLIPBOARD_START)\n if (start === -1) return null\n const from = start + WEB_CAPTURE_CLIPBOARD_START.length\n const end = html.indexOf(WEB_CAPTURE_CLIPBOARD_END, from)\n return end === -1 ? null : html.slice(from, end)\n}\n\n/** Whether clipboard HTML holds a complete capture marker. */\nexport function hasWebCaptureClipboardMarker(html: string): boolean {\n return markedPayload(html) !== null\n}\n\n/** Inflates at most `MAX_CAPTURE_JSON_LENGTH` bytes of text. */\nfunction inflateText(bytes: Uint8Array): { text: string } | 'invalid' | 'too-large' {\n const decoder = new TextDecoder()\n // An object, since the inflate callback changes it where control flow analysis cannot see.\n const state = { text: '', length: 0, overflow: false }\n const inflate = new Inflate((chunk) => {\n state.length += chunk.length\n if (state.length > MAX_CAPTURE_JSON_LENGTH) state.overflow = true\n else state.text += decoder.decode(chunk, { stream: true })\n })\n try {\n for (let offset = 0; offset < bytes.length; offset += INFLATE_STEP) {\n if (state.overflow) break\n const end = offset + INFLATE_STEP\n inflate.push(bytes.subarray(offset, end), end >= bytes.length)\n }\n } catch {\n return 'invalid'\n }\n return state.overflow ? 'too-large' : { text: state.text + decoder.decode() }\n}\n\n/**\n * The capture clipboard HTML holds, or null when it holds none. Clipboard HTML is writable by\n * any page, so the payload is size-limited, validated, and normalized before it is returned.\n */\nexport function readWebCaptureClipboard(html: string): WebCaptureReadResult | null {\n const payload = markedPayload(html)\n if (payload === null) return null\n const encoded = payload.trim()\n if (encoded.length > MAX_CAPTURE_JSON_LENGTH) return { ok: false, error: 'too-large' }\n if (!isValid(encoded)) return { ok: false, error: 'invalid' }\n const inflated = inflateText(toUint8Array(encoded))\n if (typeof inflated === 'string') return { ok: false, error: inflated }\n return parseWebCapture(inflated.text)\n}\n","import { encodeWebCaptureClipboard, type WebCaptureClipboardPayload } from '#web-capture/clipboard'\nimport type { WebCapture } from '#web-capture/format'\n\n/** The part of the asynchronous clipboard a capture write uses. */\nexport type CaptureClipboard = Pick<Clipboard, 'write'>\n\nexport interface WriteCaptureClipboardOptions {\n /** The clipboard to write; the page's own by default. */\n clipboard?: CaptureClipboard\n /** Builds a clipboard item; the page's `ClipboardItem` by default. */\n createItem?: (items: Record<string, Promise<Blob>>) => ClipboardItem\n}\n\n/** Thrown when the page has no asynchronous clipboard, which only secure pages offer. */\nexport class CaptureClipboardUnavailableError extends Error {\n constructor() {\n super('Copying a capture needs a page served over HTTPS')\n this.name = 'CaptureClipboardUnavailableError'\n }\n}\n\nfunction isPayload(\n value: WebCapture | WebCaptureClipboardPayload\n): value is WebCaptureClipboardPayload {\n return 'html' in value && 'text' in value\n}\n\n/**\n * Copies a capture so it pastes into a Pairdraw canvas, as HTML for Pairdraw and other\n * applications and as the page's title and address for plain text. Pass the capture's promise\n * straight from the click that asked for it: the write starts inside that click and resolves\n * its data later, so a capture that takes a while still counts as the click's own.\n */\nexport async function writeWebCaptureClipboard(\n capture:\n | WebCapture\n | WebCaptureClipboardPayload\n | Promise<WebCapture | WebCaptureClipboardPayload>,\n options: WriteCaptureClipboardOptions = {}\n): Promise<void> {\n const clipboard =\n options.clipboard ?? (typeof navigator === 'undefined' ? undefined : navigator.clipboard)\n const createItem =\n options.createItem ??\n (typeof ClipboardItem === 'undefined'\n ? undefined\n : (items: Record<string, Promise<Blob>>) => new ClipboardItem(items))\n // `navigator.clipboard` is missing outside secure contexts.\n if (!clipboard || !createItem) throw new CaptureClipboardUnavailableError()\n const payload = Promise.resolve(capture).then((value) =>\n isPayload(value) ? value : encodeWebCaptureClipboard(value)\n )\n await clipboard.write([\n createItem({\n 'text/html': payload.then((value) => new Blob([value.html], { type: 'text/html' })),\n 'text/plain': payload.then((value) => new Blob([value.text], { type: 'text/plain' }))\n })\n ])\n}\n"],"mappings":";;;;;;;;;;AAIA,SAAgB,SACd,QACA,KACoB;CACpB,OAAO,OAAO,OAAO,QAAQ,GAAG,IAAI,OAAO,OAAO,KAAA;AACpD;;;ACHA,MAAM,4BAAY,IAAI,IAAI;CAAC;CAAQ;CAAM;CAAO;CAAM;CAAO;CAAS;CAAU;AAAK,CAAC;AAOtF,SAAS,eAAe,OAAuC;CAC7D,OAAO,OAAO,QAAQ,KAAK,CAAC,CACzB,KAAK,CAAC,UAAU,WAAW,GAAG,SAAS,IAAI,OAAO,CAAC,CACnD,KAAK,IAAI;AACd;AAEA,SAAS,WAAW,SAA4B,SAAwC;CACtF,MAAM,QAAgC,EAAE,GAAG,QAAQ,MAAM;CACzD,IAAI,QAAQ,WAAW,SAAS,SAAS,OAAO,KAAK,CAAC,EAAE,WAAW,OAAO,GAAG,OAAO,MAAM;CAC1F,MAAM,QAAQ,eAAe,QAAQ,aAAa;CAClD,IAAI,OAAO,MAAM,QAAQ;CACzB,OAAO,OAAO,QAAQ,KAAK,CAAC,CACzB,KAAK,CAAC,MAAM,WAAW,IAAI,KAAK,IAAI,gBAAgB,KAAK,EAAE,EAAE,CAAC,CAC9D,KAAK,EAAE;AACZ;AAEA,SAAS,UAAU,MAAsB,SAAwC;CAC/E,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AO;CACd;AACF;AAEA,SAAS,UACP,OACqC;CACrC,OAAO,UAAU,SAAS,UAAU;AACtC;;;;;;;AAQA,eAAsB,yBACpB,SAIA,UAAwC,CAAC,GAC1B;CACf,MAAM,YACJ,QAAQ,cAAc,OAAO,cAAc,cAAc,KAAA,IAAY,UAAU;CACjF,MAAM,aACJ,QAAQ,eACP,OAAO,kBAAkB,cACtB,KAAA,KACC,UAAyC,IAAI,cAAc,KAAK;CAEvE,IAAI,CAAC,aAAa,CAAC,YAAY,MAAM,IAAI,iCAAiC;CAC1E,MAAM,UAAU,QAAQ,QAAQ,OAAO,CAAC,CAAC,MAAM,UAC7C,UAAU,KAAK,IAAI,QAAQ,0BAA0B,KAAK,CAC5D;CACA,MAAM,UAAU,MAAM,CACpB,WAAW;EACT,aAAa,QAAQ,MAAM,UAAU,IAAI,KAAK,CAAC,MAAM,IAAI,GAAG,EAAE,MAAM,YAAY,CAAC,CAAC;EAClF,cAAc,QAAQ,MAAM,UAAU,IAAI,KAAK,CAAC,MAAM,IAAI,GAAG,EAAE,MAAM,aAAa,CAAC,CAAC;CACtF,CAAC,CACH,CAAC;AACH"}
1
+ {"version":3,"file":"clipboard.js","names":[],"sources":["../../../src/record.ts","../../../src/html.ts","../../../src/limits.ts","../../../src/schema.ts","../../../src/styles.ts","../../../src/urls.ts","../../../src/parse.ts","../../../src/clipboard.ts","../../../src/capturer/clipboard.ts"],"sourcesContent":["/**\n * The value a style or attribute record sets for `key`, or undefined when it sets none. Records\n * are typed as setting every key, which they do not.\n */\nexport function ownValue(\n record: Readonly<Record<string, string>>,\n key: string\n): string | undefined {\n return Object.hasOwn(record, key) ? record[key] : undefined\n}\n","import { escapeAttribute, escapeText } from 'entities'\n\nimport type { WebCapture } from './format'\nimport { ownValue } from './record'\nimport type { WebCaptureElement, WebCaptureNode } from './types'\n\nconst VOID_TAGS = new Set(['area', 'br', 'col', 'hr', 'img', 'input', 'source', 'wbr'])\n\nexport interface WebCaptureHTMLOptions {\n /** Keep inlined images; without them an image keeps only its size and description. */\n images?: boolean\n}\n\nfunction styleAttribute(style: Record<string, string>): string {\n return Object.entries(style)\n .map(([property, value]) => `${property}: ${value}`)\n .join('; ')\n}\n\nfunction attributes(element: WebCaptureElement, options: WebCaptureHTMLOptions): string {\n const attrs: Record<string, string> = { ...element.attrs }\n if (options.images === false && ownValue(attrs, 'src')?.startsWith('data:')) delete attrs.src\n const style = styleAttribute(element.computedStyle)\n if (style) attrs.style = style\n return Object.entries(attrs)\n .map(([name, value]) => ` ${name}=\"${escapeAttribute(value)}\"`)\n .join('')\n}\n\nfunction serialize(node: WebCaptureNode, options: WebCaptureHTMLOptions): string {\n if (node.type === 'text') return escapeText(node.text)\n const open = `<${node.tagName}${attributes(node, options)}>`\n if (VOID_TAGS.has(node.tagName)) return open\n const children = node.children.map((child) => serialize(child, options)).join('')\n return `${open}${children}</${node.tagName}>`\n}\n\n/**\n * The capture as static HTML whose elements carry their computed styles inline, for\n * applications that read clipboard HTML but not the capture itself.\n */\nexport function webCaptureToHTML(capture: WebCapture, options: WebCaptureHTMLOptions = {}): string {\n return serialize(capture.root, options)\n}\n","/** The capture format identifier that clipboard payloads and files carry. */\nexport const WEB_CAPTURE_FORMAT = 'pairdraw/web-capture'\n\n/** The capture format version this package writes and reads. */\nexport const WEB_CAPTURE_VERSION = 1\n\n/** Elements one capture holds at most; a capturer stops descending once it reaches this. */\nexport const MAX_CAPTURE_ELEMENTS = 20_000\n\n/** How deep a capture nests; deeper elements are left out, as browsers rarely draw them. */\nexport const MAX_CAPTURE_DEPTH = 256\n\n/** Bytes one inlined image may take; a larger image stays a link the importer records. */\nexport const MAX_CAPTURE_IMAGE_BYTES = 8 * 1024 * 1024\n\n/** Bytes all inlined images of a capture take together. */\nexport const MAX_CAPTURE_IMAGES_BYTES = 48 * 1024 * 1024\n\n/** Characters of serialized capture JSON a reader accepts, images included. */\nexport const MAX_CAPTURE_JSON_LENGTH = 96 * 1024 * 1024\n\n/** Characters of plain web HTML a paste styles; a larger fragment is refused. */\nexport const MAX_WEB_HTML_LENGTH = 8 * 1024 * 1024\n","import * as v from 'valibot'\n\nimport { MAX_CAPTURE_JSON_LENGTH, WEB_CAPTURE_FORMAT, WEB_CAPTURE_VERSION } from './limits'\nimport type { WebCaptureElement, WebCaptureNode } from './types'\n\nconst finiteSchema = v.pipe(v.number(), v.finite())\nconst sizeSchema = v.pipe(v.number(), v.finite(), v.minValue(0))\nconst shortStringSchema = v.pipe(v.string(), v.maxLength(4096))\n\nconst webCaptureBoxSchema = v.object({\n x: finiteSchema,\n y: finiteSchema,\n width: sizeSchema,\n height: sizeSchema\n})\n\nconst webCaptureTextSchema = v.object({\n type: v.literal('text'),\n text: v.pipe(v.string(), v.maxLength(1_000_000))\n})\n\n/** HTML and SVG tag names, lowercase as a capturer writes them. */\nconst tagNameSchema = v.pipe(v.string(), v.regex(/^[a-z][a-z0-9-]{0,63}$/))\n/** Attribute names; which of them an import keeps is decided when a capture is read. */\nconst attributeNameSchema = v.pipe(v.string(), v.regex(/^[a-z][a-z0-9:_-]{0,63}$/))\n/** Attribute values hold inlined images as data URLs, so they may be large. */\nconst attributeValueSchema = v.pipe(v.string(), v.maxLength(MAX_CAPTURE_JSON_LENGTH))\nconst propertyNameSchema = v.pipe(v.string(), v.regex(/^-?[a-z][a-z-]{0,63}$/))\n\nconst webCaptureElementSchema: v.GenericSchema<unknown, WebCaptureElement> = v.object({\n type: v.literal('element'),\n tagName: tagNameSchema,\n attrs: v.record(attributeNameSchema, attributeValueSchema),\n computedStyle: v.record(propertyNameSchema, shortStringSchema),\n box: v.optional(webCaptureBoxSchema),\n children: v.array(v.lazy(() => webCaptureNodeSchema))\n})\n\nconst webCaptureNodeSchema: v.GenericSchema<unknown, WebCaptureNode> = v.union([\n webCaptureTextSchema,\n webCaptureElementSchema\n])\n\nexport const webCaptureFontSchema = v.object({\n family: shortStringSchema,\n weight: shortStringSchema,\n style: shortStringSchema\n})\n\nexport const webCaptureViewportSchema = v.object({\n width: sizeSchema,\n height: sizeSchema,\n devicePixelRatio: v.pipe(v.number(), v.finite(), v.minValue(0))\n})\n\nconst webCaptureSourceSchema = v.object({\n url: v.optional(shortStringSchema),\n title: v.optional(shortStringSchema)\n})\n\n/** A page or element captured with the styles the browser computed for it. */\nexport const webCaptureSchema = v.object({\n format: v.literal(WEB_CAPTURE_FORMAT),\n version: v.literal(WEB_CAPTURE_VERSION),\n /** Whether a whole page or one element of it was captured. */\n scope: v.picklist(['page', 'element']),\n source: webCaptureSourceSchema,\n /** When the capture was made, as an ISO 8601 timestamp. */\n capturedAt: shortStringSchema,\n viewport: webCaptureViewportSchema,\n root: webCaptureElementSchema,\n fonts: v.array(webCaptureFontSchema),\n /** Whether the capturer stopped at its element limit, leaving later content out. */\n truncated: v.boolean()\n})\n","import { ownValue } from './record'\n\n/**\n * The computed properties a capture keeps for each element: those `@pairdraw/dom-css` builds\n * layers from, plus margins, which a capture turns into spacing when it is imported.\n */\nexport const CAPTURED_STYLE_PROPERTIES = [\n 'align-items',\n 'align-self',\n 'aspect-ratio',\n 'background-color',\n 'background-image',\n 'background-position',\n 'background-repeat',\n 'background-size',\n 'border-bottom-color',\n 'border-bottom-left-radius',\n 'border-bottom-right-radius',\n 'border-bottom-style',\n 'border-bottom-width',\n 'border-left-color',\n 'border-left-style',\n 'border-left-width',\n 'border-right-color',\n 'border-right-style',\n 'border-right-width',\n 'border-top-color',\n 'border-top-left-radius',\n 'border-top-right-radius',\n 'border-top-style',\n 'border-top-width',\n 'bottom',\n 'box-shadow',\n 'box-sizing',\n 'color',\n 'column-gap',\n 'display',\n 'flex-direction',\n 'flex-wrap',\n 'font-family',\n 'font-size',\n 'font-style',\n 'font-weight',\n 'gap',\n 'height',\n 'justify-content',\n 'left',\n 'letter-spacing',\n 'line-height',\n 'margin-bottom',\n 'margin-left',\n 'margin-right',\n 'margin-top',\n 'max-height',\n 'max-width',\n 'min-height',\n 'min-width',\n 'object-fit',\n 'opacity',\n 'overflow',\n 'padding-bottom',\n 'padding-left',\n 'padding-right',\n 'padding-top',\n 'position',\n 'right',\n 'row-gap',\n 'text-align',\n 'text-decoration-color',\n 'text-decoration-line',\n 'text-decoration-style',\n 'text-decoration-thickness',\n 'text-indent',\n 'text-shadow',\n 'text-transform',\n 'text-underline-offset',\n 'top',\n 'white-space',\n 'width'\n] as const\n\nexport type CapturedStyleProperty = (typeof CAPTURED_STYLE_PROPERTIES)[number]\n\nconst CAPTURED = new Set<string>(CAPTURED_STYLE_PROPERTIES)\n\n/** Whether a capture keeps this property; others are dropped when a capture is read. */\nexport function isCapturedStyleProperty(property: string): property is CapturedStyleProperty {\n return CAPTURED.has(property)\n}\n\nconst SIDES = ['top', 'right', 'bottom', 'left'] as const\n\n/**\n * Values the importer reads exactly as it reads a missing property, so leaving them out only\n * makes the capture smaller. Inherited text properties are always kept: a nested run reads\n * a missing one from its parent, which differs from the value the page computed.\n */\nconst IMPLIED_VALUES: Partial<Record<CapturedStyleProperty, readonly string[]>> = {\n 'align-items': ['normal'],\n 'align-self': ['auto'],\n 'aspect-ratio': ['auto'],\n 'background-color': ['rgba(0, 0, 0, 0)', 'transparent'],\n 'background-image': ['none'],\n 'background-position': ['0% 0%'],\n 'background-repeat': ['repeat'],\n 'background-size': ['auto'],\n 'box-shadow': ['none'],\n 'column-gap': ['normal'],\n 'flex-direction': ['row'],\n 'flex-wrap': ['nowrap'],\n gap: ['normal'],\n height: ['auto'],\n 'justify-content': ['normal'],\n 'max-height': ['none'],\n 'max-width': ['none'],\n 'min-height': ['auto', '0px'],\n 'min-width': ['auto', '0px'],\n 'object-fit': ['fill'],\n opacity: ['1'],\n overflow: ['visible'],\n 'row-gap': ['normal'],\n 'text-indent': ['0px'],\n width: ['auto']\n}\n\nconst ZERO_LENGTH_PROPERTIES = [\n 'border-bottom-left-radius',\n 'border-bottom-right-radius',\n 'border-top-left-radius',\n 'border-top-right-radius',\n ...SIDES.map((side) => `padding-${side}` as const),\n ...SIDES.map((side) => `margin-${side}` as const)\n]\n\nconst TEXT_DECORATION_DETAILS = [\n 'text-decoration-color',\n 'text-decoration-style',\n 'text-decoration-thickness',\n 'text-underline-offset'\n]\n\n/**\n * The style without values that change nothing on import: defaults, borders without a style,\n * offsets of boxes in normal flow, and decoration details of undecorated text.\n */\nexport function withoutImpliedValues(style: Record<string, string>): Record<string, string> {\n const dropped = new Set<string>()\n for (const [property, values] of Object.entries(IMPLIED_VALUES)) {\n if (values.includes(ownValue(style, property) ?? '')) dropped.add(property)\n }\n for (const property of ZERO_LENGTH_PROPERTIES) {\n if (style[property] === '0px') dropped.add(property)\n }\n for (const side of SIDES) {\n const borderStyle = ownValue(style, `border-${side}-style`)\n if (borderStyle !== undefined && borderStyle !== 'none' && borderStyle !== 'hidden') continue\n for (const part of ['style', 'width', 'color']) dropped.add(`border-${side}-${part}`)\n }\n // Sticky boxes sit in normal flow until the page scrolls, which a still capture never does.\n const position = ownValue(style, 'position')\n const inFlow = position === undefined || position === 'static' || position === 'sticky'\n if (inFlow) dropped.add('position')\n for (const side of SIDES) {\n if (inFlow || style[side] === 'auto') dropped.add(side)\n }\n const decoration = ownValue(style, 'text-decoration-line')\n if (decoration === undefined || decoration === 'none') {\n for (const property of TEXT_DECORATION_DETAILS) dropped.add(property)\n }\n return Object.fromEntries(Object.entries(style).filter(([property]) => !dropped.has(property)))\n}\n","const LINK_PROTOCOLS = new Set(['http:', 'https:', 'mailto:'])\nconst IMAGE_PROTOCOLS = new Set(['http:', 'https:'])\n/** Raster images the canvas decodes; SVG is rasterized by the capturer instead. */\nconst DATA_IMAGE =\n /^data:image\\/(?:png|jpeg|gif|webp|avif|bmp|x-icon|vnd\\.microsoft\\.icon);base64,/i\n\nfunction resolve(value: string, base: string | undefined): URL | null {\n try {\n return new URL(value.trim(), base)\n } catch {\n return null\n }\n}\n\n/** A link a layer may keep: http, https, or mailto, resolved against the page; never script. */\nexport function safeLinkURL(value: string, base?: string): string | null {\n const url = resolve(value, base)\n return url && LINK_PROTOCOLS.has(url.protocol) ? url.href : null\n}\n\n/** An image source a layer may keep: an inlined raster image, or an http(s) address. */\nexport function safeImageSource(value: string, base?: string): string | null {\n const trimmed = value.trim()\n if (DATA_IMAGE.test(trimmed)) return trimmed\n const url = resolve(trimmed, base)\n return url && IMAGE_PROTOCOLS.has(url.protocol) ? url.href : null\n}\n","import * as v from 'valibot'\n\nimport type { WebCapture, WebCaptureReadResult } from './format'\nimport {\n MAX_CAPTURE_DEPTH,\n MAX_CAPTURE_ELEMENTS,\n MAX_CAPTURE_JSON_LENGTH,\n WEB_CAPTURE_FORMAT,\n WEB_CAPTURE_VERSION\n} from './limits'\nimport { webCaptureSchema } from './schema'\nimport { isCapturedStyleProperty } from './styles'\nimport type { WebCaptureElement, WebCaptureNode } from './types'\nimport { safeImageSource, safeLinkURL } from './urls'\n\n/** Read first, so a capture from a newer capturer is told apart from a damaged one. */\nconst captureHeaderSchema = v.looseObject({\n format: v.literal(WEB_CAPTURE_FORMAT),\n version: v.number()\n})\n\n/** Attributes a layer can use: names, links, images, control kinds, and accessible labels. */\nconst KEPT_ATTRIBUTES = new Set([\n 'id',\n 'class',\n 'href',\n 'src',\n 'alt',\n 'title',\n 'type',\n 'role',\n 'aria-label',\n 'lang',\n 'dir'\n])\n\n/** Elements that never draw, whatever a capture claims. */\nconst DROPPED_TAGS = new Set([\n 'script',\n 'style',\n 'link',\n 'meta',\n 'head',\n 'title',\n 'template',\n 'noscript',\n 'iframe',\n 'frame',\n 'object',\n 'embed',\n 'base'\n])\n\n/**\n * JSON nesting a capture within `MAX_CAPTURE_DEPTH` takes: an object and a `children` array per\n * element, the capture around the root, and the records of the deepest element, with room to\n * spare. Deeper values are refused before validation, whose recursion they could overflow.\n */\nconst MAX_JSON_NESTING = 2 * MAX_CAPTURE_DEPTH + 16\n\n/** Whether a value nests deeper than `limit`, walked without recursion; a cycle counts as deep. */\nfunction nestsDeeperThan(value: unknown, limit: number): boolean {\n const pending: { value: unknown; depth: number }[] = [{ value, depth: 0 }]\n for (let next = pending.pop(); next; next = pending.pop()) {\n if (typeof next.value !== 'object' || next.value === null) continue\n if (next.depth >= limit) return true\n const depth = next.depth + 1\n for (const child of Object.values(next.value)) pending.push({ value: child, depth })\n }\n return false\n}\n\ninterface Budget {\n elements: number\n truncated: boolean\n}\n\nfunction keptAttributes(\n attrs: Record<string, string>,\n base: string | undefined\n): Record<string, string> {\n const kept: Record<string, string> = {}\n for (const [name, value] of Object.entries(attrs)) {\n if (!KEPT_ATTRIBUTES.has(name)) continue\n if (name === 'href') {\n const href = safeLinkURL(value, base)\n if (href) kept.href = href\n } else if (name === 'src') {\n const src = safeImageSource(value, base)\n if (src) kept.src = src\n } else {\n kept[name] = value\n }\n }\n return kept\n}\n\n/** The `url(...)` sources of a value, with the spans they occupy. */\nconst BACKGROUND_URL = /url\\(\\s*(['\"]?)(.*?)\\1\\s*\\)/g\n\n/**\n * A `background-image` list with every `url(...)` source limited to what an image layer may\n * keep; a layer whose source is unsafe is dropped, and a list left empty paints nothing.\n * Gradient layers carry no address and pass through as written.\n */\nfunction keptBackgroundImage(value: string, base: string | undefined): string | null {\n const layers: string[] = []\n let cursor = 0\n let dropped = false\n for (const match of value.matchAll(BACKGROUND_URL)) {\n const source = safeImageSource(match[2], base)\n if (source) layers.push(value.slice(cursor, match.index) + `url(\"${source}\")`)\n else dropped = true\n cursor = match.index + match[0].length\n }\n if (cursor === 0 && !dropped) return value\n layers.push(value.slice(cursor))\n // Split at top-level commas only: a gradient's own commas stay inside its parentheses.\n const kept: string[] = []\n let depth = 0\n let current = ''\n for (const character of layers.join('')) {\n if (character === '(') depth++\n else if (character === ')') depth--\n if (character === ',' && depth === 0) {\n kept.push(current)\n current = ''\n continue\n }\n current += character\n }\n kept.push(current)\n const painted = kept\n .map((layer) => layer.trim())\n .filter((layer) => layer.length > 0 && layer !== 'none')\n return painted.length > 0 ? painted.join(', ') : null\n}\n\nfunction keptStyle(\n style: Record<string, string>,\n base: string | undefined\n): Record<string, string> {\n const kept: Record<string, string> = {}\n for (const [property, value] of Object.entries(style)) {\n if (!isCapturedStyleProperty(property)) continue\n if (property === 'background-image') {\n const image = keptBackgroundImage(value, base)\n if (image) kept[property] = image\n continue\n }\n kept[property] = value\n }\n return kept\n}\n\nfunction normalizeElement(\n element: WebCaptureElement,\n base: string | undefined,\n depth: number,\n budget: Budget\n): WebCaptureElement {\n const children: WebCaptureNode[] = []\n for (const child of element.children) {\n if (child.type === 'text') {\n children.push(child)\n continue\n }\n if (DROPPED_TAGS.has(child.tagName)) continue\n if (depth + 1 > MAX_CAPTURE_DEPTH || budget.elements >= MAX_CAPTURE_ELEMENTS) {\n budget.truncated = true\n continue\n }\n budget.elements++\n children.push(normalizeElement(child, base, depth + 1, budget))\n }\n return {\n type: 'element',\n tagName: element.tagName,\n attrs: keptAttributes(element.attrs, base),\n ...(element.box ? { box: element.box } : {}),\n computedStyle: keptStyle(element.computedStyle, base),\n children\n }\n}\n\n/**\n * A capture as an import may use it: only the attributes and properties layers read, links\n * limited to http, https, and mailto, images limited to raster data URLs and http(s) addresses,\n * and at most `MAX_CAPTURE_ELEMENTS` elements. Captures come from any page, so every reader\n * goes through this.\n */\nexport function normalizeWebCapture(capture: WebCapture): WebCapture {\n const budget: Budget = { elements: 1, truncated: false }\n const base = capture.source.url\n const root = normalizeElement(capture.root, base, 0, budget)\n return { ...capture, root, truncated: capture.truncated || budget.truncated }\n}\n\n/** Reads a capture that is already a value, such as one a capturer handed over. */\nexport function readWebCapture(value: unknown): WebCaptureReadResult {\n if (nestsDeeperThan(value, MAX_JSON_NESTING)) return { ok: false, error: 'invalid' }\n const header = v.safeParse(captureHeaderSchema, value)\n if (!header.success) return { ok: false, error: 'invalid' }\n if (header.output.version !== WEB_CAPTURE_VERSION) {\n return { ok: false, error: 'unsupported-version' }\n }\n const parsed = v.safeParse(webCaptureSchema, value)\n if (!parsed.success) return { ok: false, error: 'invalid' }\n return { ok: true, capture: normalizeWebCapture(parsed.output) }\n}\n\n/** Reads a capture serialized as JSON, as files and clipboard payloads hold it. */\nexport function parseWebCapture(text: string): WebCaptureReadResult {\n if (text.length > MAX_CAPTURE_JSON_LENGTH) return { ok: false, error: 'too-large' }\n const json = v.safeParse(v.pipe(v.string(), v.parseJson()), text)\n if (!json.success) return { ok: false, error: 'invalid' }\n return readWebCapture(json.output)\n}\n","import { compact } from 'es-toolkit'\nimport { Inflate, deflateSync, strToU8 } from 'fflate'\nimport { fromUint8Array, isValid, toUint8Array } from 'js-base64'\n\nimport type { WebCapture, WebCaptureReadResult } from './format'\nimport { webCaptureToHTML } from './html'\nimport { MAX_CAPTURE_JSON_LENGTH } from './limits'\nimport { normalizeWebCapture, parseWebCapture } from './parse'\n\n/**\n * Clipboard HTML carries a capture between these markers, as Base64 of the DEFLATE-compressed\n * JSON, the way Figma and Pairdraw carry their layers in an HTML comment.\n */\nexport const WEB_CAPTURE_CLIPBOARD_START = '<!--(pairdraw-web-capture)'\nexport const WEB_CAPTURE_CLIPBOARD_END = '(/pairdraw-web-capture)-->'\n\n/** Compressed bytes inflated per step, so an oversized payload stops early. */\nconst INFLATE_STEP = 16 * 1024\n\nexport interface WebCaptureClipboardPayload {\n /** The capture in markers, followed by its content as styled HTML for other applications. */\n html: string\n /** The page's title and address, for applications that only read text. */\n text: string\n}\n\n/** What the clipboard holds after copying a capture: the capture itself and a readable copy. */\nexport function encodeWebCaptureClipboard(captured: WebCapture): WebCaptureClipboardPayload {\n const capture = normalizeWebCapture(captured)\n const compressed = deflateSync(strToU8(JSON.stringify(capture)), { level: 6 })\n const marker = `${WEB_CAPTURE_CLIPBOARD_START}${fromUint8Array(compressed)}${WEB_CAPTURE_CLIPBOARD_END}`\n const html = `<meta charset=\"utf-8\">${marker}${webCaptureToHTML(capture, { images: false })}`\n const text = compact([capture.source.title, capture.source.url]).join('\\n')\n return { html, text }\n}\n\nfunction markedPayload(html: string): string | null {\n const start = html.indexOf(WEB_CAPTURE_CLIPBOARD_START)\n if (start === -1) return null\n const from = start + WEB_CAPTURE_CLIPBOARD_START.length\n const end = html.indexOf(WEB_CAPTURE_CLIPBOARD_END, from)\n return end === -1 ? null : html.slice(from, end)\n}\n\n/** Whether clipboard HTML holds a complete capture marker. */\nexport function hasWebCaptureClipboardMarker(html: string): boolean {\n return markedPayload(html) !== null\n}\n\n/** Inflates at most `MAX_CAPTURE_JSON_LENGTH` bytes of text. */\nfunction inflateText(bytes: Uint8Array): { text: string } | 'invalid' | 'too-large' {\n const decoder = new TextDecoder()\n // An object, since the inflate callback changes it where control flow analysis cannot see.\n const state = { text: '', length: 0, overflow: false }\n const inflate = new Inflate((chunk) => {\n state.length += chunk.length\n if (state.length > MAX_CAPTURE_JSON_LENGTH) state.overflow = true\n else state.text += decoder.decode(chunk, { stream: true })\n })\n try {\n for (let offset = 0; offset < bytes.length; offset += INFLATE_STEP) {\n if (state.overflow) break\n const end = offset + INFLATE_STEP\n inflate.push(bytes.subarray(offset, end), end >= bytes.length)\n }\n } catch {\n return 'invalid'\n }\n return state.overflow ? 'too-large' : { text: state.text + decoder.decode() }\n}\n\n/**\n * The capture clipboard HTML holds, or null when it holds none. Clipboard HTML is writable by\n * any page, so the payload is size-limited, validated, and normalized before it is returned.\n */\nexport function readWebCaptureClipboard(html: string): WebCaptureReadResult | null {\n const payload = markedPayload(html)\n if (payload === null) return null\n const encoded = payload.trim()\n if (encoded.length > MAX_CAPTURE_JSON_LENGTH) return { ok: false, error: 'too-large' }\n if (!isValid(encoded)) return { ok: false, error: 'invalid' }\n const inflated = inflateText(toUint8Array(encoded))\n if (typeof inflated === 'string') return { ok: false, error: inflated }\n return parseWebCapture(inflated.text)\n}\n","import { encodeWebCaptureClipboard, type WebCaptureClipboardPayload } from '#web-capture/clipboard'\nimport type { WebCapture } from '#web-capture/format'\n\n/** The part of the asynchronous clipboard a capture write uses. */\nexport type CaptureClipboard = Pick<Clipboard, 'write'>\n\nexport interface WriteCaptureClipboardOptions {\n /** The clipboard to write; the page's own by default. */\n clipboard?: CaptureClipboard\n /** Builds a clipboard item; the page's `ClipboardItem` by default. */\n createItem?: (items: Record<string, Promise<Blob>>) => ClipboardItem\n}\n\n/** Thrown when the page has no asynchronous clipboard, which only secure pages offer. */\nexport class CaptureClipboardUnavailableError extends Error {\n constructor() {\n super('Copying a capture needs a page served over HTTPS')\n this.name = 'CaptureClipboardUnavailableError'\n }\n}\n\nfunction isPayload(\n value: WebCapture | WebCaptureClipboardPayload\n): value is WebCaptureClipboardPayload {\n return 'html' in value && 'text' in value\n}\n\n/**\n * Copies a capture so it pastes into a Pairdraw canvas, as HTML for Pairdraw and other\n * applications and as the page's title and address for plain text. Pass the capture's promise\n * straight from the click that asked for it: the write starts inside that click and resolves\n * its data later, so a capture that takes a while still counts as the click's own.\n */\nexport async function writeWebCaptureClipboard(\n capture:\n | WebCapture\n | WebCaptureClipboardPayload\n | Promise<WebCapture | WebCaptureClipboardPayload>,\n options: WriteCaptureClipboardOptions = {}\n): Promise<void> {\n const clipboard =\n options.clipboard ?? (typeof navigator === 'undefined' ? undefined : navigator.clipboard)\n const createItem =\n options.createItem ??\n (typeof ClipboardItem === 'undefined'\n ? undefined\n : (items: Record<string, Promise<Blob>>) => new ClipboardItem(items))\n // `navigator.clipboard` is missing outside secure contexts.\n if (!clipboard || !createItem) throw new CaptureClipboardUnavailableError()\n const payload = Promise.resolve(capture).then((value) =>\n isPayload(value) ? value : encodeWebCaptureClipboard(value)\n )\n await clipboard.write([\n createItem({\n 'text/html': payload.then((value) => new Blob([value.html], { type: 'text/html' })),\n 'text/plain': payload.then((value) => new Blob([value.text], { type: 'text/plain' }))\n })\n ])\n}\n"],"mappings":";;;;;;;;;;AAIA,SAAgB,SACd,QACA,KACoB;CACpB,OAAO,OAAO,OAAO,QAAQ,GAAG,IAAI,OAAO,OAAO,KAAA;AACpD;;;ACHA,MAAM,4BAAY,IAAI,IAAI;CAAC;CAAQ;CAAM;CAAO;CAAM;CAAO;CAAS;CAAU;AAAK,CAAC;AAOtF,SAAS,eAAe,OAAuC;CAC7D,OAAO,OAAO,QAAQ,KA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RIBUTES = [
96
96
  "class",
97
97
  "alt",
98
98
  "title",
99
+ "type",
99
100
  "role",
100
101
  "aria-label",
101
102
  "lang",
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../src/capturer/svg.ts","../../../src/capturer/walk.ts","../../../src/capturer/index.ts"],"sourcesContent":["import type { CaptureWindow, ImageSize } from './images'\n\n/**\n * Presentation properties an icon usually takes from the page's stylesheets or `currentColor`,\n * which a standalone SVG loses. They are written onto the copy as inline styles.\n */\nconst PRESENTATION_PROPERTIES = [\n 'fill',\n 'fill-opacity',\n 'fill-rule',\n 'stroke',\n 'stroke-width',\n 'stroke-opacity',\n 'stroke-linecap',\n 'stroke-linejoin',\n 'stroke-dasharray',\n 'opacity',\n 'color',\n 'font-family',\n 'font-size',\n 'font-weight',\n 'display',\n 'visibility'\n]\n\n/** Elements whose styles are copied; very large drawings keep the rest as they are. */\nconst MAX_STYLED_ELEMENTS = 4000\n\nconst SVG_NAMESPACE = 'http://www.w3.org/2000/svg'\n\nfunction inlineStyles(view: CaptureWindow, original: Element, copy: Element): void {\n const style = view.getComputedStyle(original)\n const declarations = PRESENTATION_PROPERTIES.flatMap((property) => {\n const value = style.getPropertyValue(property)\n return value ? [`${property}:${value}`] : []\n })\n if (declarations.length > 0) copy.setAttribute('style', declarations.join(';'))\n}\n\n/** A `<use>` pointing at an icon sprite elsewhere in the page needs that sprite in the copy. */\nfunction referencedSymbols(svg: SVGSVGElement, document: Document): Element[] {\n const symbols = new Set<Element>()\n for (const use of svg.querySelectorAll('use')) {\n const reference = use.getAttribute('href') ?? use.getAttribute('xlink:href') ?? ''\n if (!reference.startsWith('#')) continue\n const target = document.getElementById(reference.slice(1))\n if (target && !svg.contains(target)) symbols.add(target)\n }\n return [...symbols]\n}\n\n/**\n * The SVG as standalone markup that draws as it did on the page: its computed presentation\n * styles inlined, sprites it references copied in, and its drawn size set.\n */\nexport function standaloneSVGMarkup(\n view: CaptureWindow,\n svg: SVGSVGElement,\n size: ImageSize\n): string {\n const copy = svg.cloneNode(true)\n if (!(copy instanceof view.SVGSVGElement)) return ''\n const originals = [svg, ...svg.querySelectorAll('*')]\n const copies = [copy, ...copy.querySelectorAll('*')]\n for (const [index, original] of originals.slice(0, MAX_STYLED_ELEMENTS).entries()) {\n const target = copies.at(index)\n if (target) inlineStyles(view, original, target)\n }\n const symbols = referencedSymbols(svg, svg.ownerDocument)\n if (symbols.length > 0) {\n const defs = svg.ownerDocument.createElementNS(SVG_NAMESPACE, 'defs')\n for (const symbol of symbols) defs.append(symbol.cloneNode(true))\n copy.prepend(defs)\n }\n copy.setAttribute('xmlns', SVG_NAMESPACE)\n copy.setAttribute('width', String(size.width))\n copy.setAttribute('height', String(size.height))\n return new view.XMLSerializer().serializeToString(copy)\n}\n","import { MAX_CAPTURE_DEPTH } from '#web-capture/limits'\nimport { CAPTURED_STYLE_PROPERTIES, withoutImpliedValues } from '#web-capture/styles'\nimport type { WebCaptureBox, WebCaptureElement, WebCaptureNode } from '#web-capture/types'\n\nimport type { FontCollector } from './fonts'\nimport type { CaptureWindow, ImageInliner } from './images'\nimport { standaloneSVGMarkup } from './svg'\n\n/** What a walk shares: the page, where the root sits, its budget, and work left to finish. */\nexport interface WalkContext {\n view: CaptureWindow\n origin: Pick<WebCaptureBox, 'x' | 'y'>\n maxElements: number\n elements: number\n truncated: boolean\n images: ImageInliner\n fonts: FontCollector\n /** Images still being read, each writing its element's source when done. */\n pending: Promise<void>[]\n}\n\n/** Elements that never draw, or draw another document a page cannot read. */\nconst SKIPPED_TAGS = new Set([\n 'script',\n 'style',\n 'link',\n 'meta',\n 'head',\n 'title',\n 'template',\n 'noscript',\n 'base',\n 'iframe',\n 'frame',\n 'object',\n 'embed',\n 'source',\n 'track',\n 'param'\n])\n\nconst KEPT_ATTRIBUTES = ['id', 'class', 'alt', 'title', 'role', 'aria-label', 'lang', 'dir']\n\n/** Input types whose value is text a person reads in the field. */\nconst TEXT_INPUT_TYPES = new Set([\n '',\n 'text',\n 'email',\n 'search',\n 'url',\n 'tel',\n 'number',\n 'password'\n])\n\nconst BACKGROUND_URL = /url\\(\\s*(['\"]?)(.*?)\\1\\s*\\)/\n\nfunction boxOf(element: Element, origin: WalkContext['origin']): WebCaptureBox {\n const rect = element.getBoundingClientRect()\n return {\n x: rect.left - origin.x,\n y: rect.top - origin.y,\n width: rect.width,\n height: rect.height\n }\n}\n\nfunction attributesOf(element: Element, view: CaptureWindow): Record<string, string> {\n const attrs: Record<string, string> = {}\n for (const name of KEPT_ATTRIBUTES) {\n const value = element.getAttribute(name)\n if (value !== null && value !== '') attrs[name] = value\n }\n // The resolved address, not the attribute as written, which may be relative.\n if (element instanceof view.HTMLAnchorElement && element.hasAttribute('href') && element.href) {\n attrs.href = element.href\n }\n return attrs\n}\n\nfunction readStyle(style: CSSStyleDeclaration): Record<string, string> {\n const computed: Record<string, string> = {}\n for (const property of CAPTURED_STYLE_PROPERTIES) {\n const value = style.getPropertyValue(property)\n if (value) computed[property] = value\n }\n // A hidden box keeps its room but draws nothing, as a transparent layer does.\n const visibility = style.getPropertyValue('visibility')\n if (visibility === 'hidden' || visibility === 'collapse') computed.opacity = '0'\n return withoutImpliedValues(computed)\n}\n\nfunction hasDirectText(element: Element): boolean {\n return [...element.childNodes].some(\n (child) => child.nodeType === 3 && (child.textContent ?? '').trim().length > 0\n )\n}\n\n/** The nodes an element draws: its shadow tree with slots filled when it has an open one. */\nfunction renderedChildren(element: Element, view: CaptureWindow): Node[] {\n const source = element.shadowRoot ? element.shadowRoot.childNodes : element.childNodes\n return [...source].flatMap((child) => {\n if (child instanceof view.HTMLSlotElement) {\n const assigned = child.assignedNodes({ flatten: true })\n return assigned.length > 0 ? assigned : [...child.childNodes]\n }\n return [child]\n })\n}\n\nfunction controlText(element: Element, view: CaptureWindow): string | null {\n if (element instanceof view.HTMLTextAreaElement) {\n return element.value || element.placeholder || null\n }\n if (element instanceof view.HTMLSelectElement) {\n return element.selectedOptions.item(0)?.text ?? null\n }\n if (element instanceof view.HTMLInputElement) {\n if (!TEXT_INPUT_TYPES.has(element.type)) {\n return element.type === 'button' || element.type === 'submit' ? element.value : null\n }\n if (element.type === 'password' && element.value) return '•'.repeat(element.value.length)\n return element.value || element.placeholder || null\n }\n return null\n}\n\n/** Reads an image in the background and writes it as the element's source. */\nfunction inlineSource(\n context: WalkContext,\n node: WebCaptureElement,\n read: () => Promise<string | null>\n): void {\n context.pending.push(\n read().then((source) => {\n if (source) node.attrs.src = source\n return undefined\n })\n )\n}\n\nfunction imageSize(box: WebCaptureBox) {\n return { width: Math.round(box.width), height: Math.round(box.height) }\n}\n\n/** What a canvas shows, or null when it drew another site's image, which taints it. */\nfunction canvasDataURL(canvas: HTMLCanvasElement): string | null {\n try {\n return canvas.toDataURL('image/png')\n } catch {\n return null\n }\n}\n\nfunction captureReplaced(element: Element, node: WebCaptureElement, context: WalkContext): boolean {\n const { view } = context\n const box = node.box ?? { x: 0, y: 0, width: 0, height: 0 }\n if (element instanceof view.SVGSVGElement) {\n node.tagName = 'img'\n if (box.width > 0 && box.height > 0) {\n const markup = standaloneSVGMarkup(view, element, imageSize(box))\n inlineSource(context, node, () => context.images.rasterizeSVG(markup, imageSize(box)))\n }\n return true\n }\n if (element instanceof view.HTMLImageElement) {\n const source = element.currentSrc || element.src\n if (source) {\n // The address stays when the image cannot be inlined; the importer records it.\n node.attrs.src = source\n inlineSource(context, node, () => context.images.inline(source, imageSize(box)))\n }\n return true\n }\n if (element instanceof view.HTMLCanvasElement) {\n node.tagName = 'img'\n const drawn = canvasDataURL(element)\n const source = drawn && context.images.accept(drawn)\n if (source) node.attrs.src = source\n return true\n }\n if (element instanceof view.HTMLVideoElement) {\n node.tagName = 'img'\n const poster = element.poster\n if (poster) inlineSource(context, node, () => context.images.inline(poster, imageSize(box)))\n return true\n }\n const text = controlText(element, view)\n if (text !== null) {\n node.children = [{ type: 'text', text }]\n return true\n }\n return false\n}\n\n/**\n * A background image becomes an image: the element itself when it holds nothing else, or an\n * image layer behind its content otherwise, since layers have no background images.\n */\nfunction captureBackground(\n style: CSSStyleDeclaration,\n node: WebCaptureElement,\n context: WalkContext\n) {\n const match = BACKGROUND_URL.exec(style.getPropertyValue('background-image'))\n const url = match?.[2]\n const box = node.box\n if (!url || !box || box.width <= 0 || box.height <= 0) return\n const fit = style.getPropertyValue('background-size') === 'contain' ? 'contain' : 'cover'\n if (node.tagName !== 'img' && node.children.length === 0) {\n node.tagName = 'img'\n node.computedStyle['object-fit'] = fit\n inlineSource(context, node, () => context.images.inline(url))\n return\n }\n if (node.tagName === 'img') return\n const radii = Object.fromEntries(\n Object.entries(node.computedStyle).filter(([property]) => property.endsWith('-radius'))\n )\n const image: WebCaptureElement = {\n type: 'element',\n tagName: 'img',\n attrs: {},\n computedStyle: {\n ...radii,\n display: 'block',\n position: 'absolute',\n left: '0px',\n top: '0px',\n width: `${box.width}px`,\n height: `${box.height}px`,\n 'object-fit': fit\n },\n box,\n children: []\n }\n inlineSource(context, image, () => context.images.inline(url))\n node.children.unshift(image)\n}\n\nfunction captureChildren(element: Element, context: WalkContext, depth: number): WebCaptureNode[] {\n return renderedChildren(element, context.view).flatMap((child) => {\n if (child.nodeType === 3) {\n const text = child.textContent ?? ''\n return text.length > 0 ? [{ type: 'text' as const, text }] : []\n }\n return child instanceof context.view.Element ? walkElement(child, context, depth + 1) : []\n })\n}\n\n/**\n * The element as a capture holds it, with its descendants; several nodes when it has no box\n * of its own (`display: contents`) and none when it is not displayed.\n */\nexport function walkElement(element: Element, context: WalkContext, depth = 0): WebCaptureNode[] {\n const tagName = element.localName.toLowerCase()\n if (SKIPPED_TAGS.has(tagName)) return []\n const style = context.view.getComputedStyle(element)\n const display = style.getPropertyValue('display')\n if (display === 'none') return []\n if (display === 'contents') return captureChildren(element, context, depth)\n if (depth > MAX_CAPTURE_DEPTH || context.elements >= context.maxElements) {\n context.truncated = true\n return []\n }\n context.elements++\n const node: WebCaptureElement = {\n type: 'element',\n tagName,\n attrs: attributesOf(element, context.view),\n computedStyle: readStyle(style),\n box: boxOf(element, context.origin),\n children: []\n }\n if (!captureReplaced(element, node, context)) {\n node.children = captureChildren(element, context, depth)\n }\n if (hasDirectText(element) || node.children.some((child) => child.type === 'text')) {\n context.fonts.add(style)\n }\n captureBackground(style, node, context)\n return [node]\n}\n","import type { WebCapture } from '#web-capture/format'\nimport { MAX_CAPTURE_ELEMENTS, WEB_CAPTURE_FORMAT, WEB_CAPTURE_VERSION } from '#web-capture/limits'\nimport { normalizeWebCapture } from '#web-capture/parse'\nimport type { WebCaptureElement } from '#web-capture/types'\n\nimport { createFontCollector } from './fonts'\nimport {\n createImageInliner,\n type CaptureImageFetcher,\n type CaptureWindow,\n type ImageInliner\n} from './images'\nimport { walkElement, type WalkContext } from './walk'\n\nexport {\n CaptureClipboardUnavailableError,\n writeWebCaptureClipboard,\n type CaptureClipboard,\n type WriteCaptureClipboardOptions\n} from './clipboard'\nexport type { CaptureImageFetcher } from './images'\n\nexport interface CaptureOptions {\n /** Elements to capture at most; the capture is marked truncated when the page has more. */\n maxElements?: number\n /** Carry images inside the capture as data URLs (the default), or keep only their addresses. */\n inlineImages?: boolean\n /** Reads images the page cannot, such as another site's without CORS headers. */\n fetchImage?: CaptureImageFetcher\n /** Bytes one inlined image may take. */\n maxImageBytes?: number\n /** Bytes all inlined images may take together. */\n maxTotalImageBytes?: number\n signal?: AbortSignal\n}\n\nconst NO_IMAGES: ImageInliner = {\n inline: async () => null,\n rasterizeSVG: async () => null,\n accept: () => null\n}\n\nfunction windowOf(document: Document): CaptureWindow {\n const view = document.defaultView\n if (!view) throw new TypeError('Capturing needs a document shown in a window')\n return view\n}\n\nfunction createContext(\n view: CaptureWindow,\n origin: WalkContext['origin'],\n options: CaptureOptions\n): WalkContext {\n return {\n view,\n origin,\n maxElements: options.maxElements ?? MAX_CAPTURE_ELEMENTS,\n elements: 0,\n truncated: false,\n images:\n options.inlineImages === false\n ? NO_IMAGES\n : createImageInliner(view, {\n fetchImage: options.fetchImage,\n maxImageBytes: options.maxImageBytes,\n maxTotalBytes: options.maxTotalImageBytes,\n signal: options.signal\n }),\n fonts: createFontCollector(),\n pending: []\n }\n}\n\nasync function finish(\n context: WalkContext,\n root: WebCaptureElement,\n scope: WebCapture['scope'],\n options: CaptureOptions\n): Promise<WebCapture> {\n await Promise.all(context.pending)\n options.signal?.throwIfAborted()\n const { view } = context\n return normalizeWebCapture({\n format: WEB_CAPTURE_FORMAT,\n version: WEB_CAPTURE_VERSION,\n scope,\n source: { url: view.location.href || undefined, title: view.document.title || undefined },\n capturedAt: new Date().toISOString(),\n viewport: {\n width: view.innerWidth,\n height: view.innerHeight,\n devicePixelRatio: view.devicePixelRatio || 1\n },\n root,\n fonts: context.fonts.list(),\n truncated: context.truncated\n })\n}\n\n/** The single root a walk returns; an element without a box of its own gets one around it. */\nfunction rootElement(element: Element, context: WalkContext): WebCaptureElement {\n const nodes = walkElement(element, context)\n const first = nodes.at(0)\n if (nodes.length === 1 && first?.type === 'element') return first\n if (nodes.length === 0) throw new Error('The element is not displayed')\n const rect = element.getBoundingClientRect()\n return {\n type: 'element',\n tagName: 'div',\n attrs: {},\n computedStyle: { display: 'block' },\n box: { x: 0, y: 0, width: rect.width, height: rect.height },\n children: nodes\n }\n}\n\n/**\n * Captures one element of a live page with the styles the browser computed for it, its\n * images inlined as data URLs. Runs in the page, as a content script or a capturer SDK does.\n */\nexport async function captureElement(\n element: Element,\n options: CaptureOptions = {}\n): Promise<WebCapture> {\n options.signal?.throwIfAborted()\n const view = windowOf(element.ownerDocument)\n const rect = element.getBoundingClientRect()\n const context = createContext(view, { x: rect.left, y: rect.top }, options)\n return finish(context, rootElement(element, context), 'element', options)\n}\n\nfunction isTransparent(color: string): boolean {\n return color === '' || color === 'transparent' || color === 'rgba(0, 0, 0, 0)'\n}\n\n/**\n * Captures a whole page: the body at the page's full scroll size, on the background the page\n * shows, with the body's margins kept as space around its content.\n */\nexport async function capturePage(\n document: Document = globalThis.document,\n options: CaptureOptions = {}\n): Promise<WebCapture> {\n options.signal?.throwIfAborted()\n const view = windowOf(document)\n const { body, documentElement } = document\n const pageRect = documentElement.getBoundingClientRect()\n const context = createContext(view, { x: pageRect.left, y: pageRect.top }, options)\n const root = rootElement(body, context)\n const bodyStyle = view.getComputedStyle(body)\n const style = root.computedStyle\n for (const side of ['top', 'right', 'bottom', 'left'] as const) {\n const margin = Number.parseFloat(bodyStyle.getPropertyValue(`margin-${side}`)) || 0\n const padding = Number.parseFloat(bodyStyle.getPropertyValue(`padding-${side}`)) || 0\n if (margin + padding > 0) style[`padding-${side}`] = `${margin + padding}px`\n delete style[`margin-${side}`]\n }\n const background = [bodyStyle, view.getComputedStyle(documentElement)]\n .map((computed) => computed.getPropertyValue('background-color'))\n .find((color) => !isTransparent(color))\n style['background-color'] = background ?? 'rgb(255, 255, 255)'\n // The page's size, not the body's, which may be shorter than the window.\n const width = documentElement.clientWidth || pageRect.width\n const height = Math.max(documentElement.scrollHeight, view.innerHeight)\n style.width = `${width}px`\n style.height = `${height}px`\n style['box-sizing'] = 'border-box'\n root.box = { x: 0, y: 0, width, height }\n return finish(context, root, 'page', options)\n}\n"],"mappings":";;;;;;;;AAMA,MAAM,0BAA0B;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAM,sBAAsB;AAE5B,MAAM,gBAAgB;AAEtB,SAAS,aAAa,MAAqB,UAAmB,MAAqB;CACjF,MAAM,QAAQ,KAAK,iBAAiB,QAAQ;CAC5C,MAAM,eAAe,wBAAwB,SAAS,aAAa;EACjE,MAAM,QAAQ,MAAM,iBAAiB,QAAQ;EAC7C,OAAO,QAAQ,CAAC,GAAG,SAAS,GAAG,OAAO,IAAI,CAAC;CAC7C,CAAC;CACD,IAAI,aAAa,SAAS,GAAG,KAAK,aAAa,SAAS,aAAa,KAAK,GAAG,CAAC;AAChF;;AAGA,SAAS,kBAAkB,KAAoB,UAA+B;CAC5E,MAAM,0BAAU,I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AC,GACN;CACrB,QAAQ,QAAQ,eAAe;CAC/B,MAAM,OAAO,SAAS,QAAQ;CAC9B,MAAM,EAAE,MAAM,oBAAoB;CAClC,MAAM,WAAW,gBAAgB,sBAAsB;CACvD,MAAM,UAAU,cAAc,MAAM;EAAE,GAAG,SAAS;EAAM,GAAG,SAAS;CAAI,GAAG,OAAO;CAClF,MAAM,OAAO,YAAY,MAAM,OAAO;CACtC,MAAM,YAAY,KAAK,iBAAiB,IAAI;CAC5C,MAAM,QAAQ,KAAK;CACnB,KAAK,MAAM,QAAQ;EAAC;EAAO;EAAS;EAAU;CAAM,GAAY;EAC9D,MAAM,SAAS,OAAO,WAAW,UAAU,iBAAiB,UAAU,MAAM,CAAC,KAAK;EAClF,MAAM,UAAU,OAAO,WAAW,UAAU,iBAAiB,WAAW,MAAM,CAAC,KAAK;EACpF,IAAI,SAAS,UAAU,GAAG,MAAM,WAAW,UAAU,GAAG,SAAS,QAAQ;EACzE,OAAO,MAAM,UAAU;CACzB;CAIA,MAAM,sBAHa,CAAC,WAAW,KAAK,iBAAiB,eAAe,CAAC,CAAC,CACnE,KAAK,aAAa,SAAS,iBAAiB,kBAAkB,CAAC,CAAC,CAChE,MAAM,UAAU,CAAC,cAAc,KAAK,CACF,KAAK;CAE1C,MAAM,QAAQ,gBAAgB,eAAe,SAAS;CACtD,MAAM,SAAS,KAAK,IAAI,gBAAgB,cAAc,KAAK,WAAW;CACtE,MAAM,QAAQ,GAAG,MAAM;CACvB,MAAM,SAAS,GAAG,OAAO;CACzB,MAAM,gBAAgB;CACtB,KAAK,MAAM;EAAE,GAAG;EAAG,GAAG;EAAG;EAAO;CAAO;CACvC,OAAO,OAAO,SAAS,MAAM,QAAQ,OAAO;AAC9C"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/capturer/svg.ts","../../../src/capturer/walk.ts","../../../src/capturer/index.ts"],"sourcesContent":["import type { CaptureWindow, ImageSize } from './images'\n\n/**\n * Presentation properties an icon usually takes from the page's stylesheets or `currentColor`,\n * which a standalone SVG loses. They are written onto the copy as inline styles.\n */\nconst PRESENTATION_PROPERTIES = [\n 'fill',\n 'fill-opacity',\n 'fill-rule',\n 'stroke',\n 'stroke-width',\n 'stroke-opacity',\n 'stroke-linecap',\n 'stroke-linejoin',\n 'stroke-dasharray',\n 'opacity',\n 'color',\n 'font-family',\n 'font-size',\n 'font-weight',\n 'display',\n 'visibility'\n]\n\n/** Elements whose styles are copied; very large drawings keep the rest as they are. */\nconst MAX_STYLED_ELEMENTS = 4000\n\nconst SVG_NAMESPACE = 'http://www.w3.org/2000/svg'\n\nfunction inlineStyles(view: CaptureWindow, original: Element, copy: Element): void {\n const style = view.getComputedStyle(original)\n const declarations = PRESENTATION_PROPERTIES.flatMap((property) => {\n const value = style.getPropertyValue(property)\n return value ? [`${property}:${value}`] : []\n })\n if (declarations.length > 0) copy.setAttribute('style', declarations.join(';'))\n}\n\n/** A `<use>` pointing at an icon sprite elsewhere in the page needs that sprite in the copy. */\nfunction referencedSymbols(svg: SVGSVGElement, document: Document): Element[] {\n const symbols = new Set<Element>()\n for (const use of svg.querySelectorAll('use')) {\n const reference = use.getAttribute('href') ?? use.getAttribute('xlink:href') ?? ''\n if (!reference.startsWith('#')) continue\n const target = document.getElementById(reference.slice(1))\n if (target && !svg.contains(target)) symbols.add(target)\n }\n return [...symbols]\n}\n\n/**\n * The SVG as standalone markup that draws as it did on the page: its computed presentation\n * styles inlined, sprites it references copied in, and its drawn size set.\n */\nexport function standaloneSVGMarkup(\n view: CaptureWindow,\n svg: SVGSVGElement,\n size: ImageSize\n): string {\n const copy = svg.cloneNode(true)\n if (!(copy instanceof view.SVGSVGElement)) return ''\n const originals = [svg, ...svg.querySelectorAll('*')]\n const copies = [copy, ...copy.querySelectorAll('*')]\n for (const [index, original] of originals.slice(0, MAX_STYLED_ELEMENTS).entries()) {\n const target = copies.at(index)\n if (target) inlineStyles(view, original, target)\n }\n const symbols = referencedSymbols(svg, svg.ownerDocument)\n if (symbols.length > 0) {\n const defs = svg.ownerDocument.createElementNS(SVG_NAMESPACE, 'defs')\n for (const symbol of symbols) defs.append(symbol.cloneNode(true))\n copy.prepend(defs)\n }\n copy.setAttribute('xmlns', SVG_NAMESPACE)\n copy.setAttribute('width', String(size.width))\n copy.setAttribute('height', String(size.height))\n return new view.XMLSerializer().serializeToString(copy)\n}\n","import { MAX_CAPTURE_DEPTH } from '#web-capture/limits'\nimport { CAPTURED_STYLE_PROPERTIES, withoutImpliedValues } from '#web-capture/styles'\nimport type { WebCaptureBox, WebCaptureElement, WebCaptureNode } from '#web-capture/types'\n\nimport type { FontCollector } from './fonts'\nimport type { CaptureWindow, ImageInliner } from './images'\nimport { standaloneSVGMarkup } from './svg'\n\n/** What a walk shares: the page, where the root sits, its budget, and work left to finish. */\nexport interface WalkContext {\n view: CaptureWindow\n origin: Pick<WebCaptureBox, 'x' | 'y'>\n maxElements: number\n elements: number\n truncated: boolean\n images: ImageInliner\n fonts: FontCollector\n /** Images still being read, each writing its element's source when done. */\n pending: Promise<void>[]\n}\n\n/** Elements that never draw, or draw another document a page cannot read. */\nconst SKIPPED_TAGS = new Set([\n 'script',\n 'style',\n 'link',\n 'meta',\n 'head',\n 'title',\n 'template',\n 'noscript',\n 'base',\n 'iframe',\n 'frame',\n 'object',\n 'embed',\n 'source',\n 'track',\n 'param'\n])\n\nconst KEPT_ATTRIBUTES = ['id', 'class', 'alt', 'title', 'type', 'role', 'aria-label', 'lang', 'dir']\n\n/** Input types whose value is text a person reads in the field. */\nconst TEXT_INPUT_TYPES = new Set([\n '',\n 'text',\n 'email',\n 'search',\n 'url',\n 'tel',\n 'number',\n 'password'\n])\n\nconst BACKGROUND_URL = /url\\(\\s*(['\"]?)(.*?)\\1\\s*\\)/\n\nfunction boxOf(element: Element, origin: WalkContext['origin']): WebCaptureBox {\n const rect = element.getBoundingClientRect()\n return {\n x: rect.left - origin.x,\n y: rect.top - origin.y,\n width: rect.width,\n height: rect.height\n }\n}\n\nfunction attributesOf(element: Element, view: CaptureWindow): Record<string, string> {\n const attrs: Record<string, string> = {}\n for (const name of KEPT_ATTRIBUTES) {\n const value = element.getAttribute(name)\n if (value !== null && value !== '') attrs[name] = value\n }\n // The resolved address, not the attribute as written, which may be relative.\n if (element instanceof view.HTMLAnchorElement && element.hasAttribute('href') && element.href) {\n attrs.href = element.href\n }\n return attrs\n}\n\nfunction readStyle(style: CSSStyleDeclaration): Record<string, string> {\n const computed: Record<string, string> = {}\n for (const property of CAPTURED_STYLE_PROPERTIES) {\n const value = style.getPropertyValue(property)\n if (value) computed[property] = value\n }\n // A hidden box keeps its room but draws nothing, as a transparent layer does.\n const visibility = style.getPropertyValue('visibility')\n if (visibility === 'hidden' || visibility === 'collapse') computed.opacity = '0'\n return withoutImpliedValues(computed)\n}\n\nfunction hasDirectText(element: Element): boolean {\n return [...element.childNodes].some(\n (child) => child.nodeType === 3 && (child.textContent ?? '').trim().length > 0\n )\n}\n\n/** The nodes an element draws: its shadow tree with slots filled when it has an open one. */\nfunction renderedChildren(element: Element, view: CaptureWindow): Node[] {\n const source = element.shadowRoot ? element.shadowRoot.childNodes : element.childNodes\n return [...source].flatMap((child) => {\n if (child instanceof view.HTMLSlotElement) {\n const assigned = child.assignedNodes({ flatten: true })\n return assigned.length > 0 ? assigned : [...child.childNodes]\n }\n return [child]\n })\n}\n\nfunction controlText(element: Element, view: CaptureWindow): string | null {\n if (element instanceof view.HTMLTextAreaElement) {\n return element.value || element.placeholder || null\n }\n if (element instanceof view.HTMLSelectElement) {\n return element.selectedOptions.item(0)?.text ?? null\n }\n if (element instanceof view.HTMLInputElement) {\n if (!TEXT_INPUT_TYPES.has(element.type)) {\n return element.type === 'button' || element.type === 'submit' ? element.value : null\n }\n if (element.type === 'password' && element.value) return '•'.repeat(element.value.length)\n return element.value || element.placeholder || null\n }\n return null\n}\n\n/** Reads an image in the background and writes it as the element's source. */\nfunction inlineSource(\n context: WalkContext,\n node: WebCaptureElement,\n read: () => Promise<string | null>\n): void {\n context.pending.push(\n read().then((source) => {\n if (source) node.attrs.src = source\n return undefined\n })\n )\n}\n\nfunction imageSize(box: WebCaptureBox) {\n return { width: Math.round(box.width), height: Math.round(box.height) }\n}\n\n/** What a canvas shows, or null when it drew another site's image, which taints it. */\nfunction canvasDataURL(canvas: HTMLCanvasElement): string | null {\n try {\n return canvas.toDataURL('image/png')\n } catch {\n return null\n }\n}\n\nfunction captureReplaced(element: Element, node: WebCaptureElement, context: WalkContext): boolean {\n const { view } = context\n const box = node.box ?? { x: 0, y: 0, width: 0, height: 0 }\n if (element instanceof view.SVGSVGElement) {\n node.tagName = 'img'\n if (box.width > 0 && box.height > 0) {\n const markup = standaloneSVGMarkup(view, element, imageSize(box))\n inlineSource(context, node, () => context.images.rasterizeSVG(markup, imageSize(box)))\n }\n return true\n }\n if (element instanceof view.HTMLImageElement) {\n const source = element.currentSrc || element.src\n if (source) {\n // The address stays when the image cannot be inlined; the importer records it.\n node.attrs.src = source\n inlineSource(context, node, () => context.images.inline(source, imageSize(box)))\n }\n return true\n }\n if (element instanceof view.HTMLCanvasElement) {\n node.tagName = 'img'\n const drawn = canvasDataURL(element)\n const source = drawn && context.images.accept(drawn)\n if (source) node.attrs.src = source\n return true\n }\n if (element instanceof view.HTMLVideoElement) {\n node.tagName = 'img'\n const poster = element.poster\n if (poster) inlineSource(context, node, () => context.images.inline(poster, imageSize(box)))\n return true\n }\n const text = controlText(element, view)\n if (text !== null) {\n node.children = [{ type: 'text', text }]\n return true\n }\n return false\n}\n\n/**\n * A background image becomes an image: the element itself when it holds nothing else, or an\n * image layer behind its content otherwise, since layers have no background images.\n */\nfunction captureBackground(\n style: CSSStyleDeclaration,\n node: WebCaptureElement,\n context: WalkContext\n) {\n const match = BACKGROUND_URL.exec(style.getPropertyValue('background-image'))\n const url = match?.[2]\n const box = node.box\n if (!url || !box || box.width <= 0 || box.height <= 0) return\n const fit = style.getPropertyValue('background-size') === 'contain' ? 'contain' : 'cover'\n if (node.tagName !== 'img' && node.children.length === 0) {\n node.tagName = 'img'\n node.computedStyle['object-fit'] = fit\n inlineSource(context, node, () => context.images.inline(url))\n return\n }\n if (node.tagName === 'img') return\n const radii = Object.fromEntries(\n Object.entries(node.computedStyle).filter(([property]) => property.endsWith('-radius'))\n )\n const image: WebCaptureElement = {\n type: 'element',\n tagName: 'img',\n attrs: {},\n computedStyle: {\n ...radii,\n display: 'block',\n position: 'absolute',\n left: '0px',\n top: '0px',\n width: `${box.width}px`,\n height: `${box.height}px`,\n 'object-fit': fit\n },\n box,\n children: []\n }\n inlineSource(context, image, () => context.images.inline(url))\n node.children.unshift(image)\n}\n\nfunction captureChildren(element: Element, context: WalkContext, depth: number): WebCaptureNode[] {\n return renderedChildren(element, context.view).flatMap((child) => {\n if (child.nodeType === 3) {\n const text = child.textContent ?? ''\n return text.length > 0 ? [{ type: 'text' as const, text }] : []\n }\n return child instanceof context.view.Element ? walkElement(child, context, depth + 1) : []\n })\n}\n\n/**\n * The element as a capture holds it, with its descendants; several nodes when it has no box\n * of its own (`display: contents`) and none when it is not displayed.\n */\nexport function walkElement(element: Element, context: WalkContext, depth = 0): WebCaptureNode[] {\n const tagName = element.localName.toLowerCase()\n if (SKIPPED_TAGS.has(tagName)) return []\n const style = context.view.getComputedStyle(element)\n const display = style.getPropertyValue('display')\n if (display === 'none') return []\n if (display === 'contents') return captureChildren(element, context, depth)\n if (depth > MAX_CAPTURE_DEPTH || context.elements >= context.maxElements) {\n context.truncated = true\n return []\n }\n context.elements++\n const node: WebCaptureElement = {\n type: 'element',\n tagName,\n attrs: attributesOf(element, context.view),\n computedStyle: readStyle(style),\n box: boxOf(element, context.origin),\n children: []\n }\n if (!captureReplaced(element, node, context)) {\n node.children = captureChildren(element, context, depth)\n }\n if (hasDirectText(element) || node.children.some((child) => child.type === 'text')) {\n context.fonts.add(style)\n }\n captureBackground(style, node, context)\n return [node]\n}\n","import type { WebCapture } from '#web-capture/format'\nimport { MAX_CAPTURE_ELEMENTS, WEB_CAPTURE_FORMAT, WEB_CAPTURE_VERSION } from '#web-capture/limits'\nimport { normalizeWebCapture } from '#web-capture/parse'\nimport type { WebCaptureElement } from '#web-capture/types'\n\nimport { createFontCollector } from './fonts'\nimport {\n createImageInliner,\n type CaptureImageFetcher,\n type CaptureWindow,\n type ImageInliner\n} from './images'\nimport { walkElement, type WalkContext } from './walk'\n\nexport {\n CaptureClipboardUnavailableError,\n writeWebCaptureClipboard,\n type CaptureClipboard,\n type WriteCaptureClipboardOptions\n} from './clipboard'\nexport type { CaptureImageFetcher } from './images'\n\nexport interface CaptureOptions {\n /** Elements to capture at most; the capture is marked truncated when the page has more. */\n maxElements?: number\n /** Carry images inside the capture as data URLs (the default), or keep only their addresses. */\n inlineImages?: boolean\n /** Reads images the page cannot, such as another site's without CORS headers. */\n fetchImage?: CaptureImageFetcher\n /** Bytes one inlined image may take. */\n maxImageBytes?: number\n /** Bytes all inlined images may take together. */\n maxTotalImageBytes?: number\n signal?: AbortSignal\n}\n\nconst NO_IMAGES: ImageInliner = {\n inline: async () => null,\n rasterizeSVG: async () => null,\n accept: () => null\n}\n\nfunction windowOf(document: Document): CaptureWindow {\n const view = document.defaultView\n if (!view) throw new TypeError('Capturing needs a document shown in a window')\n return view\n}\n\nfunction createContext(\n view: CaptureWindow,\n origin: WalkContext['origin'],\n options: CaptureOptions\n): WalkContext {\n return {\n view,\n origin,\n maxElements: options.maxElements ?? MAX_CAPTURE_ELEMENTS,\n elements: 0,\n truncated: false,\n images:\n options.inlineImages === false\n ? NO_IMAGES\n : createImageInliner(view, {\n fetchImage: options.fetchImage,\n maxImageBytes: options.maxImageBytes,\n maxTotalBytes: options.maxTotalImageBytes,\n signal: options.signal\n }),\n fonts: createFontCollector(),\n pending: []\n }\n}\n\nasync function finish(\n context: WalkContext,\n root: WebCaptureElement,\n scope: WebCapture['scope'],\n options: CaptureOptions\n): Promise<WebCapture> {\n await Promise.all(context.pending)\n options.signal?.throwIfAborted()\n const { view } = context\n return normalizeWebCapture({\n format: WEB_CAPTURE_FORMAT,\n version: WEB_CAPTURE_VERSION,\n scope,\n source: { url: view.location.href || undefined, title: view.document.title || undefined },\n capturedAt: new Date().toISOString(),\n viewport: {\n width: view.innerWidth,\n height: view.innerHeight,\n devicePixelRatio: view.devicePixelRatio || 1\n },\n root,\n fonts: context.fonts.list(),\n truncated: context.truncated\n })\n}\n\n/** The single root a walk returns; an element without a box of its own gets one around it. */\nfunction rootElement(element: Element, context: WalkContext): WebCaptureElement {\n const nodes = walkElement(element, context)\n const first = nodes.at(0)\n if (nodes.length === 1 && first?.type === 'element') return first\n if (nodes.length === 0) throw new Error('The element is not displayed')\n const rect = element.getBoundingClientRect()\n return {\n type: 'element',\n tagName: 'div',\n attrs: {},\n computedStyle: { display: 'block' },\n box: { x: 0, y: 0, width: rect.width, height: rect.height },\n children: nodes\n }\n}\n\n/**\n * Captures one element of a live page with the styles the browser computed for it, its\n * images inlined as data URLs. Runs in the page, as a content script or a capturer SDK does.\n */\nexport async function captureElement(\n element: Element,\n options: CaptureOptions = {}\n): Promise<WebCapture> {\n options.signal?.throwIfAborted()\n const view = windowOf(element.ownerDocument)\n const rect = element.getBoundingClientRect()\n const context = createContext(view, { x: rect.left, y: rect.top }, options)\n return finish(context, rootElement(element, context), 'element', options)\n}\n\nfunction isTransparent(color: string): boolean {\n return color === '' || color === 'transparent' || color === 'rgba(0, 0, 0, 0)'\n}\n\n/**\n * Captures a whole page: the body at the page's full scroll size, on the background the page\n * shows, with the body's margins kept as space around its content.\n */\nexport async function capturePage(\n document: Document = globalThis.document,\n options: CaptureOptions = {}\n): Promise<WebCapture> {\n options.signal?.throwIfAborted()\n const view = windowOf(document)\n const { body, documentElement } = document\n const pageRect = documentElement.getBoundingClientRect()\n const context = createContext(view, { x: pageRect.left, y: pageRect.top }, options)\n const root = rootElement(body, context)\n const bodyStyle = view.getComputedStyle(body)\n const style = root.computedStyle\n for (const side of ['top', 'right', 'bottom', 'left'] as const) {\n const margin = Number.parseFloat(bodyStyle.getPropertyValue(`margin-${side}`)) || 0\n const padding = Number.parseFloat(bodyStyle.getPropertyValue(`padding-${side}`)) || 0\n if (margin + padding > 0) style[`padding-${side}`] = `${margin + padding}px`\n delete style[`margin-${side}`]\n }\n const background = [bodyStyle, view.getComputedStyle(documentElement)]\n .map((computed) => computed.getPropertyValue('background-color'))\n .find((color) => !isTransparent(color))\n style['background-color'] = background ?? 'rgb(255, 255, 255)'\n // The page's size, not the body's, which may be shorter than the window.\n const width = documentElement.clientWidth || pageRect.width\n const height = Math.max(documentElement.scrollHeight, view.innerHeight)\n style.width = `${width}px`\n style.height = `${height}px`\n style['box-sizing'] = 'border-box'\n root.box = { x: 0, y: 0, width, height }\n return finish(context, root, 'page', options)\n}\n"],"mappings":";;;;;;;;AAMA,MAAM,0BAA0B;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAM,sBAAsB;AAE5B,MAAM,gBAAgB;AAEtB,SAAS,aAAa,MAAqB,UAAmB,MAAqB;CACjF,MAAM,QAAQ,KAAK,iBAAiB,QAAQ;CAC5C,MAAM,eAAe,wBAAwB,SAAS,aAAa;EACjE,MAAM,QAAQ,MAAM,iBAAiB,QAAQ;EAC7C,OAAO,QAAQ,CAAC,GAAG,SAAS,GAAG,OAAO,IAAI,CAAC;CAC7C,CAAC;CACD,IAAI,aAAa,SAAS,GAAG,KAAK,aAAa,SAAS,aAAa,KAAK,GAAG,CAAC;AAChF;;AAGA,SAAS,kBAAkB,KAAoB,UAA+B;CAC5E,MAAM,0BAAU,IAAI,IAAa;CACjC,KAAK,MAAM,OAAO,IAAI,iBAAiB,KAAK,GAAG;EAC7C,MAAM,YAAY,IAAI,aAAa,MAAM,KAAK,IAAI,aAAa,YAAY,KAAK;EAChF,IAAI,CAAC,UAAU,WAAW,GAAG,GAAG;EAChC,MAAM,SAAS,SAAS,eAAe,UAAU,MAAM,CAAC,CAAC;EACzD,IAAI,UAAU,CAAC,IAAI,SA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OAAO;CACtC,MAAM,YAAY,KAAK,iBAAiB,IAAI;CAC5C,MAAM,QAAQ,KAAK;CACnB,KAAK,MAAM,QAAQ;EAAC;EAAO;EAAS;EAAU;CAAM,GAAY;EAC9D,MAAM,SAAS,OAAO,WAAW,UAAU,iBAAiB,UAAU,MAAM,CAAC,KAAK;EAClF,MAAM,UAAU,OAAO,WAAW,UAAU,iBAAiB,WAAW,MAAM,CAAC,KAAK;EACpF,IAAI,SAAS,UAAU,GAAG,MAAM,WAAW,UAAU,GAAG,SAAS,QAAQ;EACzE,OAAO,MAAM,UAAU;CACzB;CAIA,MAAM,sBAHa,CAAC,WAAW,KAAK,iBAAiB,eAAe,CAAC,CAAC,CACnE,KAAK,aAAa,SAAS,iBAAiB,kBAAkB,CAAC,CAAC,CAChE,MAAM,UAAU,CAAC,cAAc,KAAK,CACF,KAAK;CAE1C,MAAM,QAAQ,gBAAgB,eAAe,SAAS;CACtD,MAAM,SAAS,KAAK,IAAI,gBAAgB,cAAc,KAAK,WAAW;CACtE,MAAM,QAAQ,GAAG,MAAM;CACvB,MAAM,SAAS,GAAG,OAAO;CACzB,MAAM,gBAAgB;CACtB,KAAK,MAAM;EAAE,GAAG;EAAG,GAAG;EAAG;EAAO;CAAO;CACvC,OAAO,OAAO,SAAS,MAAM,QAAQ,OAAO;AAC9C"}
@@ -202,6 +202,63 @@ function layoutOf(element) {
202
202
  children: convertChildren(element.children, element.box)
203
203
  };
204
204
  }
205
+ /** Input types Chrome paints as a small intrinsic glyph, whatever box `width` gives them. */
206
+ const GLYPH_INPUT_TYPES = {
207
+ checkbox: true,
208
+ radio: true
209
+ };
210
+ /**
211
+ * A checkbox or radio wider than its glyph: Chrome honors the width for layout but paints only
212
+ * a small square centered in the box (`input { width: 100% }` in a flex label). Import the
213
+ * square at the glyph's size, centered in a box that keeps the room the wide element took, so
214
+ * following content stays where the page put it. Null when the box already fits the glyph.
215
+ */
216
+ function glyphBox(element, converted, margins, parentBox) {
217
+ const box = element.box;
218
+ if (element.tagName !== "input" || !Object.hasOwn(GLYPH_INPUT_TYPES, element.attrs.type) || !box || box.width <= 0 || box.height <= 0) return null;
219
+ const side = Math.min(box.width, box.height);
220
+ if (box.width - side < 1) return null;
221
+ const style = converted.computedStyle;
222
+ const absolute = isAbsolute(style);
223
+ style.width = px(side);
224
+ style.height = px(side);
225
+ style["box-sizing"] = "border-box";
226
+ delete style.position;
227
+ delete style.left;
228
+ delete style.top;
229
+ delete style.right;
230
+ delete style.bottom;
231
+ const wrapper = {
232
+ display: "flex",
233
+ "justify-content": "center",
234
+ "align-items": "center",
235
+ width: px(box.width),
236
+ height: px(box.height),
237
+ "box-sizing": "border-box"
238
+ };
239
+ const alignSelf = ownValue(style, "align-self");
240
+ if (alignSelf !== void 0) {
241
+ wrapper["align-self"] = alignSelf;
242
+ delete style["align-self"];
243
+ }
244
+ const wrapped = {
245
+ type: "element",
246
+ tagName: "div",
247
+ attrs: {},
248
+ computedStyle: wrapper,
249
+ children: [converted]
250
+ };
251
+ if (absolute) {
252
+ wrapper.position = element.computedStyle.position === "fixed" ? "fixed" : "absolute";
253
+ for (const key of ["left", "top"]) {
254
+ const value = ownValue(element.computedStyle, key);
255
+ if (value !== void 0) wrapper[key] = value;
256
+ }
257
+ placeAbsolute(wrapper, margins, box, parentBox);
258
+ return wrapped;
259
+ }
260
+ return SIDES.some((side) => margins[side] > 0) ? marginBox(wrapped, margins) : wrapped;
261
+ }
205
262
  function convertElement(element, parentBox) {
206
263
  const { displayed, children } = layoutOf(element);
207
264
  const inline = isInline(displayed);
@@ -215,6 +272,8 @@ function convertElement(element, parentBox) {
215
272
  computedStyle: style,
216
273
  children
217
274
  };
275
+ const glyph = glyphBox(element, converted, margins, parentBox);
276
+ if (glyph) return glyph;
218
277
  if (isAbsolute(style)) {
219
278
  placeAbsolute(style, margins, element.box, parentBox);
220
279
  return converted;
@@ -1 +1 @@
1
- {"version":3,"file":"design-document.js","names":[],"sources":["../../src/design-document.ts"],"sourcesContent":["import { omit } from 'es-toolkit'\n\nimport type { WebCapture } from './format'\nimport { ownValue } from './record'\nimport type { WebCaptureBox, WebCaptureElement, WebCaptureNode, WebCaptureText } from './types'\n\n/**\n * An element of the styled DOM `@pairdraw/dom-css` builds layers from. The shape matches its\n * `DesignElement`, so a capture imports through `sceneGraphFromStyledHTML` without a CSS runtime.\n */\nexport interface WebCaptureDesignElement {\n type: 'element'\n tagName: string\n attrs: Record<string, string>\n computedStyle: Record<string, string>\n children: WebCaptureDesignNode[]\n}\n\nexport type WebCaptureDesignNode = WebCaptureDesignElement | WebCaptureText\n\n/** The styled DOM of a capture, matching `@pairdraw/dom-css`'s `DesignDocument`. */\nexport interface WebCaptureDesignDocument {\n type: 'document'\n children: WebCaptureDesignNode[]\n}\n\nconst SIDES = ['top', 'right', 'bottom', 'left'] as const\ntype Side = (typeof SIDES)[number]\n\n/**\n * Displays the importer has no layout for, mapped to the closest one it has. A grid of\n * fixed-size cells wraps as a row of them does, and a table row is a row of its cells.\n */\nconst DISPLAY_FALLBACKS: Record<string, Record<string, string>> = {\n grid: { display: 'flex', 'flex-direction': 'row', 'flex-wrap': 'wrap' },\n 'inline-grid': { display: 'inline-flex', 'flex-direction': 'row', 'flex-wrap': 'wrap' },\n 'table-row': { display: 'flex', 'flex-direction': 'row', 'flex-wrap': 'nowrap' },\n table: { display: 'block' },\n 'inline-table': { display: 'inline-block' },\n 'table-row-group': { display: 'block' },\n 'table-header-group': { display: 'block' },\n 'table-footer-group': { display: 'block' },\n 'table-cell': { display: 'block' },\n 'table-caption': { display: 'block' },\n 'list-item': { display: 'block' },\n 'flow-root': { display: 'block' }\n}\n\n/**\n * Inline text tags the importer lays out inline when they say nothing of their display. Left\n * without one, a run such as a link or a bold word stays text instead of a box around text.\n */\nconst INLINE_TEXT_TAGS = new Set(['a', 'b', 'code', 'em', 'i', 'small', 'span', 'strong', 'u'])\n\nfunction pixels(value: string | undefined): number {\n if (!value?.endsWith('px')) return 0\n const parsed = Number.parseFloat(value)\n return Number.isFinite(parsed) ? parsed : 0\n}\n\nfunction px(value: number): string {\n return `${Math.round(value * 100) / 100}px`\n}\n\nconst MARGINS = SIDES.map((side) => `margin-${side}` as const)\n\n/** The element's margins in pixels, and its style without them. */\nfunction splitMargins(style: Record<string, string>) {\n const margins = { top: 0, right: 0, bottom: 0, left: 0 }\n for (const side of SIDES) margins[side] = pixels(style[`margin-${side}`])\n return { margins, style: omit(style, MARGINS) }\n}\n\nfunction isAbsolute(style: Record<string, string>): boolean {\n return style.position === 'absolute' || style.position === 'fixed'\n}\n\nfunction isInline(style: Record<string, string>): boolean {\n return (ownValue(style, 'display') ?? '').startsWith('inline')\n}\n\n/**\n * Places an absolute box in its parent layer. CSS measures `left` and `top` from the containing\n * block, which may be a further ancestor or the viewport, so the recorded boxes place it where\n * the page drew it. Without them, it sits at its offset plus its margin, as CSS places it.\n */\nfunction placeAbsolute(\n style: Record<string, string>,\n margins: Record<Side, number>,\n box: WebCaptureBox | undefined,\n parentBox: WebCaptureBox | undefined\n): void {\n if (box && parentBox) {\n style.left = px(box.x - parentBox.x)\n style.top = px(box.y - parentBox.y)\n return\n }\n if (ownValue(style, 'left') !== undefined) style.left = px(pixels(style.left) + margins.left)\n if (ownValue(style, 'top') !== undefined) style.top = px(pixels(style.top) + margins.top)\n}\n\n/**\n * A box in normal flow keeps the room its margins took inside a transparent box padded by them.\n * Negative margins, which pull neighbours over each other, are dropped.\n */\nfunction marginBox(\n element: WebCaptureDesignElement,\n margins: Record<Side, number>\n): WebCaptureDesignElement {\n const style: Record<string, string> = { display: 'block' }\n for (const side of SIDES) {\n if (margins[side] > 0) style[`padding-${side}`] = px(margins[side])\n }\n const alignSelf = ownValue(element.computedStyle, 'align-self')\n if (alignSelf === undefined) {\n return { type: 'element', tagName: 'div', attrs: {}, computedStyle: style, children: [element] }\n }\n // The box is the flex item now, so it aligns itself as the element did.\n style['align-self'] = alignSelf\n const child = { ...element, computedStyle: omit(element.computedStyle, ['align-self']) }\n return { type: 'element', tagName: 'div', attrs: {}, computedStyle: style, children: [child] }\n}\n\nfunction convertChildren(\n children: readonly WebCaptureNode[],\n parentBox: WebCaptureBox | undefined\n): WebCaptureDesignNode[] {\n return children.map((child): WebCaptureDesignNode =>\n child.type === 'text' ? child : convertElement(child, parentBox)\n )\n}\n\nconst GRID_DISPLAYS = new Set(['grid', 'inline-grid'])\n\ntype BoxedElement = WebCaptureElement & { box: WebCaptureBox }\n\nfunction hasBox(element: WebCaptureElement): element is BoxedElement {\n return element.box !== undefined\n}\n\n/**\n * A grid whose items can stay where the page drew them: the capture recorded the grid's box and\n * every item's, and the grid holds no loose text. Null otherwise, and for anything but a grid.\n */\nfunction placeableGrid(\n element: WebCaptureElement\n): { box: WebCaptureBox; items: BoxedElement[] } | null {\n if (!GRID_DISPLAYS.has(ownValue(element.computedStyle, 'display') ?? '') || !hasBox(element)) {\n return null\n }\n const items: BoxedElement[] = []\n for (const child of element.children) {\n if (child.type === 'text') {\n if (child.text.trim().length > 0) return null\n } else if (hasBox(child)) {\n items.push(child)\n } else {\n return null\n }\n }\n return { box: element.box, items }\n}\n\n/**\n * Auto layout has no grid tracks, so a grid keeps its drawn size and its items become absolute\n * boxes where the page drew them. Their margins already moved their boxes.\n */\nfunction gridStyle(style: Record<string, string>, box: WebCaptureBox): Record<string, string> {\n return {\n ...omit(style, ['gap', 'row-gap', 'column-gap']),\n display: style.display === 'inline-grid' ? 'inline-block' : 'block',\n width: px(box.width),\n height: px(box.height),\n 'box-sizing': 'border-box'\n }\n}\n\nconst PLACEMENT = [...MARGINS, 'position', ...SIDES]\n\nfunction placeGridItem(item: BoxedElement, grid: WebCaptureBox): WebCaptureDesignElement {\n // Without margins or a position of its own, the item converts to itself, not a margin box.\n const converted = convertElement({ ...item, computedStyle: omit(item.computedStyle, PLACEMENT) })\n converted.computedStyle = {\n ...converted.computedStyle,\n position: 'absolute',\n left: px(item.box.x - grid.x),\n top: px(item.box.y - grid.y),\n width: px(item.box.width),\n height: px(item.box.height),\n 'box-sizing': 'border-box'\n }\n return converted\n}\n\n/**\n * The style an element is laid out with, the closest display the importer has standing in for\n * one it lacks, and its converted children.\n */\nfunction layoutOf(element: WebCaptureElement) {\n const grid = placeableGrid(element)\n if (grid) {\n return {\n displayed: gridStyle(element.computedStyle, grid.box),\n children: grid.items.map((item) => placeGridItem(item, grid.box))\n }\n }\n const display = ownValue(element.computedStyle, 'display') ?? ''\n return {\n displayed: { ...element.computedStyle, ...DISPLAY_FALLBACKS[display] },\n children: convertChildren(element.children, element.box)\n }\n}\n\nfunction convertElement(\n element: WebCaptureElement,\n parentBox?: WebCaptureBox\n): WebCaptureDesignElement {\n const { displayed, children } = layoutOf(element)\n const inline = isInline(displayed)\n const split = splitMargins(displayed)\n const { margins } = split\n const style =\n displayed.display === 'inline' && INLINE_TEXT_TAGS.has(element.tagName)\n ? omit(split.style, ['display'])\n : split.style\n const converted: WebCaptureDesignElement = {\n type: 'element',\n tagName: element.tagName,\n attrs: { ...element.attrs },\n computedStyle: style,\n children\n }\n if (isAbsolute(style)) {\n placeAbsolute(style, margins, element.box, parentBox)\n return converted\n }\n const spaced = SIDES.some((side) => margins[side] > 0)\n return spaced && !inline ? marginBox(converted, margins) : converted\n}\n\n/**\n * The capture as the styled DOM layers are built from. The root keeps the size it had on the\n * page and drops its own position and margins, so it lands where a paste puts it.\n */\nexport function webCaptureDesignDocument(capture: WebCapture): WebCaptureDesignDocument {\n const { root } = capture\n const { displayed, children } = layoutOf(root)\n const style = omit(splitMargins(displayed).style, ['position', ...SIDES])\n // The box a capture records is the border box, padding and borders included.\n if (root.box) {\n style.width = px(root.box.width)\n style.height = px(root.box.height)\n style['box-sizing'] = 'border-box'\n }\n return {\n type: 'document',\n children: [\n {\n type: 'element',\n tagName: root.tagName,\n attrs: { ...root.attrs },\n computedStyle: style,\n children\n }\n ]\n }\n}\n"],"mappings":";;;AA0BA,MAAM,QAAQ;CAAC;CAAO;CAAS;CAAU;AAAM;;;;;AAO/C,MAAM,oBAA4D;CAChE,M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esContent":["import { omit } from 'es-toolkit'\n\nimport type { WebCapture } from './format'\nimport { ownValue } from './record'\nimport type { WebCaptureBox, WebCaptureElement, WebCaptureNode, WebCaptureText } from './types'\n\n/**\n * An element of the styled DOM `@pairdraw/dom-css` builds layers from. The shape matches its\n * `DesignElement`, so a capture imports through `sceneGraphFromStyledHTML` without a CSS runtime.\n */\nexport interface WebCaptureDesignElement {\n type: 'element'\n tagName: string\n attrs: Record<string, string>\n computedStyle: Record<string, string>\n children: WebCaptureDesignNode[]\n}\n\nexport type WebCaptureDesignNode = WebCaptureDesignElement | WebCaptureText\n\n/** The styled DOM of a capture, matching `@pairdraw/dom-css`'s `DesignDocument`. */\nexport interface WebCaptureDesignDocument {\n type: 'document'\n children: WebCaptureDesignNode[]\n}\n\nconst SIDES = ['top', 'right', 'bottom', 'left'] as const\ntype Side = (typeof SIDES)[number]\n\n/**\n * Displays the importer has no layout for, mapped to the closest one it has. A grid of\n * fixed-size cells wraps as a row of them does, and a table row is a row of its cells.\n */\nconst DISPLAY_FALLBACKS: Record<string, Record<string, string>> = {\n grid: { display: 'flex', 'flex-direction': 'row', 'flex-wrap': 'wrap' },\n 'inline-grid': { display: 'inline-flex', 'flex-direction': 'row', 'flex-wrap': 'wrap' },\n 'table-row': { display: 'flex', 'flex-direction': 'row', 'flex-wrap': 'nowrap' },\n table: { display: 'block' },\n 'inline-table': { display: 'inline-block' },\n 'table-row-group': { display: 'block' },\n 'table-header-group': { display: 'block' },\n 'table-footer-group': { display: 'block' },\n 'table-cell': { display: 'block' },\n 'table-caption': { display: 'block' },\n 'list-item': { display: 'block' },\n 'flow-root': { display: 'block' }\n}\n\n/**\n * Inline text tags the importer lays out inline when they say nothing of their display. Left\n * without one, a run such as a link or a bold word stays text instead of a box around text.\n */\nconst INLINE_TEXT_TAGS = new Set(['a', 'b', 'code', 'em', 'i', 'small', 'span', 'strong', 'u'])\n\nfunction pixels(value: string | undefined): number {\n if (!value?.endsWith('px')) return 0\n const parsed = Number.parseFloat(value)\n return Number.isFinite(parsed) ? parsed : 0\n}\n\nfunction px(value: number): string {\n return `${Math.round(value * 100) / 100}px`\n}\n\nconst MARGINS = SIDES.map((side) => `margin-${side}` as const)\n\n/** The element's margins in pixels, and its style without them. */\nfunction splitMargins(style: Record<string, string>) {\n const margins = { top: 0, right: 0, bottom: 0, left: 0 }\n for (const side of SIDES) margins[side] = pixels(style[`margin-${side}`])\n return { margins, style: omit(style, MARGINS) }\n}\n\nfunction isAbsolute(style: Record<string, string>): boolean {\n return style.position === 'absolute' || style.position === 'fixed'\n}\n\nfunction isInline(style: Record<string, string>): boolean {\n return (ownValue(style, 'display') ?? '').startsWith('inline')\n}\n\n/**\n * Places an absolute box in its parent layer. CSS measures `left` and `top` from the containing\n * block, which may be a further ancestor or the viewport, so the recorded boxes place it where\n * the page drew it. Without them, it sits at its offset plus its margin, as CSS places it.\n */\nfunction placeAbsolute(\n style: Record<string, string>,\n margins: Record<Side, number>,\n box: WebCaptureBox | undefined,\n parentBox: WebCaptureBox | undefined\n): void {\n if (box && parentBox) {\n style.left = px(box.x - parentBox.x)\n style.top = px(box.y - parentBox.y)\n return\n }\n if (ownValue(style, 'left') !== undefined) style.left = px(pixels(style.left) + margins.left)\n if (ownValue(style, 'top') !== undefined) style.top = px(pixels(style.top) + margins.top)\n}\n\n/**\n * A box in normal flow keeps the room its margins took inside a transparent box padded by them.\n * Negative margins, which pull neighbours over each other, are dropped.\n */\nfunction marginBox(\n element: WebCaptureDesignElement,\n margins: Record<Side, number>\n): WebCaptureDesignElement {\n const style: Record<string, string> = { display: 'block' }\n for (const side of SIDES) {\n if (margins[side] > 0) style[`padding-${side}`] = px(margins[side])\n }\n const alignSelf = ownValue(element.computedStyle, 'align-self')\n if (alignSelf === undefined) {\n return { type: 'element', tagName: 'div', attrs: {}, computedStyle: style, children: [element] }\n }\n // The box is the flex item now, so it aligns itself as the element did.\n style['align-self'] = alignSelf\n const child = { ...element, computedStyle: omit(element.computedStyle, ['align-self']) }\n return { type: 'element', tagName: 'div', attrs: {}, computedStyle: style, children: [child] }\n}\n\nfunction convertChildren(\n children: readonly WebCaptureNode[],\n parentBox: WebCaptureBox | undefined\n): WebCaptureDesignNode[] {\n return children.map((child): WebCaptureDesignNode =>\n child.type === 'text' ? child : convertElement(child, parentBox)\n )\n}\n\nconst GRID_DISPLAYS = new Set(['grid', 'inline-grid'])\n\ntype BoxedElement = WebCaptureElement & { box: WebCaptureBox }\n\nfunction hasBox(element: WebCaptureElement): element is BoxedElement {\n return element.box !== undefined\n}\n\n/**\n * A grid whose items can stay where the page drew them: the capture recorded the grid's box and\n * every item's, and the grid holds no loose text. Null otherwise, and for anything but a grid.\n */\nfunction placeableGrid(\n element: WebCaptureElement\n): { box: WebCaptureBox; items: BoxedElement[] } | null {\n if (!GRID_DISPLAYS.has(ownValue(element.computedStyle, 'display') ?? '') || !hasBox(element)) {\n return null\n }\n const items: BoxedElement[] = []\n for (const child of element.children) {\n if (child.type === 'text') {\n if (child.text.trim().length > 0) return null\n } else if (hasBox(child)) {\n items.push(child)\n } else {\n return null\n }\n }\n return { box: element.box, items }\n}\n\n/**\n * Auto layout has no grid tracks, so a grid keeps its drawn size and its items become absolute\n * boxes where the page drew them. Their margins already moved their boxes.\n */\nfunction gridStyle(style: Record<string, string>, box: WebCaptureBox): Record<string, string> {\n return {\n ...omit(style, ['gap', 'row-gap', 'column-gap']),\n display: style.display === 'inline-grid' ? 'inline-block' : 'block',\n width: px(box.width),\n height: px(box.height),\n 'box-sizing': 'border-box'\n }\n}\n\nconst PLACEMENT = [...MARGINS, 'position', ...SIDES]\n\nfunction placeGridItem(item: BoxedElement, grid: WebCaptureBox): WebCaptureDesignElement {\n // Without margins or a position of its own, the item converts to itself, not a margin box.\n const converted = convertElement({ ...item, computedStyle: omit(item.computedStyle, PLACEMENT) })\n converted.computedStyle = {\n ...converted.computedStyle,\n position: 'absolute',\n left: px(item.box.x - grid.x),\n top: px(item.box.y - grid.y),\n width: px(item.box.width),\n height: px(item.box.height),\n 'box-sizing': 'border-box'\n }\n return converted\n}\n\n/**\n * The style an element is laid out with, the closest display the importer has standing in for\n * one it lacks, and its converted children.\n */\nfunction layoutOf(element: WebCaptureElement) {\n const grid = placeableGrid(element)\n if (grid) {\n return {\n displayed: gridStyle(element.computedStyle, grid.box),\n children: grid.items.map((item) => placeGridItem(item, grid.box))\n }\n }\n const display = ownValue(element.computedStyle, 'display') ?? ''\n return {\n displayed: { ...element.computedStyle, ...DISPLAY_FALLBACKS[display] },\n children: convertChildren(element.children, element.box)\n }\n}\n\n/** Input types Chrome paints as a small intrinsic glyph, whatever box `width` gives them. */\nconst GLYPH_INPUT_TYPES: Record<string, true> = { checkbox: true, radio: true }\n\n/**\n * A checkbox or radio wider than its glyph: Chrome honors the width for layout but paints only\n * a small square centered in the box (`input { width: 100% }` in a flex label). Import the\n * square at the glyph's size, centered in a box that keeps the room the wide element took, so\n * following content stays where the page put it. Null when the box already fits the glyph.\n */\nfunction glyphBox(\n element: WebCaptureElement,\n converted: WebCaptureDesignElement,\n margins: Record<Side, number>,\n parentBox: WebCaptureBox | undefined\n): WebCaptureDesignElement | null {\n const box = element.box\n if (\n element.tagName !== 'input' ||\n !Object.hasOwn(GLYPH_INPUT_TYPES, element.attrs.type) ||\n !box ||\n box.width <= 0 ||\n box.height <= 0\n ) {\n return null\n }\n const side = Math.min(box.width, box.height)\n if (box.width - side < 1) return null\n const style = converted.computedStyle\n // The wrapper takes the placement, so the square must not be positioned or margined itself.\n const absolute = isAbsolute(style)\n style.width = px(side)\n style.height = px(side)\n style['box-sizing'] = 'border-box'\n delete style.position\n delete style.left\n delete style.top\n delete style.right\n delete style.bottom\n const wrapper: Record<string, string> = {\n display: 'flex',\n 'justify-content': 'center',\n 'align-items': 'center',\n width: px(box.width),\n height: px(box.height),\n 'box-sizing': 'border-box'\n }\n const alignSelf = ownValue(style, 'align-self')\n if (alignSelf !== undefined) {\n wrapper['align-self'] = alignSelf\n delete style['align-self']\n }\n const wrapped: WebCaptureDesignElement = {\n type: 'element',\n tagName: 'div',\n attrs: {},\n computedStyle: wrapper,\n children: [converted]\n }\n if (absolute) {\n wrapper.position = element.computedStyle.position === 'fixed' ? 'fixed' : 'absolute'\n for (const key of ['left', 'top']) {\n const value = ownValue(element.computedStyle, key)\n if (value !== undefined) wrapper[key] = value\n }\n placeAbsolute(wrapper, margins, box, parentBox)\n return wrapped\n }\n return SIDES.some((side) => margins[side] > 0) ? marginBox(wrapped, margins) : wrapped\n}\n\nfunction convertElement(\n element: WebCaptureElement,\n parentBox?: WebCaptureBox\n): WebCaptureDesignElement {\n const { displayed, children } = layoutOf(element)\n const inline = isInline(displayed)\n const split = splitMargins(displayed)\n const { margins } = split\n const style =\n displayed.display === 'inline' && INLINE_TEXT_TAGS.has(element.tagName)\n ? omit(split.style, ['display'])\n : split.style\n const converted: WebCaptureDesignElement = {\n type: 'element',\n tagName: element.tagName,\n attrs: { ...element.attrs },\n computedStyle: style,\n children\n }\n const glyph = glyphBox(element, converted, margins, parentBox)\n if (glyph) return glyph\n if (isAbsolute(style)) {\n placeAbsolute(style, margins, element.box, parentBox)\n return converted\n }\n const spaced = SIDES.some((side) => margins[side] > 0)\n return spaced && !inline ? marginBox(converted, margins) : converted\n}\n\n/**\n * The capture as the styled DOM layers are built from. The root keeps the size it had on the\n * page and drops its own position and margins, so it lands where a paste puts it.\n */\nexport function webCaptureDesignDocument(capture: WebCapture): WebCaptureDesignDocument {\n const { root } = capture\n const { displayed, children } = layoutOf(root)\n const style = omit(splitMargins(displayed).style, ['position', ...SIDES])\n // The box a capture records is the border box, padding and borders included.\n if (root.box) {\n style.width = px(root.box.width)\n style.height = px(root.box.height)\n style['box-sizing'] = 'border-box'\n }\n return {\n type: 'document',\n children: [\n {\n type: 'element',\n tagName: root.tagName,\n attrs: { ...root.attrs },\n computedStyle: style,\n children\n }\n ]\n }\n}\n"],"mappings":";;;AA0BA,MAAM,QAAQ;CAAC;CAAO;CAAS;CAAU;AAAM;;;;;AAO/C,MAAM,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K;GACd,OAAO,EAAE,GAAG,KAAK,MAAM;GACvB,eAAe;GACf;EACF,CACF;CACF;AACF"}
package/dist/index.d.ts CHANGED
@@ -90,7 +90,7 @@ declare function hasWebContent(html: string, options?: Pick<SanitizeWebHTMLOptio
90
90
  * The computed properties a capture keeps for each element: those `@pairdraw/dom-css` builds
91
91
  * layers from, plus margins, which a capture turns into spacing when it is imported.
92
92
  */
93
- declare const CAPTURED_STYLE_PROPERTIES: readonly ["align-items", "align-self", "aspect-ratio", "background-color", "border-bottom-color", "border-bottom-left-radius", "border-bottom-right-radius", "border-bottom-style", "border-bottom-width", "border-left-color", "border-left-style", "border-left-width", "border-right-color", "border-right-style", "border-right-width", "border-top-color", "border-top-left-radius", "border-top-right-radius", "border-top-style", "border-top-width", "bottom", "box-shadow", "box-sizing", "color", "column-gap", "display", "flex-direction", "flex-wrap", "font-family", "font-size", "font-style", "font-weight", "gap", "height", "justify-content", "left", "letter-spacing", "line-height", "margin-bottom", "margin-left", "margin-right", "margin-top", "max-height", "max-width", "min-height", "min-width", "object-fit", "opacity", "overflow", "padding-bottom", "padding-left", "padding-right", "padding-top", "position", "right", "row-gap", "text-align", "text-decoration-color", "text-decoration-line", "text-decoration-style", "text-decoration-thickness", "text-indent", "text-shadow", "text-transform", "text-underline-offset", "top", "white-space", "width"];
93
+ declare const CAPTURED_STYLE_PROPERTIES: readonly ["align-items", "align-self", "aspect-ratio", "background-color", "background-image", "background-position", "background-repeat", "background-size", "border-bottom-color", "border-bottom-left-radius", "border-bottom-right-radius", "border-bottom-style", "border-bottom-width", "border-left-color", "border-left-style", "border-left-width", "border-right-color", "border-right-style", "border-right-width", "border-top-color", "border-top-left-radius", "border-top-right-radius", "border-top-style", "border-top-width", "bottom", "box-shadow", "box-sizing", "color", "column-gap", "display", "flex-direction", "flex-wrap", "font-family", "font-size", "font-style", "font-weight", "gap", "height", "justify-content", "left", "letter-spacing", "line-height", "margin-bottom", "margin-left", "margin-right", "margin-top", "max-height", "max-width", "min-height", "min-width", "object-fit", "opacity", "overflow", "padding-bottom", "padding-left", "padding-right", "padding-top", "position", "right", "row-gap", "text-align", "text-decoration-color", "text-decoration-line", "text-decoration-style", "text-decoration-thickness", "text-indent", "text-shadow", "text-transform", "text-underline-offset", "top", "white-space", "width"];
94
94
  type CapturedStyleProperty = (typeof CAPTURED_STYLE_PROPERTIES)[number];
95
95
  /** Whether a capture keeps this property; others are dropped when a capture is read. */
96
96
  declare function isCapturedStyleProperty(property: string): property is CapturedStyleProperty;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/design-document.ts","../src/html.ts","../src/limits.ts","../src/parse.ts","../src/sanitize.ts","../src/styles.ts","../src/urls.ts"],"mappings":";;;;;;UAUiB;EACf;EACA;EACA,OAAO;EACP,eAAe;EACf,UAAU;;KAGA,uBAAuB,0BAA0B;;UAG5C;EACf;EACA,UAAU;;;;;;iBA6NI,yBAAyB,SAAS,aAAa;;;UC5O9C;;EAEf;;;;;;iBA+Bc,iBAAiB,SAAS,YAAY,UAAS;;;;cCxClD;;cAGA;;cAGA;;cAGA;;cAGA;;cAGA;;cAGA;;cAGA;;;;;;;;;iBCoHG,oBAAoB,SAAS,aAAa;;iBAQ1C,eAAe,iBAAiB;;iBAahC,gBAAgB,eAAe;;;UCnH9B;;EAEf,SAAS,KAAK;;EAEd;;;;;;;;;;;iBA+Dc,gBAAgB,cAAc,UAAS;;iBAcvC,cAAc,cAAc,UAAS,KAAK;;;;;;;cCvH7C;KAuED,gCAAgC;;iBAK5B,wBAAwB,mBAAmB,YAAY;;;;;iBAuDvD,qBAAqB,OAAO,yBAAyB;;;;iBC1HrD,YAAY,eAAe;;iBAM3B,gBAAgB,eAAe"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/design-document.ts","../src/html.ts","../src/limits.ts","../src/parse.ts","../src/sanitize.ts","../src/styles.ts","../src/urls.ts"],"mappings":";;;;;;UAUiB;EACf;EACA;EACA,OAAO;EACP,eAAe;EACf,UAAU;;KAGA,uBAAuB,0BAA0B;;UAG5C;EACf;EACA,UAAU;;;;;;iBAqSI,yBAAyB,SAAS,aAAa;;;UCpT9C;;EAEf;;;;;;iBA+Bc,iBAAiB,SAAS,YAAY,UAAS;;;;cCxClD;;cAGA;;cAGA;;cAGA;;cAGA;;cAGA;;cAGA;;cAGA;;;;;;;;;iBCyKG,oBAAoB,SAAS,aAAa;;iBAQ1C,eAAe,iBAAiB;;iBAahC,gBAAgB,eAAe;;;UCxK9B;;EAEf,SAAS,KAAK;;EAEd;;;;;;;;;;;iBA+Dc,gBAAgB,cAAc,UAAS;;iBAcvC,cAAc,cAAc,UAAS,KAAK;;;;;;;cCvH7C;KA2ED,gCAAgC;;iBAK5B,wBAAwB,mBAAmB,YAAY;;;;;iBA2DvD,qBAAqB,OAAO,yBAAyB;;;;iBClIrD,YAAY,eAAe;;iBAM3B,gBAAgB,eAAe"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pairdraw/web-capture",
3
- "version": "0.18.0",
3
+ "version": "0.19.0",
4
4
  "license": "MIT",
5
5
  "files": [
6
6
  "dist",
@@ -39,7 +39,7 @@ const SKIPPED_TAGS = new Set([
39
39
  'param'
40
40
  ])
41
41
 
42
- const KEPT_ATTRIBUTES = ['id', 'class', 'alt', 'title', 'role', 'aria-label', 'lang', 'dir']
42
+ const KEPT_ATTRIBUTES = ['id', 'class', 'alt', 'title', 'type', 'role', 'aria-label', 'lang', 'dir']
43
43
 
44
44
  /** Input types whose value is text a person reads in the field. */
45
45
  const TEXT_INPUT_TYPES = new Set([
@@ -211,6 +211,76 @@ function layoutOf(element: WebCaptureElement) {
211
211
  }
212
212
  }
213
213
 
214
+ /** Input types Chrome paints as a small intrinsic glyph, whatever box `width` gives them. */
215
+ const GLYPH_INPUT_TYPES: Record<string, true> = { checkbox: true, radio: true }
216
+
217
+ /**
218
+ * A checkbox or radio wider than its glyph: Chrome honors the width for layout but paints only
219
+ * a small square centered in the box (`input { width: 100% }` in a flex label). Import the
220
+ * square at the glyph's size, centered in a box that keeps the room the wide element took, so
221
+ * following content stays where the page put it. Null when the box already fits the glyph.
222
+ */
223
+ function glyphBox(
224
+ element: WebCaptureElement,
225
+ converted: WebCaptureDesignElement,
226
+ margins: Record<Side, number>,
227
+ parentBox: WebCaptureBox | undefined
228
+ ): WebCaptureDesignElement | null {
229
+ const box = element.box
230
+ if (
231
+ element.tagName !== 'input' ||
232
+ !Object.hasOwn(GLYPH_INPUT_TYPES, element.attrs.type) ||
233
+ !box ||
234
+ box.width <= 0 ||
235
+ box.height <= 0
236
+ ) {
237
+ return null
238
+ }
239
+ const side = Math.min(box.width, box.height)
240
+ if (box.width - side < 1) return null
241
+ const style = converted.computedStyle
242
+ // The wrapper takes the placement, so the square must not be positioned or margined itself.
243
+ const absolute = isAbsolute(style)
244
+ style.width = px(side)
245
+ style.height = px(side)
246
+ style['box-sizing'] = 'border-box'
247
+ delete style.position
248
+ delete style.left
249
+ delete style.top
250
+ delete style.right
251
+ delete style.bottom
252
+ const wrapper: Record<string, string> = {
253
+ display: 'flex',
254
+ 'justify-content': 'center',
255
+ 'align-items': 'center',
256
+ width: px(box.width),
257
+ height: px(box.height),
258
+ 'box-sizing': 'border-box'
259
+ }
260
+ const alignSelf = ownValue(style, 'align-self')
261
+ if (alignSelf !== undefined) {
262
+ wrapper['align-self'] = alignSelf
263
+ delete style['align-self']
264
+ }
265
+ const wrapped: WebCaptureDesignElement = {
266
+ type: 'element',
267
+ tagName: 'div',
268
+ attrs: {},
269
+ computedStyle: wrapper,
270
+ children: [converted]
271
+ }
272
+ if (absolute) {
273
+ wrapper.position = element.computedStyle.position === 'fixed' ? 'fixed' : 'absolute'
274
+ for (const key of ['left', 'top']) {
275
+ const value = ownValue(element.computedStyle, key)
276
+ if (value !== undefined) wrapper[key] = value
277
+ }
278
+ placeAbsolute(wrapper, margins, box, parentBox)
279
+ return wrapped
280
+ }
281
+ return SIDES.some((side) => margins[side] > 0) ? marginBox(wrapped, margins) : wrapped
282
+ }
283
+
214
284
  function convertElement(
215
285
  element: WebCaptureElement,
216
286
  parentBox?: WebCaptureBox
@@ -230,6 +300,8 @@ function convertElement(
230
300
  computedStyle: style,
231
301
  children
232
302
  }
303
+ const glyph = glyphBox(element, converted, margins, parentBox)
304
+ if (glyph) return glyph
233
305
  if (isAbsolute(style)) {
234
306
  placeAbsolute(style, margins, element.box, parentBox)
235
307
  return converted
package/src/parse.ts CHANGED
@@ -19,7 +19,7 @@ const captureHeaderSchema = v.looseObject({
19
19
  version: v.number()
20
20
  })
21
21
 
22
- /** Attributes a layer can use: names, links, images, and accessible labels. */
22
+ /** Attributes a layer can use: names, links, images, control kinds, and accessible labels. */
23
23
  const KEPT_ATTRIBUTES = new Set([
24
24
  'id',
25
25
  'class',
@@ -27,6 +27,7 @@ const KEPT_ATTRIBUTES = new Set([
27
27
  'src',
28
28
  'alt',
29
29
  'title',
30
+ 'type',
30
31
  'role',
31
32
  'aria-label',
32
33
  'lang',
@@ -94,10 +95,62 @@ function keptAttributes(
94
95
  return kept
95
96
  }
96
97
 
97
- function keptStyle(style: Record<string, string>): Record<string, string> {
98
- return Object.fromEntries(
99
- Object.entries(style).filter(([property]) => isCapturedStyleProperty(property))
100
- )
98
+ /** The `url(...)` sources of a value, with the spans they occupy. */
99
+ const BACKGROUND_URL = /url\(\s*(['"]?)(.*?)\1\s*\)/g
100
+
101
+ /**
102
+ * A `background-image` list with every `url(...)` source limited to what an image layer may
103
+ * keep; a layer whose source is unsafe is dropped, and a list left empty paints nothing.
104
+ * Gradient layers carry no address and pass through as written.
105
+ */
106
+ function keptBackgroundImage(value: string, base: string | undefined): string | null {
107
+ const layers: string[] = []
108
+ let cursor = 0
109
+ let dropped = false
110
+ for (const match of value.matchAll(BACKGROUND_URL)) {
111
+ const source = safeImageSource(match[2], base)
112
+ if (source) layers.push(value.slice(cursor, match.index) + `url("${source}")`)
113
+ else dropped = true
114
+ cursor = match.index + match[0].length
115
+ }
116
+ if (cursor === 0 && !dropped) return value
117
+ layers.push(value.slice(cursor))
118
+ // Split at top-level commas only: a gradient's own commas stay inside its parentheses.
119
+ const kept: string[] = []
120
+ let depth = 0
121
+ let current = ''
122
+ for (const character of layers.join('')) {
123
+ if (character === '(') depth++
124
+ else if (character === ')') depth--
125
+ if (character === ',' && depth === 0) {
126
+ kept.push(current)
127
+ current = ''
128
+ continue
129
+ }
130
+ current += character
131
+ }
132
+ kept.push(current)
133
+ const painted = kept
134
+ .map((layer) => layer.trim())
135
+ .filter((layer) => layer.length > 0 && layer !== 'none')
136
+ return painted.length > 0 ? painted.join(', ') : null
137
+ }
138
+
139
+ function keptStyle(
140
+ style: Record<string, string>,
141
+ base: string | undefined
142
+ ): Record<string, string> {
143
+ const kept: Record<string, string> = {}
144
+ for (const [property, value] of Object.entries(style)) {
145
+ if (!isCapturedStyleProperty(property)) continue
146
+ if (property === 'background-image') {
147
+ const image = keptBackgroundImage(value, base)
148
+ if (image) kept[property] = image
149
+ continue
150
+ }
151
+ kept[property] = value
152
+ }
153
+ return kept
101
154
  }
102
155
 
103
156
  function normalizeElement(
@@ -124,8 +177,8 @@ function normalizeElement(
124
177
  type: 'element',
125
178
  tagName: element.tagName,
126
179
  attrs: keptAttributes(element.attrs, base),
127
- computedStyle: keptStyle(element.computedStyle),
128
180
  ...(element.box ? { box: element.box } : {}),
181
+ computedStyle: keptStyle(element.computedStyle, base),
129
182
  children
130
183
  }
131
184
  }
package/src/styles.ts CHANGED
@@ -9,6 +9,10 @@ export const CAPTURED_STYLE_PROPERTIES = [
9
9
  'align-self',
10
10
  'aspect-ratio',
11
11
  'background-color',
12
+ 'background-image',
13
+ 'background-position',
14
+ 'background-repeat',
15
+ 'background-size',
12
16
  'border-bottom-color',
13
17
  'border-bottom-left-radius',
14
18
  'border-bottom-right-radius',
@@ -96,6 +100,10 @@ const IMPLIED_VALUES: Partial<Record<CapturedStyleProperty, readonly string[]>>
96
100
  'align-self': ['auto'],
97
101
  'aspect-ratio': ['auto'],
98
102
  'background-color': ['rgba(0, 0, 0, 0)', 'transparent'],
103
+ 'background-image': ['none'],
104
+ 'background-position': ['0% 0%'],
105
+ 'background-repeat': ['repeat'],
106
+ 'background-size': ['auto'],
99
107
  'box-shadow': ['none'],
100
108
  'column-gap': ['normal'],
101
109
  'flex-direction': ['row'],