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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
// Observe SVG geometry and styles per node in root SVG coordinates.
;(opts) => {
  const wantDiff = !!(opts && opts.wantDiff)
  // Null reads all computed styles.
  const styles = (opts && opts.styles) || null
  const resourceStyles = (opts && opts.resourceStyles) || null
  const reuseOutline = !(opts && opts.reuseOutline === false)
  const r = (v) => Math.round(v * 1e4) / 1e4

  const root = document.querySelector('svg')
  if (!root) return { error: 'no <svg> in the document' }
  const baseline = window.__baseline
  if (wantDiff && !baseline) return { needsBaseline: true }

  // Remove page layout from the measured coordinates.
  const rootCTM = root.getScreenCTM()
  const inv = rootCTM ? rootCTM.inverse() : null
  const OUTLINE_SAMPLES = 32

  // Definitions are not painted, even though <defs> is an SVGGraphicsElement.
  const paints = (el) => el instanceof SVGGraphicsElement && el.tagName.toLowerCase() !== 'defs'

  const styleOf = (el, properties = styles) => {
    const cs = getComputedStyle(el)
    const out = {}
    if (properties) {
      for (const k of properties) out[k] = cs.getPropertyValue(k)
      return out
    }
    for (let i = 0; i < cs.length; i++) {
      const k = cs[i]
      out[k] = cs.getPropertyValue(k)
    }
    return out
  }

  // CSS geometry overrides SVG presentation attributes.
  const OUTLINE_INPUTS = {
    path: [['d'], []],
    circle: [['cx', 'cy', 'r'], []],
    ellipse: [['cx', 'cy', 'rx', 'ry'], []],
    rect: [['x', 'y', 'width', 'height', 'rx', 'ry'], []],
    line: [[], ['x1', 'y1', 'x2', 'y2']],
    polyline: [[], ['points']],
    polygon: [[], ['points']],
  }

  if (!window.__outline) window.__outline = {}
  const outlineCache = window.__outline

  const outlineSignature = (el, tag) => {
    const inputs = OUTLINE_INPUTS[tag]
    if (!inputs) return null
    const cs = getComputedStyle(el)
    let sig = tag
    for (const k of inputs[0]) sig += '|' + cs.getPropertyValue(k)
    for (const k of inputs[1]) sig += '|' + (el.getAttribute(k) || '')
    return sig
  }

  const sampleOutline = (el, length, ends) => {
    if (!ends) return null
    if (length <= 0) return [ends[0]]
    const closed = Math.hypot(ends[0][0] - ends[1][0], ends[0][1] - ends[1][1]) <= 1e-4
    const divisor = OUTLINE_SAMPLES - 1
    const points = []
    for (let i = 0; i < OUTLINE_SAMPLES; i++) {
      const p = el.getPointAtLength((length * i) / divisor)
      points.push([r(p.x), r(p.y)])
    }
    if (closed) points[points.length - 1] = points[0]
    return points
  }

  const placePoints = (points, matrix) => {
    if (!points || !matrix) return null
    return points.map(([x, y]) => [
      r(matrix.a * x + matrix.c * y + matrix.e),
      r(matrix.b * x + matrix.d * y + matrix.f),
    ])
  }

  // Fill interiors can remain visible when their outlines are clipped away.
  const paintedSamples = (el, bbox, contour, matrix) => {
    if (!matrix || !(el instanceof SVGGeometryElement)) return null
    const cs = getComputedStyle(el)
    const fillOpacity = parseFloat(cs.fillOpacity)
    if (bbox && cs.fill !== 'none' && (!Number.isFinite(fillOpacity) || fillOpacity > 0)) {
      const [x, y, width, height] = bbox
      const points = []
      for (let row = 0; row < 8; row++) {
        for (let column = 0; column < 8; column++) {
          const point = new DOMPoint(
            x + (width * (column + 0.5)) / 8,
            y + (height * (row + 0.5)) / 8,
          )
          if (el.isPointInFill(point)) points.push([point.x, point.y])
        }
      }
      if (points.length) return placePoints(points, matrix)
    }
    const strokeOpacity = parseFloat(cs.strokeOpacity)
    return cs.stroke !== 'none' && (!Number.isFinite(strokeOpacity) || strokeOpacity > 0)
      ? contour
      : null
  }

  // Stroke width is approximate under nonuniform scale.
  const linearScale = (matrix) =>
    matrix ? Math.sqrt((matrix.a ** 2 + matrix.b ** 2 + matrix.c ** 2 + matrix.d ** 2) / 2) : null
  const effectiveStrokeWidth = (el, matrix) => {
    if (!matrix) return null
    const cs = getComputedStyle(el)
    const width = parseFloat(cs.strokeWidth)
    const strokeOpacity = parseFloat(cs.strokeOpacity)
    if (cs.stroke === 'none' || !Number.isFinite(width) || width <= 0 || strokeOpacity === 0)
      return 0
    const scale =
      cs.vectorEffect === 'non-scaling-stroke' ? 1 / linearScale(rootCTM) : linearScale(matrix)
    return Number.isFinite(scale) ? r(width * scale) : null
  }

  const definitionOf = (reference) => {
    const found = /url\(["']?#([^"')]+)/.exec(reference || '')
    return found ? document.getElementById(found[1]) : null
  }

  // Definition records describe inputs, not composited pixels.
  const referenceStyles = [
    'fill',
    'stroke',
    'filter',
    'clip-path',
    'mask-image',
    'marker-start',
    'marker-mid',
    'marker-end',
  ]
  const hrefTags = new Set([
    'use',
    'image',
    'lineargradient',
    'radialgradient',
    'pattern',
    'textpath',
    'feimage',
    'mpath',
  ])
  const referencesOf = (el, cs) => {
    const refs = new Set()
    for (const property of referenceStyles) {
      const value = cs.getPropertyValue(property)
      for (const match of value.matchAll(/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)]*?))\s*\)/g)) {
        refs.add((match[1] ?? match[2] ?? match[3]).trim())
      }
    }
    if (hrefTags.has(el.tagName.toLowerCase())) {
      const href = el.hasAttribute('href')
        ? el.getAttribute('href')
        : el.getAttributeNS('http://www.w3.org/1999/xlink', 'href')
      if (href) refs.add(href)
    }
    return refs
  }
  const resourceCache = new WeakMap()
  const definitionTags = new Set([
    'defs',
    'mask',
    'clippath',
    'filter',
    'lineargradient',
    'radialgradient',
    'pattern',
    'marker',
    'symbol',
  ])
  const resourceNode = (el) => {
    if (resourceCache.has(el)) return resourceCache.get(el)
    const cs = getComputedStyle(el)
    const attrs = Object.fromEntries(Array.from(el.attributes, (a) => [a.name, a.value]))
    const style = styleOf(el, resourceStyles)
    const children = Array.from(el.children)
      // Include nested definitions only when referenced.
      .filter(
        (child) => child instanceof SVGElement && !definitionTags.has(child.tagName.toLowerCase()),
      )
      .map(resourceNode)
    const refs = referencesOf(el, cs)
    for (const child of children) for (const ref of child.refs) refs.add(ref)
    const result = {
      value: {
        tag: el.tagName.toLowerCase(),
        attrs,
        style,
        children: children.map((c) => c.value),
      },
      refs,
    }
    resourceCache.set(el, result)
    return result
  }
  const resourceInputsOf = (el) => {
    const inputs = Object.create(null)
    const pending = Array.from(referencesOf(el, getComputedStyle(el)))
    for (let i = 0; i < pending.length; i++) {
      const reference = pending[i]
      if (Object.hasOwn(inputs, reference)) continue
      inputs[reference] = null // Unresolved references remain explicit.
      let target = null
      try {
        const url = new URL(reference, document.baseURI)
        if (url.hash && url.href.split('#')[0] === document.URL.split('#')[0]) {
          target = document.getElementById(decodeURIComponent(url.hash.slice(1)))
        }
      } catch (e) {
        /* malformed reference */
      }
      if (!(target instanceof SVGElement)) continue
      const record = resourceNode(target)
      inputs[reference] = record.value
      pending.push(...record.refs)
    }
    return inputs
  }

  // Place definition bounds using the referencing element's transform.
  const definitionBox = (el, reference) => {
    const def = reference.includes(',') ? null : definitionOf(reference)
    if (!def) return null
    let box = null
    for (const child of def.children) {
      try {
        const b = child.getBBox()
        const one = { x0: b.x, y0: b.y, x1: b.x + b.width, y1: b.y + b.height }
        box = box
          ? {
              x0: Math.min(box.x0, one.x0),
              y0: Math.min(box.y0, one.y0),
              x1: Math.max(box.x1, one.x1),
              y1: Math.max(box.y1, one.y1),
            }
          : one
      } catch (e) {
        /* a child with no box contributes nothing */
      }
    }
    if (!box) return null
    const m = el.getScreenCTM()
    if (!m || !inv) return null
    const l = inv.multiply(m)
    const xs = [],
      ys = []
    for (const [x, y] of [
      [box.x0, box.y0],
      [box.x1, box.y0],
      [box.x1, box.y1],
      [box.x0, box.y1],
    ]) {
      xs.push(l.a * x + l.c * y + l.e)
      ys.push(l.b * x + l.d * y + l.f)
    }
    return { x0: Math.min(...xs), y0: Math.min(...ys), x1: Math.max(...xs), y1: Math.max(...ys) }
  }

  // Nonrectangular clip bounds can overestimate visible area.
  const clipOf = (el) => definitionBox(el, getComputedStyle(el).clipPath)

  // Hidden source nodes can produce unusable zero-area mask bounds.
  const maskOf = (el) => {
    const box = definitionBox(el, getComputedStyle(el).maskImage)
    if (!box || box.x1 <= box.x0 || box.y1 <= box.y0) return null
    return box
  }

  const chainTo = (el, one) => {
    let box = null
    for (let node = el; node && node.nodeType === 1; node = node.parentNode) {
      const here = one(node)
      if (!here) continue
      box = box
        ? {
            x0: Math.max(box.x0, here.x0),
            y0: Math.max(box.y0, here.y0),
            x1: Math.min(box.x1, here.x1),
            y1: Math.min(box.y1, here.y1),
          }
        : here
    }
    return box ? [r(box.x0), r(box.y0), r(box.x1), r(box.y1)] : null
  }

  // Unsupported clip or mask constructs remain unmeasurable.
  const constraintCache = new WeakMap()
  const opaquePaint = (paint, opacity) => {
    if (paint === 'none' || opacity === 0) return false
    if (opacity !== 1 || paint.startsWith('url(')) return null
    const rgba = /^rgba\([^,]+,[^,]+,[^,]+,\s*([\d.]+)\)$/.exec(paint)
    if (!rgba) return true
    const alpha = Number(rgba[1])
    return alpha === 0 ? false : alpha === 1 ? true : null
  }
  const constraintOf = (el, kind, reference) => {
    const cached = constraintCache.get(el) || {}
    if (kind in cached) return cached[kind]

    const def = reference.includes(',') ? null : definitionOf(reference)
    let checker = null
    if (
      def &&
      ((kind === 'clip' && def.tagName.toLowerCase() === 'clippath') ||
        (kind === 'mask' && def.tagName.toLowerCase() === 'mask'))
    ) {
      const unit = kind === 'clip' ? def.clipPathUnits : def.maskContentUnits
      const binaryAlphaMask =
        kind !== 'mask' ||
        ((def.getAttribute('mask-type') || getComputedStyle(def).maskType) === 'alpha' &&
          !['x', 'y', 'width', 'height'].some((name) => def.hasAttribute(name)))
      const descendants = Array.from(def.querySelectorAll('*'))
      const allowedContainers = new Set(['g', 'a', 'switch', 'title', 'desc', 'metadata'])
      const unsupportedNode = descendants.some(
        (node) =>
          !(node instanceof SVGGeometryElement) &&
          !allowedContainers.has(node.tagName.toLowerCase()),
      )
      const shapes = descendants.filter((node) => node instanceof SVGGeometryElement)
      const placed = []
      const ref = (() => {
        try {
          const m = el.getScreenCTM()
          return m && inv ? inv.multiply(m) : null
        } catch (e) {
          return null
        }
      })()
      let supported = !!unit && unit.baseVal === 1 && binaryAlphaMask && !unsupportedNode && !!ref
      for (const shape of shapes) {
        const cs = getComputedStyle(shape)
        if (cs.display === 'none' || cs.visibility === 'hidden') continue
        if (kind === 'clip' && cs.clipRule !== cs.fillRule) supported = false
        let ancestor = shape
        let opaque = true
        while (ancestor && ancestor !== def) {
          const style = getComputedStyle(ancestor)
          const opacity = parseFloat(style.opacity)
          if (kind === 'clip' && style.clipPath !== 'none') supported = false
          if (
            (Number.isFinite(opacity) && opacity !== 1) ||
            style.filter !== 'none' ||
            style.clipPath !== 'none' ||
            style.maskImage !== 'none'
          )
            opaque = false
          ancestor = ancestor.parentNode
        }
        const fillOpacity = parseFloat(cs.fillOpacity)
        const strokeOpacity = parseFloat(cs.strokeOpacity)
        const fillState = opaquePaint(cs.fill, fillOpacity)
        const strokeState = opaquePaint(cs.stroke, strokeOpacity)
        const fill = fillState === true
        const stroke = strokeState === true
        if (kind === 'mask' && (!opaque || fillState === null || strokeState === null))
          supported = false
        try {
          const m = shape.getScreenCTM()
          if (!m || !inv || !ref) {
            supported = false
            continue
          }
          const inverse = ref.multiply(inv.multiply(m)).inverse()
          if (
            ![inverse.a, inverse.b, inverse.c, inverse.d, inverse.e, inverse.f].every(
              Number.isFinite,
            )
          ) {
            supported = false
            continue
          }
          placed.push({
            shape,
            inverse,
            fill: kind === 'clip' || fill,
            stroke: kind === 'mask' && stroke,
          })
        } catch (e) {
          supported = false
        }
      }
      if (supported) {
        checker = ([x, y]) =>
          placed.some(({ shape, inverse, fill, stroke }) => {
            const point = new DOMPoint(
              inverse.a * x + inverse.c * y + inverse.e,
              inverse.b * x + inverse.d * y + inverse.f,
            )
            return (fill && shape.isPointInFill(point)) || (stroke && shape.isPointInStroke(point))
          })
      }
    }
    cached[kind] = checker
    constraintCache.set(el, cached)
    return checker
  }

  const visibleFractionOf = (el, bbox, contour, matrix) => {
    if (!contour || !contour.length) return null
    const constraints = []
    for (let node = el; node && node.nodeType === 1; node = node.parentNode) {
      const cs = getComputedStyle(node)
      for (const [kind, reference] of [
        ['clip', cs.clipPath],
        ['mask', cs.maskImage],
      ]) {
        if (!reference || reference === 'none') continue
        const checker = constraintOf(node, kind, reference)
        if (!checker) return null
        constraints.push(checker)
      }
    }
    if (!constraints.length) return 1
    const samples = paintedSamples(el, bbox, contour, matrix)
    if (!samples || !samples.length) return null
    return r(
      samples.filter((point) => constraints.every((checker) => checker(point))).length /
        samples.length,
    )
  }

  const rows = []
  let order = 0

  const walk = (el, parentPath) => {
    const tag = el.tagName.toLowerCase()
    if (!paints(el)) return

    const sameTag =
      parentPath === null
        ? []
        : Array.from(el.parentNode.children).filter((c) => c.tagName.toLowerCase() === tag)
    const idx = sameTag.indexOf(el)
    const seg = parentPath === null ? tag : `${tag}[${idx}]`
    const path = parentPath === null ? seg : `${parentPath}/${seg}`

    let ctm = null
    let rootMatrix = null
    try {
      const m = el.getScreenCTM()
      if (m && inv) {
        const l = inv.multiply(m)
        rootMatrix = l
        ctm = [r(l.a), r(l.b), r(l.c), r(l.d), r(l.e), r(l.f)]
      }
    } catch (e) {
      ctm = null
    }

    // CSS transforms are recorded separately from the transform attribute.
    let own = [1, 0, 0, 1, 0, 0]
    try {
      const c = el.transform.baseVal.consolidate()
      if (c)
        own = [
          r(c.matrix.a),
          r(c.matrix.b),
          r(c.matrix.c),
          r(c.matrix.d),
          r(c.matrix.e),
          r(c.matrix.f),
        ]
    } catch (e) {
      own = null
    }

    let bbox = null
    try {
      const b = el.getBBox()
      bbox = [r(b.x), r(b.y), r(b.width), r(b.height)]
    } catch (e) {
      bbox = null
    }

    let length = null
    let ends = null
    let localContour = null
    try {
      if (typeof el.getTotalLength === 'function') {
        // Cached geometry excludes transforms, which are applied afterward.
        const sig = reuseOutline ? outlineSignature(el, tag) : null
        const cached = sig === null ? null : outlineCache[path]
        if (cached && cached.sig === sig && cached.contour) {
          length = cached.length
          ends = cached.ends
          localContour = cached.contour
        } else {
          length = r(el.getTotalLength())
          const a = el.getPointAtLength(0)
          const b = el.getPointAtLength(length)
          ends = [
            [r(a.x), r(a.y)],
            [r(b.x), r(b.y)],
          ]
          localContour = sampleOutline(el, length, ends)
          if (sig !== null) outlineCache[path] = { sig, length, ends, contour: localContour }
        }
      }
    } catch (e) {
      length = null
      ends = null
      localContour = null
    }
    const contour = placePoints(localContour, rootMatrix)
    const strokeWidth = effectiveStrokeWidth(el, rootMatrix)

    const attrs = {}
    for (const a of el.attributes) attrs[a.name] = a.value

    const full = styleOf(el)
    let style = full
    if (baseline) {
      const base = baseline[path] || {}
      style = {}
      for (const k in full) if (full[k] !== base[k]) style[k] = full[k]
    }

    rows.push({
      path,
      tag,
      parent: parentPath,
      order: order++,
      ctm,
      own,
      bbox,
      length,
      ends,
      contour,
      stroke_width: strokeWidth,
      visible_fraction: visibleFractionOf(el, bbox, contour, rootMatrix),
      clip_box: chainTo(el, clipOf),
      mask_box: chainTo(el, maskOf),
      resource_inputs: resourceInputsOf(el),
      attrs,
      style,
    })

    for (const child of el.children) walk(child, path)
  }

  walk(root, null)

  const vb = root.getAttribute('viewBox')
  return {
    rows,
    canvas: {
      viewBox: vb
        ? vb
            .trim()
            .split(/[\s,]+/)
            .map(Number)
        : null,
      width: root.getAttribute('width'),
      height: root.getAttribute('height'),
    },
  }
}