@pixerate/editor 0.107.0 → 0.109.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/THIRD_PARTY_NOTICES.md +4 -0
- package/dist/animation/index.cjs +5 -5
- package/dist/animation/index.cjs.map +1 -1
- package/dist/animation/index.js +9 -9
- package/dist/animation-editor/index.cjs +59 -59
- package/dist/animation-editor/index.cjs.map +1 -1
- package/dist/animation-editor/index.d.cts +2 -1
- package/dist/animation-editor/index.d.ts +2 -1
- package/dist/animation-editor/index.js +29 -29
- package/dist/canvas/index.cjs +27 -27
- package/dist/canvas/index.cjs.map +1 -1
- package/dist/canvas/index.js +11 -11
- package/dist/{chunk-2FGRTYJN.cjs → chunk-477UVMNR.cjs} +3 -3
- package/dist/{chunk-2FGRTYJN.cjs.map → chunk-477UVMNR.cjs.map} +1 -1
- package/dist/{chunk-T3QZ6S47.cjs → chunk-AZTZRLDI.cjs} +40 -2
- package/dist/chunk-AZTZRLDI.cjs.map +1 -0
- package/dist/{chunk-63EFQCT5.js → chunk-BLWCAQCW.js} +2879 -3362
- package/dist/chunk-BLWCAQCW.js.map +1 -0
- package/dist/{chunk-G4BIYE6R.js → chunk-CFMWALBM.js} +39 -1
- package/dist/chunk-CFMWALBM.js.map +1 -0
- package/dist/{chunk-FRD3FUXI.cjs → chunk-D37BX2ZA.cjs} +2081 -460
- package/dist/chunk-D37BX2ZA.cjs.map +1 -0
- package/dist/chunk-JLYX4V57.cjs +2001 -0
- package/dist/chunk-JLYX4V57.cjs.map +1 -0
- package/dist/chunk-KB2YBCVS.js +2001 -0
- package/dist/chunk-KB2YBCVS.js.map +1 -0
- package/dist/{chunk-SOROZ2BF.js → chunk-RE77QYUF.js} +1938 -317
- package/dist/chunk-RE77QYUF.js.map +1 -0
- package/dist/{chunk-KANRAHTL.cjs → chunk-W3GXSUSQ.cjs} +2830 -3313
- package/dist/chunk-W3GXSUSQ.cjs.map +1 -0
- package/dist/{chunk-JK6M6V7G.js → chunk-Z3YWVUWT.js} +4 -4
- package/dist/{export-a9bnF7Cl.d.ts → export-BLPLaE6Z.d.ts} +417 -16
- package/dist/{export-JGWQEPJn.d.cts → export-DSUc4fQD.d.cts} +417 -16
- package/dist/image-editor/index.cjs +1527 -1001
- package/dist/image-editor/index.cjs.map +1 -1
- package/dist/image-editor/index.d.cts +73 -9
- package/dist/image-editor/index.d.ts +73 -9
- package/dist/image-editor/index.js +814 -288
- package/dist/image-editor/index.js.map +1 -1
- package/dist/paint-editor/index.cjs +252 -64
- package/dist/paint-editor/index.cjs.map +1 -1
- package/dist/paint-editor/index.d.cts +101 -4
- package/dist/paint-editor/index.d.ts +101 -4
- package/dist/paint-editor/index.js +196 -8
- package/dist/paint-editor/index.js.map +1 -1
- package/dist/raster/index.cjs +4 -2
- package/dist/raster/index.cjs.map +1 -1
- package/dist/raster/index.d.cts +3 -129
- package/dist/raster/index.d.ts +3 -129
- package/dist/raster/index.js +3 -1
- package/dist/{compositor-D92URMlm.d.cts → render-C-fO_mes.d.cts} +135 -1
- package/dist/{compositor-Kt_M4ruo.d.ts → render-OLIMk_v0.d.ts} +135 -1
- package/dist/{svg-vme0PLNo.d.ts → svg-D_cfkhlB.d.cts} +6 -608
- package/dist/{svg-Bj1MQFh6.d.cts → svg-wIaKLrU0.d.ts} +6 -608
- package/dist/types-DtL_qLFz.d.ts +630 -0
- package/dist/types-DyQq-WPY.d.cts +630 -0
- package/dist/vector/index.cjs +1080 -1051
- package/dist/vector/index.cjs.map +1 -1
- package/dist/vector/index.d.cts +268 -7
- package/dist/vector/index.d.ts +268 -7
- package/dist/vector/index.js +495 -466
- package/dist/vector/index.js.map +1 -1
- package/dist/video-editor/index.cjs +3 -3
- package/dist/video-editor/index.js +2 -2
- package/package.json +1 -1
- package/skills/pixerate-image-editor/SKILL.md +50 -7
- package/skills/pixerate-vector/SKILL.md +35 -5
- package/dist/chunk-63EFQCT5.js.map +0 -1
- package/dist/chunk-DWGZUSES.cjs +0 -694
- package/dist/chunk-DWGZUSES.cjs.map +0 -1
- package/dist/chunk-FRD3FUXI.cjs.map +0 -1
- package/dist/chunk-G4BIYE6R.js.map +0 -1
- package/dist/chunk-KANRAHTL.cjs.map +0 -1
- package/dist/chunk-KKREERP2.js +0 -694
- package/dist/chunk-KKREERP2.js.map +0 -1
- package/dist/chunk-SOROZ2BF.js.map +0 -1
- package/dist/chunk-T3QZ6S47.cjs.map +0 -1
- /package/dist/{chunk-JK6M6V7G.js.map → chunk-Z3YWVUWT.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/vector/types.ts","../src/vector/gradient.ts","../src/geom/affine.ts","../src/vector/corners.ts","../src/vector/width.ts","../src/vector/varstroke.ts","../src/vector/stroke.ts","../src/vector/paintLayers.ts","../src/vector/pathMap.ts","../src/vector/pathCut.ts","../src/vector/filters.ts","../src/vector/mask.ts","../src/geom/warp.ts","../src/vector/warp.ts","../src/vector/appearance.ts","../src/vector/geometry.ts","../src/vector/pathEffects.ts"],"sourcesContent":["import type { CanvasGradientDef } from '../canvas/gradient.js';\nimport type { WarpMesh, WarpStyle } from '../geom/types.js';\n\n/** An affine matrix `[a, b, c, d, e, f]`: `x' = a·x + c·y + e`, `y' = b·x + d·y + f` (SVG order). */\nexport type VectorMatrix = readonly [number, number, number, number, number, number];\n\n/** A point in document coordinates. */\nexport interface Vec2 {\n\tx: number;\n\ty: number;\n}\n\n/**\n * How an anchor's handles relate:\n * - `corner`: handles move independently (or are absent).\n * - `smooth`: handles stay on one line through the anchor, lengths independent.\n * - `symmetric`: handles stay on one line with equal lengths.\n */\nexport type VectorAnchorType = 'corner' | 'smooth' | 'symmetric';\n\n/**\n * Live corner shapes: `round` (an arc tangent to both sides), `inverted` (an arc centred on\n * the corner, cut into the shape) and `chamfer` (a straight bevel).\n */\nexport type VectorCornerKind = 'round' | 'inverted' | 'chamfer';\n\nexport const VECTOR_CORNER_KINDS: readonly VectorCornerKind[] = ['round', 'inverted', 'chamfer'];\n\n/**\n * A live corner: drawn rounded (or cut) at render, hit-test, bounds, boolean, outline and export\n * time while the stored anchor stays sharp. The radius shrinks to fit when the sides are short:\n * the cut reaches at most halfway along each side.\n */\nexport interface VectorCorner {\n\tradius: number;\n\t/** Default `round`. */\n\tkind?: VectorCornerKind;\n}\n\n/**\n * One anchor of a subpath. Handles are absolute document positions; a missing (or `null`)\n * handle sits on the anchor, so a segment with no handles at either end is a straight line.\n */\nexport interface VectorAnchor {\n\tx: number;\n\ty: number;\n\t/** Control point of the segment arriving at this anchor. */\n\tin?: Vec2 | null;\n\t/** Control point of the segment leaving this anchor. */\n\tout?: Vec2 | null;\n\t/** Default `corner`. */\n\ttype?: VectorAnchorType;\n\t/** Live corner radius. Ignored on smooth / symmetric anchors and the ends of open subpaths. */\n\tcorner?: VectorCorner | null;\n}\n\n/** A chain of anchors joined by line or cubic Bézier segments. */\nexport interface VectorSubpath {\n\tanchors: VectorAnchor[];\n\t/** Joins the last anchor back to the first. */\n\tclosed: boolean;\n}\n\n/**\n * Gradient styles: `linear` (start → end), `radial` (centred on the start, reaching the end;\n * focal point and aspect), `conic` (an angle sweep around the start, from the end's direction\n * towards the aspect handle's: clockwise on screen), `reflected` (linear mirrored about the\n * start) and `diamond` (`|u| + |v|` in the gradient's frame: a rhombus through the end and the\n * aspect handle).\n */\nexport type VectorGradientType = 'linear' | 'radial' | 'conic' | 'reflected' | 'diamond';\nexport const VECTOR_GRADIENT_TYPES: readonly VectorGradientType[] = ['linear', 'radial', 'conic', 'reflected', 'diamond'];\n\n/** What a gradient paints past its ends: the end colours, mirrored periods or repeated periods. */\nexport type VectorGradientSpread = 'pad' | 'reflect' | 'repeat';\nexport const VECTOR_GRADIENT_SPREADS: readonly VectorGradientSpread[] = ['pad', 'reflect', 'repeat'];\n\n/** Where colours mix between stops: sRGB (SVG's own), linear light or Oklab. */\nexport type VectorGradientInterpolation = 'srgb' | 'linear' | 'oklab';\nexport const VECTOR_GRADIENT_INTERPOLATIONS: readonly VectorGradientInterpolation[] = ['srgb', 'linear', 'oklab'];\n\n/**\n * The space a gradient's points are in: fractions of the shape's bounding box (SVG's\n * `objectBoundingBox`, the default) or the node's own coordinates (`userSpaceOnUse`).\n */\nexport type VectorGradientUnits = 'objectBoundingBox' | 'userSpaceOnUse';\n\n/**\n * How a gradient lies on a stroke: `within` (laid over the stroke's area like a fill), `along`\n * (t runs from 0 at the start of each subpath to 1 at its end) or `across` (from the stroke's\n * left edge to its right edge, looking along the path).\n */\nexport type VectorStrokeGradientMode = 'within' | 'along' | 'across';\nexport const VECTOR_STROKE_GRADIENT_MODES: readonly VectorStrokeGradientMode[] = ['within', 'along', 'across'];\n\n/** A colour stop. `opacity` multiplies the colour's own alpha. */\nexport interface VectorGradientStop {\n\t/** 0–1. */\n\toffset: number;\n\tcolor: string;\n\t/** 0–1, default 1. */\n\topacity?: number;\n\t/**\n\t * Where, between this stop and the next (0–1 of the way), the colour is half-way between\n\t * them. Default 0.5 (an even mix).\n\t */\n\tmidpoint?: number;\n}\n\n/**\n * A gradient paint. `CanvasGradientDef` (the canvas package's linear `angle` / radial\n * `cx, cy, r` gradients) is a valid value: those fields are the shorthand form. Explicit\n * geometry (`start` / `end`, in `units`) wins over the shorthand.\n */\nexport interface VectorGradient {\n\ttype: VectorGradientType;\n\tstops: VectorGradientStop[];\n\t/**\n\t * Shorthand direction in degrees, CSS style (0 points up, clockwise): a linear or reflected\n\t * gradient's direction across the box (default 180), a conic gradient's start angle or a\n\t * diamond's turn (default 90).\n\t */\n\tangle?: number;\n\t/** Shorthand centre and radius of radial, conic and diamond gradients (fractions of the box, default 0.5). */\n\tcx?: number;\n\tcy?: number;\n\tr?: number;\n\t/** Where t = 0: a linear gradient's start, the centre of the other styles. */\n\tstart?: Vec2;\n\t/** Where t = 1 along the gradient's main axis (a radial gradient's radius). */\n\tend?: Vec2;\n\t/**\n\t * The end of the secondary axis (radial, conic and diamond): its distance from `start` over\n\t * the main axis' length is the aspect ratio. Absent: square to the main axis, as long.\n\t */\n\twidth?: Vec2 | null;\n\t/** A radial gradient's focal point (where t = 0); absent: the centre. */\n\tfocal?: Vec2 | null;\n\t/** Radius of the focal circle as a fraction of the radius (SVG `fr`, default 0). */\n\tfocalRadius?: number;\n\t/** Space of `start`, `end`, `width` and `focal` (default `objectBoundingBox`). */\n\tunits?: VectorGradientUnits;\n\t/** Default `pad`. */\n\tspread?: VectorGradientSpread;\n\t/** Default `srgb`. */\n\tinterpolation?: VectorGradientInterpolation;\n\t/**\n\t * 0–1: how far the colours follow a smooth spline through the stops instead of straight\n\t * lines (Photoshop's Smoothness). Default 0.\n\t */\n\tsmoothness?: number;\n\t/** On a stroke: how the gradient lies on it (default `within`). Ignored on fills. */\n\tstrokeMode?: VectorStrokeGradientMode;\n}\n\n/** A fill or stroke: any CSS colour, a gradient, or `null` / `'none'` for no paint. */\nexport type VectorPaint = string | VectorGradient | CanvasGradientDef | null;\n\nexport type VectorFillRule = 'nonzero' | 'evenodd';\nexport type VectorLineCap = 'butt' | 'round' | 'square';\nexport type VectorLineJoin = 'miter' | 'round' | 'bevel';\n/**\n * Where the stroke sits on the outline: centred on it, inside the shape or outside it. Only\n * shapes whose subpaths are all closed have an inside; open paths always stroke centred.\n */\nexport type VectorStrokeAlign = 'center' | 'inside' | 'outside';\n/** Arrowheads and end markers for the ends of open paths. */\nexport type VectorArrowhead = 'triangle' | 'arrow' | 'open' | 'circle' | 'square' | 'bar';\nexport const VECTOR_ARROWHEADS: readonly VectorArrowhead[] = ['triangle', 'arrow', 'open', 'circle', 'square', 'bar'];\n/**\n * `extend`: the head's tip sits past the end point and the path keeps its length; `tip`: the\n * tip sits on the end point and the stroke is shortened under the head.\n */\nexport type VectorArrowAlign = 'extend' | 'tip';\n\n/**\n * One point of a variable-width stroke profile. `t` is the position along the subpath by\n * length (0 at its start, 1 at its end); `left` and `right` are how far the stroke reaches on\n * each side, as multiples of half the stroke width (looking along the path on screen, y down).\n * A uniform stroke has 1 on both sides. Two points at the same `t` make a step.\n */\nexport interface VectorWidthPoint {\n\tt: number;\n\tleft: number;\n\tright: number;\n}\n\n/**\n * Blend modes of paint layers and nodes: the set SVG and CSS `mix-blend-mode` draw, named as the\n * image editor names them (`@pixerate/editor/image-editor` `BlendMode`). `linear-dodge` draws as\n * CSS `plus-lighter`. The image editor's other modes (linear burn, vivid light, pigment, …) have\n * no SVG equivalent and are not offered.\n */\nexport type VectorBlendMode =\n\t| 'normal'\n\t| 'darken'\n\t| 'multiply'\n\t| 'color-burn'\n\t| 'lighten'\n\t| 'screen'\n\t| 'color-dodge'\n\t| 'linear-dodge'\n\t| 'overlay'\n\t| 'soft-light'\n\t| 'hard-light'\n\t| 'difference'\n\t| 'exclusion'\n\t| 'hue'\n\t| 'saturation'\n\t| 'color'\n\t| 'luminosity';\n/** Every vector blend mode, in the image editor's (Photoshop's) menu order. */\nexport const VECTOR_BLEND_MODES: readonly VectorBlendMode[] = [\n\t'normal',\n\t'darken',\n\t'multiply',\n\t'color-burn',\n\t'lighten',\n\t'screen',\n\t'color-dodge',\n\t'linear-dodge',\n\t'overlay',\n\t'soft-light',\n\t'hard-light',\n\t'difference',\n\t'exclusion',\n\t'hue',\n\t'saturation',\n\t'color',\n\t'luminosity'\n];\n\n/** One fill of a path's fill stack (`VectorStyle.fills`). */\nexport interface VectorPaintLayer {\n\t/** A colour, a gradient, or `null` for none. */\n\tpaint: VectorPaint;\n\t/** 0–1, default 1. Multiplies the paint's own alpha. */\n\topacity?: number;\n\t/** How the layer mixes with what is under it (the layers below, then the backdrop). Default `normal`. */\n\tblendMode?: VectorBlendMode;\n\t/** Hidden layers are kept but not drawn or hit. Default true. */\n\tvisible?: boolean;\n}\n\n/** The settings each stroke layer has of its own (the stroke shorthand fields of `VectorStyle`). */\nexport type VectorStrokeSettings = Pick<\n\tVectorStyle,\n\t| 'strokeWidth'\n\t| 'strokeLinecap'\n\t| 'strokeLinejoin'\n\t| 'strokeDasharray'\n\t| 'strokeAlign'\n\t| 'startArrow'\n\t| 'endArrow'\n\t| 'arrowAlign'\n\t| 'startArrowScale'\n\t| 'endArrowScale'\n\t| 'strokeWidthProfile'\n>;\n\n/**\n * What a stroke layer draws. Only `paint` (a paint along the outline, the default) exists today.\n * Other kinds are the extension point for strokes drawn some other way, such as a raster\n * brushstroke from `@pixerate/editor/paint` laid along the path: a layer with an unknown kind is\n * kept through edits, load and SVG round trips, listed to agents, and skipped when drawing and\n * hit-testing.\n */\nexport type VectorStrokeLayerKind = 'paint';\n\n/** One stroke of a path's stroke stack (`VectorStyle.strokes`): a paint plus its own stroke settings. */\nexport interface VectorStrokeLayer extends VectorPaintLayer, VectorStrokeSettings {\n\t/** Default `paint`. See `VectorStrokeLayerKind`. */\n\tkind?: VectorStrokeLayerKind;\n}\n\n/** Paint and stroke settings of a path. */\nexport interface VectorStyle {\n\tfill?: VectorPaint;\n\tstroke?: VectorPaint;\n\t/** Default 1. */\n\tstrokeWidth?: number;\n\tstrokeLinecap?: VectorLineCap;\n\tstrokeLinejoin?: VectorLineJoin;\n\tstrokeDasharray?: number[];\n\t/** Default `nonzero`. */\n\tfillRule?: VectorFillRule;\n\t/** Default `center`. */\n\tstrokeAlign?: VectorStrokeAlign;\n\t/** Head at the start of the first subpath when it is open, or none. */\n\tstartArrow?: VectorArrowhead | null;\n\t/** Head at the end of the last subpath when it is open, or none. */\n\tendArrow?: VectorArrowhead | null;\n\t/** Default `extend`. */\n\tarrowAlign?: VectorArrowAlign;\n\t/** Size of the start head as a multiple of the stroke width (default 1: a head 4 widths long). */\n\tstartArrowScale?: number;\n\t/** Size of the end head (default 1). */\n\tendArrowScale?: number;\n\t/**\n\t * Variable width: side scales along each subpath, interpolated with a monotone cubic (see\n\t * `widthProfileAt`). Absent, empty or `null` strokes at a uniform width. A profiled stroke is\n\t * drawn as its filled outline.\n\t */\n\tstrokeWidthProfile?: VectorWidthPoint[] | null;\n\t/**\n\t * The fill stack, bottom to top. Absent: `fill` alone is the stack (one layer, or none without\n\t * a paint). Present: it is the truth, and `fill` mirrors its top layer's paint. The shorthand\n\t * stays writable: setting `fill` to a paint repaints the top layer, `null` clears the stack.\n\t * Stacks of one plain layer (full opacity, `normal`, visible) are stored as the shorthand.\n\t */\n\tfills?: VectorPaintLayer[] | null;\n\t/**\n\t * The stroke stack, bottom to top, drawn over every fill. Like `fills`: absent, `stroke` and the\n\t * stroke settings above are the one stroke; present, they mirror its top layer, and writing them\n\t * edits that layer (`stroke: null` clears the stack).\n\t */\n\tstrokes?: VectorStrokeLayer[] | null;\n}\n\ninterface VectorNodeBase {\n\tid: string;\n\tname?: string;\n\t/** Default true. */\n\tvisible?: boolean;\n\t/** Locked nodes are drawn but cannot be picked or edited on the canvas. */\n\tlocked?: boolean;\n\t/** 0–1, default 1. */\n\topacity?: number;\n\t/**\n\t * Placement in the parent's space: a rigid matrix (rotation + translation). Anchors and\n\t * children are in the node's own space. Omitted for unrotated nodes, whose positions are\n\t * stored directly. Scale and skew are never stored here — `transformVectorNode` bakes\n\t * them into the geometry, so stroke widths and the rotated selection box stay exact.\n\t */\n\ttransform?: VectorMatrix;\n\t/**\n\t * An in-between a blend group generated from its keys. Steps are rebuilt whenever a key or\n\t * the blend options change, and are locked (clicks select the blend group).\n\t */\n\tblendStep?: boolean;\n\t/**\n\t * Live path effects, applied top to bottom: each acts on every path above it (the node's own\n\t * outline, or a group's children, then the result of the effects before it), and effects after a\n\t * repeater act on its copies. The stored anchors and children never change.\n\t */\n\teffects?: VectorEffect[] | null;\n\t/**\n\t * As an operand of a live boolean group: how it combines with the result of the operands below\n\t * it. Absent: the group's `liveBoolean` operation.\n\t */\n\tbooleanOperation?: VectorBooleanOperation | null;\n\t/** How the whole node (all its paint, filters included) mixes with what is under it. Default `normal`. */\n\tblendMode?: VectorBlendMode;\n\t/**\n\t * Visual filters (drop and inner shadows, glows, blurs, feather), applied to everything the\n\t * node draws. Unlike path `effects` they never change geometry: bounds, hit-testing and\n\t * booleans ignore them.\n\t */\n\tfilters?: VectorFilter[] | null;\n}\n\n/** A shape made of one or more subpaths (holes and compound shapes included). */\nexport interface VectorPathNode extends VectorNodeBase, VectorStyle {\n\ttype: 'path';\n\tsubpaths: VectorSubpath[];\n}\n\n/**\n * How a blend spaces its in-betweens: a number of `steps` between each pair of keys, a fixed\n * `distance` between steps along the spine, or `smoothColor` (as many steps as the colours\n * need for a smooth ramp; by distance when the colours match).\n */\nexport type VectorBlendSpacing = 'steps' | 'distance' | 'smoothColor';\nexport const VECTOR_BLEND_SPACINGS: readonly VectorBlendSpacing[] = ['steps', 'distance', 'smoothColor'];\n\n/** Settings of a blend. */\nexport interface VectorBlendOptions {\n\t/** Default `steps`. */\n\tspacing?: VectorBlendSpacing;\n\t/** Steps between each pair of keys with `steps` spacing (default 5). */\n\tsteps?: number;\n\t/** Distance between steps along the spine with `distance` spacing (default 20). */\n\tdistance?: number;\n\t/** Turn the steps with the spine's direction (default `false`: they keep the keys' orientation). */\n\torientToSpine?: boolean;\n\t/** Move anchors in straight lines instead of the rotation-aware morph (default `false`). */\n\tlinear?: boolean;\n}\n\n/** A live blend: the group's keys plus how the in-betweens are made and laid out. */\nexport interface VectorBlend extends VectorBlendOptions {\n\t/**\n\t * A replaced spine in the group's space: the steps follow it instead of the straight lines\n\t * between the keys' centres (the keys sit along it, spread evenly by arc length).\n\t */\n\tspine?: VectorSubpath | null;\n\t/** The anchor of each key's first subpath its blend starts from, by key id (the Blend tool's clicks). */\n\tstarts?: Record<string, number>;\n}\n\n/**\n * How a mask group's mask (its first, bottom child) hides the rest: `clip` (a clipping mask: the\n * mask's outline, fully opaque; its paint is not drawn), `alpha` (an opacity mask by the mask's\n * drawn alpha: soft edges, gradients and opacity count) or `luminance` (by its brightness times\n * its alpha: white shows, black hides).\n */\nexport type VectorMaskType = 'clip' | 'alpha' | 'luminance';\nexport const VECTOR_MASK_TYPES: readonly VectorMaskType[] = ['clip', 'alpha', 'luminance'];\n\n/** A group's mask settings (`VectorGroupNode.mask`). */\nexport interface VectorMask {\n\ttype: VectorMaskType;\n\t/** Show the contents where the mask hides them and hide them where it shows them. Default false. */\n\tinvert?: boolean;\n}\n\n/** A group of nodes that select and transform together. */\nexport interface VectorGroupNode extends VectorNodeBase {\n\ttype: 'group';\n\tchildren: VectorNode[];\n\t/**\n\t * Makes the group a live blend: its children that are not `blendStep`s are the keys, in\n\t * stacking order, and the steps between them are regenerated whenever a key changes.\n\t */\n\tblend?: VectorBlend | null;\n\t/**\n\t * Makes the group a live boolean: its children stay editable operands, folded bottom to top\n\t * (each by its own `booleanOperation` or this one), and the group draws as the result in the\n\t * bottom operand's style.\n\t */\n\tliveBoolean?: VectorBooleanOperation | null;\n\t/**\n\t * Makes the group a mask group: its first (bottom) child is the mask and the children above it\n\t * show only where the mask lets them (see `VectorMaskType`). Hit-testing, bounds, snapping and\n\t * booleans use the masked result. A hidden mask child turns the mask off (the contents draw\n\t * whole). The group's own opacity, blend mode and filters apply to the masked result, and its\n\t * path effects to the contents (not the mask). Ignored on blends and live booleans.\n\t */\n\tmask?: VectorMask | null;\n}\n\nexport type VectorNode = VectorPathNode | VectorGroupNode;\n\n/** A vector drawing: an artboard and its nodes, bottom to top. */\nexport interface VectorDocument {\n\twidth: number;\n\theight: number;\n\t/** Artboard colour (default: transparent). */\n\tbackground?: string;\n\tnodes: VectorNode[];\n}\n\n/** An axis-aligned rectangle. */\nexport interface VectorBounds {\n\tx: number;\n\ty: number;\n\twidth: number;\n\theight: number;\n}\n\n/** Identifies one anchor of a path node. */\nexport interface VectorAnchorRef {\n\tnodeId: string;\n\tsubpath: number;\n\tindex: number;\n}\n\n/** Identifies one handle of an anchor. */\nexport interface VectorHandleRef extends VectorAnchorRef {\n\thandle: 'in' | 'out';\n}\n\n/**\n * Canvas tools. `direct` edits anchors, handles and segments; the shape tools drag out a new\n * shape; `scissors` cuts a path at a point, `knife` cuts filled shapes along a freehand stroke,\n * `eraser` rubs out the area under one and `width` drags a stroke's width at a point.\n * `shapeBuilder` merges (Alt: deletes) the faces the selected shapes make, and `paintBucket`\n * fills the region the visible outlines enclose around a click with a new shape. `blend`\n * blends the shape clicked first into the one clicked next (clicking an anchor of a closed path\n * starts the blend there). `envelope` edits the mesh of the selection's envelope: drag its\n * anchors and handles, or inside a patch to pull the surface.\n */\nexport type VectorTool =\n\t| 'select'\n\t| 'direct'\n\t| 'pen'\n\t| 'pencil'\n\t| 'rect'\n\t| 'ellipse'\n\t| 'polygon'\n\t| 'star'\n\t| 'line'\n\t| 'scissors'\n\t| 'knife'\n\t| 'eraser'\n\t| 'width'\n\t| 'shapeBuilder'\n\t| 'paintBucket'\n\t| 'blend'\n\t| 'gradient'\n\t| 'envelope';\n\nexport const VECTOR_TOOLS: readonly VectorTool[] = [\n\t'select',\n\t'direct',\n\t'pen',\n\t'pencil',\n\t'rect',\n\t'ellipse',\n\t'polygon',\n\t'star',\n\t'line',\n\t'scissors',\n\t'knife',\n\t'eraser',\n\t'width',\n\t'shapeBuilder',\n\t'paintBucket',\n\t'blend',\n\t'gradient',\n\t'envelope'\n];\n\n/** Keyboard modifiers held during a pointer event. */\nexport interface VectorModifiers {\n\tshift?: boolean;\n\talt?: boolean;\n\t/** Cmd on macOS, Ctrl elsewhere. */\n\tmod?: boolean;\n}\n\n/** The eight resize handles of a selection box and the rotation handle. */\nexport type VectorTransformHandle = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w' | 'rotate';\n\nexport const VECTOR_TRANSFORM_HANDLES: readonly VectorTransformHandle[] = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'rotate'];\n\n/** Pan and zoom of the canvas: `screen = document × zoom + (x, y)`. */\nexport interface VectorViewport {\n\t/** Screen position of the document origin, in screen pixels. */\n\tx: number;\n\ty: number;\n\tzoom: number;\n}\n\n/** What the next shape and pen path are drawn with. */\nexport interface VectorDefaults extends VectorStyle {\n\t/** Sides of the polygon tool (default 6). */\n\tpolygonSides?: number;\n\t/** Points of the star tool (default 5). */\n\tstarPoints?: number;\n\t/** Inner radius of the star tool as a fraction of the outer one (default 0.5). */\n\tstarInnerRatio?: number;\n\t/** Live corner radius the rectangle, polygon and star tools give their corners (default 0). */\n\tcornerRadius?: number;\n\t/** Corner kind of those tools (default `round`). */\n\tcornerKind?: VectorCornerKind;\n}\n\nexport type VectorAlign = 'left' | 'center' | 'right' | 'top' | 'middle' | 'bottom';\nexport type VectorDistribute = 'horizontal' | 'vertical';\nexport type VectorBooleanOperation = 'union' | 'subtract' | 'intersect' | 'exclude';\n/**\n * Pathfinder operations: `divide` (every face its own shape), `trim` (hidden parts removed),\n * `merge` (Trim, then touching parts of one fill joined), `crop` (the top shape crops the others),\n * `outline` (outlines cut into open strokes where they meet) and `minusBack` (the top shape minus\n * everything below it).\n */\nexport type VectorPathfinderOperation = 'divide' | 'trim' | 'merge' | 'crop' | 'outline' | 'minusBack';\nexport const VECTOR_PATHFINDER_OPERATIONS: readonly VectorPathfinderOperation[] = ['divide', 'trim', 'merge', 'crop', 'outline', 'minusBack'];\nexport type VectorArrange = 'front' | 'forward' | 'backward' | 'back';\n/** Average: line anchors up on a horizontal line (same y), a vertical one (same x), or both. */\nexport type VectorAverageAxis = 'horizontal' | 'vertical' | 'both';\n\n/**\n * Live path effects (After Effects' path operators): `trim` (Trim Paths), `roundCorners`,\n * `puckerBloat`, `twist`, `zigzag`, `wiggle` (Wiggle Paths), `offset` (Offset Paths), `merge`\n * (Merge Paths), `repeater` and `envelope` (an envelope distortion: a warp preset or a mesh).\n */\nexport type VectorEffectType = 'trim' | 'roundCorners' | 'puckerBloat' | 'twist' | 'zigzag' | 'wiggle' | 'offset' | 'merge' | 'repeater' | 'envelope';\nexport const VECTOR_EFFECT_TYPES: readonly VectorEffectType[] = ['trim', 'roundCorners', 'puckerBloat', 'twist', 'zigzag', 'wiggle', 'offset', 'merge', 'repeater', 'envelope'];\n\n/** Warp presets (Photoshop's fifteen, in menu order); shared with the image editor (`src/geom`). */\nexport type VectorWarpStyle = WarpStyle;\n\n/**\n * A grid of bicubic Bézier patches mapping a source box onto the plane. `us` / `vs` are the patch\n * boundaries as fractions of the box (increasing, first 0, last 1); `points` is the\n * `(3·(us.length − 1) + 1) × (3·(vs.length − 1) + 1)` control grid, row by row, in the node's own\n * space. Neighbouring patches share their edge row: anchors sit where both indices are multiples\n * of 3, handles where one is. Shared with the image editor (`src/geom`).\n */\nexport type VectorWarpMesh = WarpMesh;\n\n/** Merge Paths modes: a compound path (no boolean), union, the first minus the others, intersection or exclusion. */\nexport type VectorMergeMode = 'merge' | 'add' | 'subtract' | 'intersect' | 'exclude';\nexport const VECTOR_MERGE_MODES: readonly VectorMergeMode[] = ['merge', 'add', 'subtract', 'intersect', 'exclude'];\n\n/** Parameters of each effect type. Lengths are in the node's own units, angles in degrees, percentages 0–100. */\nexport interface VectorEffectParamsMap {\n\ttrim: {\n\t\t/** Start and end of the kept part, percent of the length (swapped when start > end). */\n\t\tstart: number;\n\t\tend: number;\n\t\t/** Shifts both, in degrees (360° = once round). */\n\t\toffset: number;\n\t\t/**\n\t\t * `simultaneous`: every path trimmed by the same fractions of its own length;\n\t\t * `individual`: the paths laid end to end in stacking order and trimmed as one length.\n\t\t */\n\t\tmode: 'simultaneous' | 'individual';\n\t};\n\troundCorners: { radius: number };\n\t/** Percent, −100 (pucker: spiky) to 100 (bloat: bulging). */\n\tpuckerBloat: { amount: number };\n\ttwist: {\n\t\t/** Turn at the farthest point from the centre (none at the centre). */\n\t\tangle: number;\n\t\t/** The centre as an offset from the middle of the paths' bounds. */\n\t\tcenter: Vec2;\n\t};\n\tzigzag: {\n\t\t/** How far the points move to either side. */\n\t\tsize: number;\n\t\t/** Ridges per segment. */\n\t\tridges: number;\n\t\t/** Rounded waves instead of sharp zig zags. */\n\t\tsmooth: boolean;\n\t};\n\twiggle: {\n\t\t/** Largest displacement. */\n\t\tsize: number;\n\t\t/** Points added per segment. */\n\t\tdetail: number;\n\t\tsmooth: boolean;\n\t\t/** Wiggles per second. */\n\t\tspeed: number;\n\t\t/** Percent: how much neighbouring points move together. */\n\t\tcorrelation: number;\n\t\t/** Degrees (360° = one wiggle). */\n\t\tphase: number;\n\t\t/** The same seed (and time) always gives the same wiggle. */\n\t\tseed: number;\n\t\t/** Seconds: where along the wiggle's motion it is drawn. */\n\t\ttime: number;\n\t};\n\toffset: {\n\t\t/** Grows (positive) or shrinks (negative) the shapes. */\n\t\tamount: number;\n\t\tjoin: VectorLineJoin;\n\t\tmiterLimit: number;\n\t\t/** Copies, copy i offset by `amount · (i + 1 + copyOffset)`. */\n\t\tcopies: number;\n\t\tcopyOffset: number;\n\t};\n\tmerge: { mode: VectorMergeMode };\n\trepeater: {\n\t\t/** Copies, the original included; a fraction fades the last copy. */\n\t\tcopies: number;\n\t\t/** Shifts the copies along: copy i is transformed `i + offset` times. */\n\t\toffset: number;\n\t\t/** Each step: move, about `anchor` turn by `rotation` and scale by `scale` percent. */\n\t\tposition: Vec2;\n\t\t/** Offset from the middle of the paths' bounds. */\n\t\tanchor: Vec2;\n\t\trotation: number;\n\t\tscale: Vec2;\n\t\t/** Percent opacity of the first and last copies (in between interpolated). */\n\t\tstartOpacity: number;\n\t\tendOpacity: number;\n\t\t/** `below`: each copy draws under the one before it; `above`: over it. */\n\t\tcomposite: 'below' | 'above';\n\t};\n\t/**\n\t * Envelope distortion: the paths above it are mapped from their combined bounds through a warp\n\t * preset (bend and horizontal / vertical distortion in percent) or, with style `mesh`, through\n\t * `mesh` (null: the flat mesh of `columns × rows` patches over the bounds). The bounds are\n\t * taken afresh each time, so editing the contents keeps the envelope.\n\t */\n\tenvelope: {\n\t\tstyle: VectorWarpStyle | 'mesh';\n\t\tbend: number;\n\t\thorizontal: number;\n\t\tvertical: number;\n\t\torientation: 'horizontal' | 'vertical';\n\t\t/** Patches of the mesh (a preset turns into a mesh of this size when it is edited). */\n\t\trows: number;\n\t\tcolumns: number;\n\t\tmesh: VectorWarpMesh | null;\n\t};\n}\n\n/** One entry of an effect stack. */\nexport type VectorEffect = {\n\t[K in VectorEffectType]: {\n\t\t/** Unique within the node. */\n\t\tid: string;\n\t\ttype: K;\n\t\t/** Disabled effects are skipped. Default true. */\n\t\tenabled?: boolean;\n\t\tparams: VectorEffectParamsMap[K];\n\t};\n}[VectorEffectType];\n\n/** Identifies one segment of a path node: from anchor `segment` to the next. */\nexport interface VectorSegmentRef {\n\tnodeId: string;\n\tsubpath: number;\n\tsegment: number;\n}\n\n/**\n * Visual filters: `dropShadow` (the node's silhouette, offset and blurred, under it),\n * `innerShadow` (a shadow cast inside the edges), `outerGlow` / `innerGlow` (an unoffset glow\n * outside or inside the edges), `layerBlur` (the whole node blurred) and `feather` (edges faded\n * to transparent).\n */\nexport type VectorFilterType = 'dropShadow' | 'innerShadow' | 'outerGlow' | 'innerGlow' | 'layerBlur' | 'feather';\nexport const VECTOR_FILTER_TYPES: readonly VectorFilterType[] = ['dropShadow', 'innerShadow', 'outerGlow', 'innerGlow', 'layerBlur', 'feather'];\n\n/** A shadow or glow: colour, offset, blur and spread in the node's own units. */\ninterface VectorShadowParams {\n\tcolor: string;\n\t/** 0–1: multiplies the colour's own alpha. */\n\topacity: number;\n\t/** Blur radius (the SVG / CSS standard deviation is half of it). */\n\tblur: number;\n\t/** Grows the silhouette before blurring (inner effects: chokes it inwards). */\n\tspread: number;\n}\n\n/** Parameters of each filter type. Lengths are in the node's own units. */\nexport interface VectorFilterParamsMap {\n\tdropShadow: VectorShadowParams & { offsetX: number; offsetY: number };\n\tinnerShadow: VectorShadowParams & { offsetX: number; offsetY: number };\n\touterGlow: VectorShadowParams;\n\tinnerGlow: VectorShadowParams;\n\tlayerBlur: { radius: number };\n\t/** Fades the edges over `radius` inwards. */\n\tfeather: { radius: number };\n}\n\n/** One entry of a node's filter stack. */\nexport type VectorFilter = {\n\t[K in VectorFilterType]: {\n\t\t/** Unique within the node. */\n\t\tid: string;\n\t\ttype: K;\n\t\t/** Disabled filters are skipped. Default true. */\n\t\tenabled?: boolean;\n\t\tparams: VectorFilterParamsMap[K];\n\t};\n}[VectorFilterType];\n","/**\n * Vector gradients: sampling (stop midpoints, smoothness, sRGB / linear-light / Oklab\n * interpolation), geometry (a three-point frame: start, end and the secondary-axis \"width\"\n * point, in the shape's bounding box or its own space; focal point and radius), spread modes and\n * DOM-free SVG paint servers for every style.\n *\n * Linear and radial gradients become `<linearGradient>` / `<radialGradient>` in\n * `userSpaceOnUse` with a `gradientTransform` (so fill, stroke parts and effect copies share one\n * frame, and a box with no height still paints). Midpoints, smoothness and non-sRGB\n * interpolation are not native to SVG: they export as extra stops (`expandVectorGradientStops`)\n * close to the true curve. Reflected gradients are a linear gradient with mirrored stops (or\n * `spreadMethod=\"reflect\"`). Conic and diamond gradients have no SVG element: they become a\n * `<pattern>` in user space whose tiles each carry a linear gradient — 4 exact quadrants for a\n * diamond (t = |u| + |v| is linear in each), thin wedges for a conic gradient.\n *\n * Ported (re-expressed in TypeScript) from the ArtCraft apps (MIT OR Apache-2.0, see\n * THIRD_PARTY_NOTICES.md): vectorcraft `crates/color/src/gradient.rs` (`Gradient::sample_with`\n * midpoint mapping, `expanded_stops`, `reverse`, `span`, stop editing helpers and\n * `GradientGeom::param_at` / `set_focal`), photocraft `crates/compose/src/gradient_fill.rs`\n * (`midpoint_remap`, the Linear / Radial / Angle / Reflected / Diamond styles of `gradient_t`),\n * photocraft `crates/io/src/gradient_bake.rs` (`eval`: smoothness as a Catmull-Rom blend and the\n * interpolation spaces), effectcraft `crates/render/src/shapes.rs` (`GradientRamp::t`, the focal\n * ray), figcraft `crates/color/src/lib.rs` (`GradientKind` angular / diamond and the three-handle\n * unit-box frame) and vectorcraft `crates/svg/src/import/spread.rs` (`expand`: spread modes as\n * repeated stop periods).\n */\nimport { hexToRgba, normalizeTokenColor, rgbaToHex } from '../tokens/color.js';\nimport { rgbToOklab, oklabToRgb } from '../animation/color.js';\nimport { angleToSvgLinearCoords, type SvgGradientDef, type SvgGradientStop } from '../canvas/gradient.js';\nimport type {\n\tVec2,\n\tVectorBounds,\n\tVectorGradient,\n\tVectorGradientInterpolation,\n\tVectorGradientSpread,\n\tVectorGradientStop,\n\tVectorGradientType,\n\tVectorGradientUnits,\n\tVectorMatrix,\n\tVectorPaint\n} from './types.js';\nimport { VECTOR_GRADIENT_INTERPOLATIONS, VECTOR_GRADIENT_SPREADS, VECTOR_GRADIENT_TYPES, VECTOR_STROKE_GRADIENT_MODES } from './types.js';\n\n\n// ---------------------------------------------------------------------------\n// Small maths\n// ---------------------------------------------------------------------------\n\nconst clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));\nconst IDENTITY: VectorMatrix = [1, 0, 0, 1, 0, 0];\n/** `a` then `b`. */\nconst mul = (a: VectorMatrix, b: VectorMatrix): VectorMatrix => [\n\tb[0] * a[0] + b[2] * a[1],\n\tb[1] * a[0] + b[3] * a[1],\n\tb[0] * a[2] + b[2] * a[3],\n\tb[1] * a[2] + b[3] * a[3],\n\tb[0] * a[4] + b[2] * a[5] + b[4],\n\tb[1] * a[4] + b[3] * a[5] + b[5]\n];\nconst apply = (m: VectorMatrix, p: Vec2): Vec2 => ({ x: m[0] * p.x + m[2] * p.y + m[4], y: m[1] * p.x + m[3] * p.y + m[5] });\nconst invert = (m: VectorMatrix): VectorMatrix | null => {\n\tconst [a, b, c, d, e, f] = m;\n\tconst det = a * d - b * c;\n\tif (!Number.isFinite(det) || Math.abs(det) < 1e-18) return null;\n\treturn [d / det, -b / det, -c / det, a / det, (c * f - d * e) / det, (b * e - a * f) / det];\n};\nconst isIdentity = (m: VectorMatrix) => m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1 && m[4] === 0 && m[5] === 0;\nconst sub = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x - b.x, y: a.y - b.y });\nconst add = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x + b.x, y: a.y + b.y });\nconst scale = (a: Vec2, k: number): Vec2 => ({ x: a.x * k, y: a.y * k });\nconst dot = (a: Vec2, b: Vec2) => a.x * b.x + a.y * b.y;\n/** 90° clockwise on screen (y down): the secondary axis of a frame. */\nconst perp = (v: Vec2): Vec2 => ({ x: -v.y, y: v.x });\nconst finitePoint = (p: unknown): p is Vec2 => !!p && typeof p === 'object' && Number.isFinite((p as Vec2).x) && Number.isFinite((p as Vec2).y);\n\nconst fmt = (n: number, digits = 4) => {\n\tconst k = 10 ** digits;\n\tconst v = Math.round(n * k) / k;\n\treturn Object.is(v, -0) ? '0' : String(v);\n};\nconst fmtMatrix = (m: VectorMatrix) => `matrix(${m.map((n) => fmt(n, 6)).join(' ')})`;\n\n/** True when `paint` is a gradient (any style). */\nexport function isVectorGradient(paint: VectorPaint | undefined): paint is VectorGradient {\n\treturn !!paint && typeof paint === 'object' && VECTOR_GRADIENT_TYPES.includes((paint as VectorGradient).type) && Array.isArray((paint as VectorGradient).stops);\n}\n\n// ---------------------------------------------------------------------------\n// Colours and interpolation spaces\n// ---------------------------------------------------------------------------\n\n/** Straight-alpha sRGB channels, 0–1. */\nexport type VectorRgba = [number, number, number, number];\n\n/** A CSS colour as 0–1 channels (hex, `rgb()`, `transparent`, `black`, `white`), or null. */\nexport function parseVectorColor(color: string): VectorRgba | null {\n\tconst hex = normalizeTokenColor(color);\n\tif (hex === null) return null;\n\tconst c = hexToRgba(hex)!;\n\treturn [c.r, c.g, c.b, c.a];\n}\n\nconst toLinear = (c: number) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4);\nconst toGamma = (c: number) => {\n\tconst v = clamp(c, 0, 1);\n\treturn v <= 0.0031308 ? 12.92 * v : 1.055 * v ** (1 / 2.4) - 0.055;\n};\n\nfunction intoSpace(space: VectorGradientInterpolation, [r, g, b]: readonly number[]): [number, number, number] {\n\tif (space === 'linear') return [toLinear(r), toLinear(g), toLinear(b)];\n\tif (space === 'oklab') {\n\t\tconst c = rgbToOklab(r, g, b);\n\t\treturn [c.l, c.a, c.b];\n\t}\n\treturn [r, g, b];\n}\n\nfunction outOfSpace(space: VectorGradientInterpolation, [x, y, z]: readonly number[]): [number, number, number] {\n\tif (space === 'linear') return [toGamma(x), toGamma(y), toGamma(z)];\n\tif (space === 'oklab') {\n\t\tconst c = oklabToRgb({ l: x, a: y, b: z, alpha: 1 });\n\t\treturn [c.r, c.g, c.b];\n\t}\n\treturn [clamp(x, 0, 1), clamp(y, 0, 1), clamp(z, 0, 1)];\n}\n\n// ---------------------------------------------------------------------------\n// Stops\n// ---------------------------------------------------------------------------\n\n/** Least and most a midpoint can be (the stop editors clamp further, to 0.05–0.95). */\nconst MID_MIN = 0.01;\nconst MID_MAX = 0.99;\n/** Fewest stops a gradient keeps when one is removed. */\nexport const VECTOR_GRADIENT_MIN_STOPS = 2;\n\n/**\n * Where relative position `u` of a segment lands once its midpoint is `m` (0.5 = unchanged): the\n * colour is half-way at `m`, linear on either side (photocraft `midpoint_remap`).\n */\nexport function gradientMidpointRemap(u: number, m: number): number {\n\tconst mid = clamp(m, MID_MIN, MID_MAX);\n\tif (Math.abs(mid - 0.5) < 1e-6) return u;\n\treturn u <= mid ? (0.5 * u) / mid : 0.5 + (0.5 * (u - mid)) / (1 - mid);\n}\n\nconst hasMidpoint = (s: VectorGradientStop) => s.midpoint !== undefined && Number.isFinite(s.midpoint) && Math.abs(s.midpoint - 0.5) > 1e-3;\n\n/** The stops sorted by offset (stable), offsets clamped to 0–1, unreadable offsets dropped. */\nexport function sortedVectorGradientStops(g: Pick<VectorGradient, 'stops'>): VectorGradientStop[] {\n\treturn (g.stops ?? [])\n\t\t.filter((s) => s && Number.isFinite(s.offset) && typeof s.color === 'string')\n\t\t.map((s, i) => ({ s: { ...s, offset: clamp(s.offset, 0, 1) }, i }))\n\t\t.sort((a, b) => a.s.offset - b.s.offset || a.i - b.i)\n\t\t.map((e) => e.s);\n}\n\n/** Does the gradient need extra stops to look the same in SVG (midpoints, smoothness or a non-sRGB space)? */\nexport function vectorGradientNeedsExpansion(g: VectorGradient): boolean {\n\treturn (g.interpolation ?? 'srgb') !== 'srgb' || (g.smoothness ?? 0) > 0 || (g.stops ?? []).some(hasMidpoint);\n}\n\ninterface RampPoint {\n\tt: number;\n\t/** Colour channels in the interpolation space. */\n\tv: [number, number, number];\n\t/** Colour alpha × opacity. */\n\ta: number;\n\tmid: number;\n}\n\n/** A gradient's colour ramp, prepared for sampling. */\nexport interface VectorGradientRamp {\n\t/** Straight-alpha sRGB at `t` (clamped to 0–1). */\n\tsample(t: number): VectorRgba;\n}\n\n/**\n * The colour ramp of a gradient (midpoints, smoothness and interpolation space applied), or null\n * when a stop colour is not one `parseVectorColor` reads.\n */\nexport function vectorGradientRamp(g: Pick<VectorGradient, 'stops' | 'interpolation' | 'smoothness'>): VectorGradientRamp | null {\n\tconst space = g.interpolation && VECTOR_GRADIENT_INTERPOLATIONS.includes(g.interpolation) ? g.interpolation : 'srgb';\n\tconst smooth = clamp(Number.isFinite(g.smoothness) ? (g.smoothness as number) : 0, 0, 1);\n\tconst pts: RampPoint[] = [];\n\tfor (const s of sortedVectorGradientStops(g)) {\n\t\tconst c = parseVectorColor(s.color);\n\t\tif (!c) return null;\n\t\tpts.push({ t: s.offset, v: intoSpace(space, c), a: c[3] * clamp(s.opacity ?? 1, 0, 1), mid: s.midpoint ?? 0.5 });\n\t}\n\treturn {\n\t\tsample(t: number): VectorRgba {\n\t\t\tconst n = pts.length;\n\t\t\tif (!n) return [0, 0, 0, 0];\n\t\t\tconst first = pts[0];\n\t\t\tconst last = pts[n - 1];\n\t\t\tconst at = (p: RampPoint): VectorRgba => [...outOfSpace(space, p.v), p.a] as VectorRgba;\n\t\t\tif (!(t > first.t) || n < 2) return at(first);\n\t\t\tif (t >= last.t) return at(last);\n\t\t\tlet i = 0;\n\t\t\twhile (i + 2 < n && !(t >= pts[i].t && t <= pts[i + 1].t)) i++;\n\t\t\tconst p0 = pts[i];\n\t\t\tconst p1 = pts[i + 1];\n\t\t\tconst h = Math.max(p1.t - p0.t, 1e-6);\n\t\t\tconst u = gradientMidpointRemap((t - p0.t) / h, p0.mid);\n\t\t\tconst alpha = p0.a + (p1.a - p0.a) * u;\n\t\t\tif (smooth <= 0) return [...outOfSpace(space, [0, 1, 2].map((c) => p0.v[c] + (p1.v[c] - p0.v[c]) * u)), alpha] as VectorRgba;\n\t\t\t// Catmull-Rom tangents per unit t; the ends use half the chord slope (gradient_bake `eval`).\n\t\t\tconst tangent = (k: number) => {\n\t\t\t\tconst [a, b] = k === 0 ? [0, 1] : k === n - 1 ? [n - 2, n - 1] : [k - 1, k + 1];\n\t\t\t\tconst d = Math.max(pts[b].t - pts[a].t, 1e-6);\n\t\t\t\tconst half = k === 0 || k === n - 1 ? 0.5 : 1;\n\t\t\t\treturn [0, 1, 2].map((c) => ((pts[b].v[c] - pts[a].v[c]) / d) * half);\n\t\t\t};\n\t\t\tconst m0 = tangent(i);\n\t\t\tconst m1 = tangent(i + 1);\n\t\t\tconst u2 = u * u;\n\t\t\tconst u3 = u2 * u;\n\t\t\tconst h00 = 2 * u3 - 3 * u2 + 1;\n\t\t\tconst h10 = u3 - 2 * u2 + u;\n\t\t\tconst h01 = -2 * u3 + 3 * u2;\n\t\t\tconst h11 = u3 - u2;\n\t\t\tconst v = [0, 1, 2].map((c) => {\n\t\t\t\tconst linear = p0.v[c] + (p1.v[c] - p0.v[c]) * u;\n\t\t\t\tconst spline = h00 * p0.v[c] + h10 * h * m0[c] + h01 * p1.v[c] + h11 * h * m1[c];\n\t\t\t\tconst value = linear + (spline - linear) * smooth;\n\t\t\t\t// Smoothness bends the ramp without inventing colours outside the segment.\n\t\t\t\treturn clamp(value, Math.min(p0.v[c], p1.v[c]), Math.max(p0.v[c], p1.v[c]));\n\t\t\t});\n\t\t\treturn [...outOfSpace(space, v), alpha] as VectorRgba;\n\t\t}\n\t};\n}\n\n/** What the gradient paints at `t` (0–1 along its stops): `#rrggbb` and opacity. */\nexport function sampleVectorGradient(g: VectorGradient, t: number): { color: string; opacity: number } {\n\tconst ramp = vectorGradientRamp(g);\n\tif (ramp) {\n\t\tconst [r, gg, b, a] = ramp.sample(t);\n\t\treturn { color: rgbaToHex(r, gg, b), opacity: a };\n\t}\n\t// Unreadable colours: the nearest stop at or before `t`.\n\tconst stops = sortedVectorGradientStops(g);\n\tconst s = [...stops].reverse().find((x) => x.offset <= t) ?? stops[0];\n\treturn s ? { color: s.color, opacity: s.opacity ?? 1 } : { color: '#000000', opacity: 0 };\n}\n\nconst stopOf = (offset: number, c: VectorRgba): VectorGradientStop => {\n\tconst color = rgbaToHex(c[0], c[1], c[2]);\n\tconst opacity = Math.round(c[3] * 1e4) / 1e4;\n\treturn opacity < 1 ? { offset, color, opacity } : { offset, color };\n};\n\nconst maxDiff = (a: VectorRgba, b: VectorRgba) => Math.max(Math.abs(a[0] - b[0]), Math.abs(a[1] - b[1]), Math.abs(a[2] - b[2]), Math.abs(a[3] - b[3]));\nconst lerpRgba = (a: VectorRgba, b: VectorRgba, u: number): VectorRgba => [0, 1, 2, 3].map((c) => a[c] + (b[c] - a[c]) * u) as VectorRgba;\n\n/**\n * Plain stops (no midpoints) that SVG's sRGB interpolation turns into the gradient's colours:\n * the stops as they are when nothing needs expanding; one extra stop per off-centre midpoint for\n * sRGB without smoothness (exact: the midpoint makes each half linear); otherwise stops placed\n * adaptively until linear interpolation between them is within `tolerance` (0–1 per channel,\n * default half a level) of the true curve everywhere they were checked.\n */\nexport function expandVectorGradientStops(g: VectorGradient, options: { tolerance?: number } = {}): VectorGradientStop[] {\n\tconst stops = sortedVectorGradientStops(g);\n\tconst plain = () => stops.map(({ offset, color, opacity }) => (opacity !== undefined && opacity !== 1 ? { offset, color, opacity } : { offset, color }));\n\tif (!vectorGradientNeedsExpansion(g)) return plain();\n\tconst ramp = vectorGradientRamp(g);\n\tif (!ramp || stops.length < 2) return plain();\n\tconst tol = options.tolerance ?? 0.5 / 255;\n\tconst sRgbOnly = (g.interpolation ?? 'srgb') === 'srgb' && !((g.smoothness ?? 0) > 0);\n\tconst own = (s: VectorGradientStop): VectorRgba => {\n\t\tconst c = parseVectorColor(s.color)!;\n\t\treturn [c[0], c[1], c[2], c[3] * clamp(s.opacity ?? 1, 0, 1)];\n\t};\n\tconst out: VectorGradientStop[] = [];\n\tconst push = (offset: number, c: VectorRgba) => out.push(stopOf(offset, c));\n\tfor (let i = 0; i < stops.length; i++) {\n\t\tconst a = stops[i];\n\t\tconst b = stops[i + 1];\n\t\tpush(a.offset, own(a));\n\t\tif (!b || b.offset - a.offset < 1e-9) continue;\n\t\tconst knots = [a.offset];\n\t\tif (hasMidpoint(a)) knots.push(a.offset + (b.offset - a.offset) * clamp(a.midpoint!, MID_MIN, MID_MAX));\n\t\tknots.push(b.offset);\n\t\t// Samples just inside the segment (the ramp at its ends is the neighbouring segment's).\n\t\tconst inside = (t: number) => ramp.sample(clamp(t, a.offset + 1e-9, b.offset - 1e-9));\n\t\tfor (let k = 0; k + 1 < knots.length; k++) {\n\t\t\tconst t0 = knots[k];\n\t\t\tconst t1 = knots[k + 1];\n\t\t\tif (k > 0) push(t0, inside(t0));\n\t\t\tif (sRgbOnly) continue;\n\t\t\tconst refine = (x0: number, c0: VectorRgba, x1: number, c1: VectorRgba, depth: number) => {\n\t\t\t\tconst xm = (x0 + x1) / 2;\n\t\t\t\tconst cm = inside(xm);\n\t\t\t\t// Checked near the ends too: gamma curves bend hardest next to a black channel.\n\t\t\t\tconst ok = depth >= 8 || [0.03, 0.1, 0.25, 0.5, 0.75, 0.9, 0.97].every((f) => maxDiff(inside(x0 + (x1 - x0) * f), lerpRgba(c0, c1, f)) <= tol);\n\t\t\t\tif (ok) return;\n\t\t\t\trefine(x0, c0, xm, cm, depth + 1);\n\t\t\t\tpush(xm, cm);\n\t\t\t\trefine(xm, cm, x1, c1, depth + 1);\n\t\t\t};\n\t\t\trefine(t0, inside(t0), t1, inside(t1), 0);\n\t\t}\n\t}\n\treturn out;\n}\n\n/** Linear interpolation between plain stops (what SVG draws from them), straight alpha. */\nexport function samplePlainStops(stops: readonly VectorGradientStop[], t: number): VectorRgba {\n\tconst parsed = stops.map((s) => {\n\t\tconst c = parseVectorColor(s.color) ?? [0, 0, 0, 1];\n\t\treturn { t: s.offset, c: [c[0], c[1], c[2], c[3] * (s.opacity ?? 1)] as VectorRgba };\n\t});\n\tif (!parsed.length) return [0, 0, 0, 0];\n\tif (t <= parsed[0].t) return parsed[0].c;\n\tfor (let i = 0; i + 1 < parsed.length; i++) {\n\t\tconst a = parsed[i];\n\t\tconst b = parsed[i + 1];\n\t\tif (t <= b.t) return b.t - a.t < 1e-12 ? b.c : lerpRgba(a.c, b.c, (t - a.t) / (b.t - a.t));\n\t}\n\treturn parsed[parsed.length - 1].c;\n}\n\n/** The gradient with its stops reversed, each midpoint measured from the other side (vectorcraft `reverse`). */\nexport function reverseVectorGradient<T extends Pick<VectorGradient, 'stops'>>(g: T): T {\n\tconst stops = sortedVectorGradientStops(g).reverse();\n\tconst next = stops.map((s, i) => {\n\t\tconst following = stops[i + 1];\n\t\tconst mid = following ? 1 - (following.midpoint ?? 0.5) : 0.5;\n\t\tconst { midpoint: _m, ...rest } = s;\n\t\treturn { ...rest, offset: 1 - s.offset, ...(Math.abs(mid - 0.5) > 1e-6 ? { midpoint: mid } : {}) };\n\t});\n\treturn { ...g, stops: next };\n}\n\n/** Stops with `stop` placed by offset (after any at the same offset); returns its index. */\nfunction placeStop(stops: VectorGradientStop[], stop: VectorGradientStop): number {\n\tlet i = stops.findIndex((o) => o.offset > stop.offset);\n\tif (i < 0) i = stops.length;\n\tstops.splice(i, 0, stop);\n\treturn i;\n}\n\n/** A stop added at `offset` painting what the gradient paints there; returns the stops and its index. */\nexport function insertVectorGradientStop(g: VectorGradient, offset: number): { stops: VectorGradientStop[]; index: number } {\n\tconst at = clamp(offset, 0, 1);\n\tconst { color, opacity } = sampleVectorGradient(g, at);\n\tconst stops = sortedVectorGradientStops(g);\n\tconst index = placeStop(stops, opacity < 1 ? { offset: at, color, opacity } : { offset: at, color });\n\treturn { stops, index };\n}\n\n/** Stop `index` moved to `offset` (re-sorted); returns the stops and its new index. */\nexport function moveVectorGradientStop(stops: readonly VectorGradientStop[], index: number, offset: number): { stops: VectorGradientStop[]; index: number } {\n\tconst next = stops.map((s) => ({ ...s }));\n\tif (index < 0 || index >= next.length) return { stops: next, index };\n\tconst [s] = next.splice(index, 1);\n\treturn { stops: next, index: placeStop(next, { ...s, offset: clamp(offset, 0, 1) }) };\n}\n\n/** The stops without stop `index`, or null when that would leave fewer than two. */\nexport function removeVectorGradientStop(stops: readonly VectorGradientStop[], index: number): VectorGradientStop[] | null {\n\tif (stops.length <= VECTOR_GRADIENT_MIN_STOPS || index < 0 || index >= stops.length) return null;\n\treturn stops.filter((_, i) => i !== index);\n}\n\n/** Where (0–1 along the gradient) the midpoint after stop `index` sits, or null for the last stop. */\nexport function vectorGradientMidpointPosition(stops: readonly VectorGradientStop[], index: number): number | null {\n\tconst a = stops[index];\n\tconst b = stops[index + 1];\n\tif (!a || !b) return null;\n\treturn a.offset + (b.offset - a.offset) * (a.midpoint ?? 0.5);\n}\n\n/** The midpoint of stop `index` that puts it at position `pos` (clamped to 0.05–0.95), or null. */\nexport function vectorGradientMidpointFromPosition(stops: readonly VectorGradientStop[], index: number, pos: number): number | null {\n\tconst a = stops[index];\n\tconst b = stops[index + 1];\n\tif (!a || !b) return null;\n\tconst span = Math.max(b.offset - a.offset, 1e-6);\n\treturn clamp((pos - a.offset) / span, 0.05, 0.95);\n}\n\n/**\n * The part of the gradient from `from` to `to` (0–1, either order) as plain stops over 0–1\n * (vectorcraft `span`): the colours at both ends plus the expanded stops between them.\n */\nexport function spanVectorGradientStops(g: VectorGradient, from: number, to: number, expanded = expandVectorGradientStops(g)): VectorGradientStop[] {\n\tif (to < from) {\n\t\tconst s = spanVectorGradientStops(g, to, from, expanded);\n\t\treturn s.map((x) => ({ ...x, offset: 1 - x.offset })).reverse();\n\t}\n\tconst d = to - from;\n\tconst at = (offset: number, t: number) => stopOf(offset, samplePlainStops(expanded, t));\n\tconst out = [at(0, from)];\n\tif (d > 1e-9) for (const s of expanded) if (s.offset > from && s.offset < to) out.push({ ...s, offset: (s.offset - from) / d });\n\tout.push(at(1, to));\n\treturn out;\n}\n\n// ---------------------------------------------------------------------------\n// Geometry\n// ---------------------------------------------------------------------------\n\n/** A gradient's frame points, in its units (see `VectorGradient`). */\nexport interface VectorGradientPoints {\n\tstart: Vec2;\n\tend: Vec2;\n\twidth: Vec2;\n\tfocal: Vec2 | null;\n\tfocalRadius: number;\n\tunits: VectorGradientUnits;\n}\n\n/** Whether the gradient carries its own points (rather than the angle / centre shorthand). */\nexport const hasExplicitGradientGeometry = (g: VectorGradient) => finitePoint(g.start) && finitePoint(g.end);\n\n/** The shorthand of a gradient as points in its bounding box. */\nfunction shorthandPoints(g: VectorGradient): { start: Vec2; end: Vec2; width: Vec2 } {\n\tif (g.type === 'linear' || g.type === 'reflected') {\n\t\tconst c = angleToSvgLinearCoords(Number.isFinite(g.angle) ? (g.angle as number) : 180);\n\t\tconst start = g.type === 'linear' ? { x: c.x1, y: c.y1 } : { x: 0.5, y: 0.5 };\n\t\tconst end = { x: c.x2, y: c.y2 };\n\t\treturn { start, end, width: add(start, perp(sub(end, start))) };\n\t}\n\tconst start = { x: Number.isFinite(g.cx) ? (g.cx as number) : 0.5, y: Number.isFinite(g.cy) ? (g.cy as number) : 0.5 };\n\tconst r = Number.isFinite(g.r) ? (g.r as number) : 0.5;\n\tif (g.type === 'radial') return { start, end: { x: start.x + r, y: start.y }, width: { x: start.x, y: start.y + r } };\n\tconst a = ((Number.isFinite(g.angle) ? (g.angle as number) : 90) * Math.PI) / 180;\n\tconst dir = { x: Math.sin(a), y: -Math.cos(a) };\n\treturn { start, end: add(start, scale(dir, r)), width: add(start, scale(perp(dir), r)) };\n}\n\n/** The gradient's frame points in its units, the shorthand resolved (it is always in the box). */\nexport function vectorGradientPoints(g: VectorGradient): VectorGradientPoints {\n\tconst explicit = hasExplicitGradientGeometry(g);\n\tconst base = explicit ? null : shorthandPoints(g);\n\tconst start = explicit ? { x: g.start!.x, y: g.start!.y } : base!.start;\n\tconst end = explicit ? { x: g.end!.x, y: g.end!.y } : base!.end;\n\tconst width = explicit ? (finitePoint(g.width) ? { x: g.width.x, y: g.width.y } : add(start, perp(sub(end, start)))) : base!.width;\n\treturn {\n\t\tstart,\n\t\tend,\n\t\twidth,\n\t\tfocal: g.type === 'radial' && finitePoint(g.focal) ? { x: g.focal.x, y: g.focal.y } : null,\n\t\tfocalRadius: g.type === 'radial' ? clamp(Number.isFinite(g.focalRadius) ? (g.focalRadius as number) : 0, 0, 0.99) : 0,\n\t\tunits: explicit && g.units === 'userSpaceOnUse' ? 'userSpaceOnUse' : 'objectBoundingBox'\n\t};\n}\n\n/**\n * The unit box → `bounds` matrix of `objectBoundingBox` gradients. A side with no extent (a\n * horizontal or vertical line) takes the other side's, centred, so the gradient still paints\n * (SVG paints nothing there).\n */\nexport function vectorBoxMatrix(bounds: VectorBounds | null | undefined): VectorMatrix {\n\tif (!bounds) return IDENTITY;\n\tlet { x, y, width: w, height: h } = bounds;\n\tconst fallback = Math.max(w, h, 1e-9) > 1e-9 ? Math.max(w, h) : 1;\n\tif (!(w > 1e-9)) {\n\t\tx -= fallback / 2 - w / 2;\n\t\tw = fallback;\n\t}\n\tif (!(h > 1e-9)) {\n\t\ty -= fallback / 2 - h / 2;\n\t\th = fallback;\n\t}\n\treturn [w, 0, 0, h, x, y];\n}\n\n/** The matrix of frame points: unit frame (u along start → end, v along start → width) → their space. */\nconst framePointsMatrix = (p: Pick<VectorGradientPoints, 'start' | 'end' | 'width'>): VectorMatrix => [p.end.x - p.start.x, p.end.y - p.start.y, p.width.x - p.start.x, p.width.y - p.start.y, p.start.x, p.start.y];\n\n/** The gradient's units → node space (the box matrix for `objectBoundingBox`, else the identity). */\nexport function vectorGradientUnitsMatrix(g: VectorGradient, bounds: VectorBounds | null | undefined): VectorMatrix {\n\treturn vectorGradientPoints(g).units === 'objectBoundingBox' ? vectorBoxMatrix(bounds) : IDENTITY;\n}\n\n/** The gradient's unit frame → node space: u = 1 at the end, v = 1 at the width point. */\nexport function vectorGradientMatrix(g: VectorGradient, bounds: VectorBounds | null | undefined): VectorMatrix {\n\treturn mul(framePointsMatrix(vectorGradientPoints(g)), vectorGradientUnitsMatrix(g, bounds));\n}\n\n/** Most a focal point reaches towards the edge of the circle (vectorcraft `FOCAL_MAX`). */\nconst FOCAL_MAX = 0.99;\n\n/** The focal point in the unit frame, pulled inside the circle (or null). */\nfunction unitFocal(g: VectorGradient): { f: Vec2; fr: number } | null {\n\tconst p = vectorGradientPoints(g);\n\tif (!p.focal && !(p.focalRadius > 0)) return null;\n\tconst inv = invert(framePointsMatrix(p));\n\tif (!inv) return null;\n\tlet f = p.focal ? apply(inv, p.focal) : { x: 0, y: 0 };\n\tconst reach = FOCAL_MAX * (1 - p.focalRadius);\n\tconst r = Math.hypot(f.x, f.y);\n\tif (r > reach) f = scale(f, reach / r);\n\treturn { f, fr: p.focalRadius };\n}\n\n/**\n * t of a radial gradient at unit-frame point `q` with the focal circle centred on `f` with radius\n * `fr` and the end circle the unit circle (SVG's two-point conical gradient). With `fr = 0` this\n * is the focal ray: t is the distance from the focal point to `q` over the distance from it to\n * the circle along the same ray (effectcraft `GradientRamp::t`, vectorcraft `param_at`).\n */\nexport function vectorGradientFocalParam(q: Vec2, f: Vec2 = { x: 0, y: 0 }, fr = 0): number {\n\tconst d = sub(q, f);\n\tconst dr = 1 - fr;\n\tconst a = dot(f, f) - dr * dr;\n\tconst b = dot(d, f) - fr * dr;\n\tconst c = dot(d, d) - fr * fr;\n\tif (Math.abs(a) < 1e-12) return Math.abs(b) < 1e-12 ? 0 : -c / (2 * b);\n\treturn (-b - Math.sqrt(Math.max(0, b * b - a * c))) / a;\n}\n\n/**\n * The raw gradient parameter (before the spread) of a style at unit-frame point `q`: linear `u`,\n * reflected `|u|`, diamond `|u| + |v|`, conic the turn from the u axis towards the v axis (0–1),\n * radial the distance through the focal circle (photocraft `gradient_t`).\n */\nexport function vectorGradientParam(type: VectorGradientType, q: Vec2, focal?: { f: Vec2; fr: number } | null): number {\n\tswitch (type) {\n\t\tcase 'linear':\n\t\t\treturn q.x;\n\t\tcase 'reflected':\n\t\t\treturn Math.abs(q.x);\n\t\tcase 'diamond':\n\t\t\treturn Math.abs(q.x) + Math.abs(q.y);\n\t\tcase 'conic': {\n\t\t\tconst turn = Math.atan2(q.y, q.x) / (2 * Math.PI);\n\t\t\treturn turn - Math.floor(turn);\n\t\t}\n\t\tcase 'radial':\n\t\t\treturn focal ? vectorGradientFocalParam(q, focal.f, focal.fr) : Math.hypot(q.x, q.y);\n\t}\n}\n\n/** `t` folded into 0–1 by a spread mode. */\nexport function applyVectorGradientSpread(t: number, spread: VectorGradientSpread = 'pad'): number {\n\tif (!Number.isFinite(t)) return 0;\n\tif (spread === 'repeat') return t - Math.floor(t);\n\tif (spread === 'reflect') {\n\t\tconst m = ((t % 2) + 2) % 2;\n\t\treturn m <= 1 ? m : 2 - m;\n\t}\n\treturn clamp(t, 0, 1);\n}\n\n/** The gradient's t (spread applied) at node-space point `p` of a shape with box `bounds`. */\nexport function vectorGradientTAt(g: VectorGradient, bounds: VectorBounds | null | undefined, p: Vec2): number {\n\tconst inv = invert(vectorGradientMatrix(g, bounds));\n\tif (!inv) return 0;\n\tconst raw = vectorGradientParam(g.type, apply(inv, p), g.type === 'radial' ? unitFocal(g) : null);\n\treturn g.type === 'conic' ? raw : applyVectorGradientSpread(raw, g.spread ?? 'pad');\n}\n\n/** What the gradient paints at node-space point `p` (straight-alpha sRGB, 0–1). */\nexport function sampleVectorGradientAt(g: VectorGradient, bounds: VectorBounds | null | undefined, p: Vec2): VectorRgba {\n\tconst t = vectorGradientTAt(g, bounds, p);\n\tconst ramp = vectorGradientRamp(g);\n\treturn ramp ? ramp.sample(t) : samplePlainStops(sortedVectorGradientStops(g), t);\n}\n\n/** The main axis length over the secondary's: |width − start| / |end − start| (signed by side). */\nexport function vectorGradientAspect(g: VectorGradient): number {\n\tconst p = vectorGradientPoints(g);\n\tconst u = sub(p.end, p.start);\n\tconst l2 = dot(u, u);\n\treturn l2 > 1e-18 ? dot(sub(p.width, p.start), perp(u)) / l2 : 1;\n}\n\n/** The gradient with explicit points (in its units) replacing the shorthand. */\nexport function explicitVectorGradient(g: VectorGradient): VectorGradient {\n\tconst p = vectorGradientPoints(g);\n\tconst { angle: _a, cx: _cx, cy: _cy, r: _r, ...rest } = g;\n\treturn {\n\t\t...rest,\n\t\tstart: p.start,\n\t\tend: p.end,\n\t\twidth: p.width,\n\t\t...(p.focal ? { focal: p.focal } : {}),\n\t\tunits: p.units\n\t};\n}\n\n/**\n * The gradient in the node's own space (`userSpaceOnUse`), painting what it paints on a shape\n * with box `bounds` (vectorcraft `GradientPaint::pin`): its points mapped through the box.\n */\nexport function pinVectorGradient(g: VectorGradient, bounds: VectorBounds | null | undefined): VectorGradient {\n\tconst e = explicitVectorGradient(g);\n\tif (e.units === 'userSpaceOnUse') return e;\n\tconst m = vectorBoxMatrix(bounds);\n\treturn { ...e, start: apply(m, e.start!), end: apply(m, e.end!), width: apply(m, e.width!), ...(e.focal ? { focal: apply(m, e.focal) } : {}), units: 'userSpaceOnUse' };\n}\n\n/**\n * The gradient after the node's geometry is mapped by `m`: a `userSpaceOnUse` gradient's points\n * are mapped too (any affine map keeps every style's t, since t is measured in the frame the\n * three points span); a box gradient follows the box and is unchanged.\n */\nexport function transformVectorGradient(g: VectorGradient, m: VectorMatrix): VectorGradient {\n\tif (!hasExplicitGradientGeometry(g) || g.units !== 'userSpaceOnUse' || isIdentity(m)) return g;\n\tconst p = vectorGradientPoints(g);\n\treturn { ...g, start: apply(m, p.start), end: apply(m, p.end), width: apply(m, p.width), ...(p.focal ? { focal: apply(m, p.focal) } : {}) };\n}\n\n/**\n * A gradient after its node's geometry goes through a non-affine map `f` (Free Distort, an\n * envelope): handles in the node's own space (`userSpaceOnUse`) are mapped point by point, which\n * keeps the gradient's frame where the shape went; bounding-box gradients are left alone, as they\n * already follow the shape's new bounds.\n */\nexport function mapVectorGradient(g: VectorGradient, f: (p: Vec2) => Vec2): VectorGradient {\n\tif (!hasExplicitGradientGeometry(g) || g.units !== 'userSpaceOnUse') return g;\n\tconst p = vectorGradientPoints(g);\n\treturn { ...g, start: f(p.start), end: f(p.end), width: f(p.width), ...(p.focal ? { focal: f(p.focal) } : {}) };\n}\n\n/** A paint after its node's geometry goes through a non-affine map `f` (see `mapVectorGradient`). */\nexport function mapVectorPaint<T extends VectorPaint | undefined>(paint: T, f: (p: Vec2) => Vec2): T {\n\treturn (isVectorGradient(paint) ? mapVectorGradient(paint, f) : paint) as T;\n}\n\n/** A paint after its node's geometry is mapped by `m` (colours unchanged). */\nexport function transformVectorPaint<T extends VectorPaint | undefined>(paint: T, m: VectorMatrix): T {\n\treturn (isVectorGradient(paint) ? transformVectorGradient(paint, m) : paint) as T;\n}\n\n// ---------------------------------------------------------------------------\n// Handles (on-canvas editing)\n// ---------------------------------------------------------------------------\n\n/**\n * An on-canvas handle of a gradient: `start` (a radial, conic or diamond gradient's centre),\n * `end` (a linear or reflected gradient's end), `radius` (the end of the others), `aspect` (the\n * secondary axis' end) and `focal` (radial).\n */\nexport type VectorGradientHandle = 'start' | 'end' | 'radius' | 'aspect' | 'focal';\n\n/** Whether the style has a centre with a radius (rather than a start and an end). */\nexport const isCentredVectorGradient = (type: VectorGradientType) => type === 'radial' || type === 'conic' || type === 'diamond';\n\n/** The handles of a gradient in the space `toWorld` maps the node's space to (the document, the screen). */\nexport function vectorGradientHandles(\n\tg: VectorGradient,\n\tbounds: VectorBounds | null | undefined,\n\ttoWorld: VectorMatrix = IDENTITY\n): { start: Vec2; end: Vec2; aspect: Vec2 | null; focal: Vec2 | null } {\n\tconst p = vectorGradientPoints(g);\n\tconst m = mul(vectorGradientUnitsMatrix(g, bounds), toWorld);\n\tconst f = g.type === 'radial' ? unitFocal(g) : null;\n\tconst frame = mul(framePointsMatrix(p), m);\n\treturn {\n\t\tstart: apply(m, p.start),\n\t\tend: apply(m, p.end),\n\t\taspect: isCentredVectorGradient(g.type) ? apply(m, p.width) : null,\n\t\tfocal: g.type === 'radial' ? apply(frame, f?.f ?? { x: 0, y: 0 }) : null\n\t};\n}\n\n/** Keeps the width point (and focal point) where they were relative to the main axis when it moves. */\nfunction withMainAxis(p: VectorGradientPoints, start: Vec2, end: Vec2): Pick<VectorGradientPoints, 'start' | 'end' | 'width' | 'focal'> {\n\tconst before = invert(framePointsMatrix(p));\n\tconst u = sub(p.end, p.start);\n\tconst l2 = dot(u, u);\n\tconst w = sub(p.width, p.start);\n\tconst rel = l2 > 1e-18 ? { a: dot(w, u) / l2, b: dot(w, perp(u)) / l2 } : { a: 0, b: 1 };\n\tconst u2 = sub(end, start);\n\tconst width = add(start, add(scale(u2, rel.a), scale(perp(u2), rel.b)));\n\tconst next = { start, end, width };\n\tconst focal = p.focal && before ? apply(framePointsMatrix(next), apply(before, p.focal)) : p.focal;\n\treturn { ...next, focal };\n}\n\n/**\n * The gradient (pinned to the node's space) with a handle dragged to node-space point `to`.\n * `start` moves the whole gradient by `to − from`; `end` / `radius` move the end, the secondary\n * axis and focal point following; `aspect` sets the secondary axis' length square to the main\n * one; `focal` sets the focal point (pulled inside the circle; null centres it).\n */\nexport function moveVectorGradientHandle(\n\tg: VectorGradient,\n\tbounds: VectorBounds | null | undefined,\n\thandle: VectorGradientHandle,\n\tto: Vec2,\n\tfrom: Vec2 = to\n): VectorGradient {\n\tconst pinned = pinVectorGradient(g, bounds);\n\tconst p = vectorGradientPoints(pinned);\n\tconst set = (q: Partial<Pick<VectorGradient, 'start' | 'end' | 'width' | 'focal'>>) => {\n\t\tconst next = { ...pinned, ...q };\n\t\tif (next.focal === null || next.focal === undefined) delete next.focal;\n\t\treturn next;\n\t};\n\tswitch (handle) {\n\t\tcase 'start': {\n\t\t\tconst d = sub(to, from);\n\t\t\treturn set({ start: add(p.start, d), end: add(p.end, d), width: add(p.width, d), focal: p.focal ? add(p.focal, d) : null });\n\t\t}\n\t\tcase 'end':\n\t\tcase 'radius': {\n\t\t\tif (Math.hypot(to.x - p.start.x, to.y - p.start.y) < 1e-6) return pinned;\n\t\t\tconst n = withMainAxis(p, p.start, to);\n\t\t\treturn set({ end: n.end, width: n.width, focal: n.focal });\n\t\t}\n\t\tcase 'aspect': {\n\t\t\tconst u = sub(p.end, p.start);\n\t\t\tconst l2 = dot(u, u);\n\t\t\tif (l2 < 1e-18) return pinned;\n\t\t\tlet aspect = dot(sub(to, p.start), perp(u)) / l2;\n\t\t\tif (Math.abs(aspect) < 0.01) aspect = aspect < 0 ? -0.01 : 0.01;\n\t\t\tconst before = invert(framePointsMatrix(p));\n\t\t\tconst width = add(p.start, scale(perp(u), aspect));\n\t\t\tconst focal = p.focal && before ? apply(framePointsMatrix({ start: p.start, end: p.end, width }), apply(before, p.focal)) : null;\n\t\t\treturn set({ width, focal });\n\t\t}\n\t\tcase 'focal': {\n\t\t\tconst frame = framePointsMatrix(p);\n\t\t\tconst inv = invert(frame);\n\t\t\tif (!inv) return pinned;\n\t\t\tlet q = apply(inv, to);\n\t\t\tconst r = Math.hypot(q.x, q.y);\n\t\t\tif (r < 1e-6) return set({ focal: null });\n\t\t\tconst reach = FOCAL_MAX * (1 - p.focalRadius);\n\t\t\tif (r > reach) q = scale(q, reach / r);\n\t\t\treturn set({ focal: apply(frame, q) });\n\t\t}\n\t}\n}\n\n/** The gradient set to run from `start` to `end` (node space), its secondary axis square to it with its aspect kept. */\nexport function setVectorGradientVector(g: VectorGradient, bounds: VectorBounds | null | undefined, start: Vec2, end: Vec2): VectorGradient {\n\tconst pinned = pinVectorGradient(g, bounds);\n\tconst p = vectorGradientPoints(pinned);\n\tconst aspect = Math.abs(vectorGradientAspect(pinned)) > 1e-6 ? vectorGradientAspect(pinned) : 1;\n\tconst u = sub(end, start);\n\tconst width = add(start, scale(perp(u), aspect));\n\tconst before = invert(framePointsMatrix(p));\n\tconst focal = p.focal && before ? apply(framePointsMatrix({ start, end, width }), apply(before, p.focal)) : null;\n\tconst next: VectorGradient = { ...pinned, start, end, width };\n\tif (focal) next.focal = focal;\n\telse delete next.focal;\n\treturn next;\n}\n\n// ---------------------------------------------------------------------------\n// Spread as stop periods\n// ---------------------------------------------------------------------------\n\n/** Most periods a spread is expanded to (vectorcraft `MAX_PERIODS`). */\nexport const VECTOR_GRADIENT_MAX_PERIODS = 64;\n\n/** The stops of one period, from 0 to 1: the end colours held out to the ends (vectorcraft `whole_period`). */\nfunction wholePeriod(stops: readonly VectorGradientStop[]): VectorGradientStop[] {\n\tconst out = stops.map((s) => ({ ...s }));\n\tif (out.length && out[0].offset > 0) out.unshift({ ...out[0], offset: 0 });\n\tconst last = out[out.length - 1];\n\tif (last && last.offset < 1) out.push({ ...last, offset: 1 });\n\treturn out;\n}\n\n/**\n * Stops repeating the gradient's plain stops over periods `lo` … `hi` (integers, at most\n * `VECTOR_GRADIENT_MAX_PERIODS`), period `k` mirrored when `mirrored(k)`; offsets over 0–1 span\n * the whole range (vectorcraft `spread::expand`, which emulates `reflect` and `repeat` this way).\n */\nexport function periodicVectorGradientStops(stops: readonly VectorGradientStop[], lo: number, hi: number, mirrored: (k: number) => boolean): VectorGradientStop[] {\n\tconst period = wholePeriod(stops);\n\tconst back = reverseVectorGradient({ stops: period }).stops;\n\tconst n = Math.max(1, hi - lo);\n\tconst out: VectorGradientStop[] = [];\n\tfor (let j = 0; j < n; j++) {\n\t\tconst one = mirrored(lo + j) ? back : period;\n\t\tfor (const s of one) out.push({ ...s, offset: (j + s.offset) / n });\n\t}\n\treturn out;\n}\n\n/**\n * A linear or reflected gradient's spread as stop periods over `area` (node space), for\n * renderers (and combinations) without the spread mode: vectorcraft's SVG import emulates\n * `reflect` and `repeat` this way. Returns where the periods start and end and their stops, or\n * null when a linear gradient pads (nothing to repeat). Reflected gradients always get at least\n * the period either side of the start (the one before it mirrored). `from` / `to` are the\n * periods' ends along the frame's u axis (`matrix` maps the frame to node space).\n */\nexport function expandVectorGradientSpread(\n\tg: VectorGradient,\n\tbounds: VectorBounds | null | undefined,\n\tarea: VectorBounds\n): { start: Vec2; end: Vec2; from: number; to: number; matrix: VectorMatrix; stops: VectorGradientStop[]; capped: boolean } | null {\n\tconst m = vectorGradientMatrix(g, bounds);\n\tconst inv = invert(m);\n\tconst spread = g.spread ?? 'pad';\n\tconst reflected = g.type === 'reflected';\n\tif (!inv || (!reflected && spread === 'pad')) return null;\n\tconst odd = (k: number) => ((k % 2) + 2) % 2 === 1;\n\tconst stops = expandVectorGradientStops(g);\n\tconst along = (a: number, b: number, mirrored: (k: number) => boolean, capped = false) => ({\n\t\tstart: apply(m, { x: a, y: 0 }),\n\t\tend: apply(m, { x: b, y: 0 }),\n\t\tfrom: a,\n\t\tto: b,\n\t\tmatrix: m,\n\t\tstops: periodicVectorGradientStops(stops, a, b, mirrored),\n\t\tcapped\n\t});\n\tif (reflected && spread === 'pad') return along(-1, 1, (k) => k < 0);\n\tconst us = boxCorners(area).map((c) => apply(inv, c).x);\n\tlet lo = Math.floor(Math.min(...us));\n\tlet hi = Math.ceil(Math.max(...us));\n\tif (reflected) {\n\t\tlo = Math.min(lo, -1);\n\t\thi = Math.max(hi, 1);\n\t}\n\thi = Math.max(hi, lo + 1);\n\tif (!reflected && lo >= 0 && hi <= 1) return null;\n\tconst capped = hi - lo > VECTOR_GRADIENT_MAX_PERIODS;\n\tif (capped) {\n\t\tlo = Math.max(lo, -VECTOR_GRADIENT_MAX_PERIODS / 2);\n\t\thi = lo + VECTOR_GRADIENT_MAX_PERIODS;\n\t}\n\t// Period k covers u in [k, k + 1]. A reflected gradient runs |u|: before the start, periods run backwards.\n\tconst mirrored = reflected\n\t\t? (k: number) => {\n\t\t\t\tconst j = k >= 0 ? k : -k - 1;\n\t\t\t\tconst own = spread === 'reflect' && odd(j);\n\t\t\t\treturn k < 0 ? !own : own;\n\t\t\t}\n\t\t: (k: number) => spread === 'reflect' && odd(k);\n\treturn along(lo, hi, mirrored, capped);\n}\n\nconst boxCorners = (b: VectorBounds): Vec2[] => [\n\t{ x: b.x, y: b.y },\n\t{ x: b.x + b.width, y: b.y },\n\t{ x: b.x + b.width, y: b.y + b.height },\n\t{ x: b.x, y: b.y + b.height }\n];\n\n// ---------------------------------------------------------------------------\n// SVG paint servers\n// ---------------------------------------------------------------------------\n\n/**\n * A `<pattern>` paint server in user space: draw `gradients` (inside it or in `<defs>`) and then\n * each tile (`d` filled with `fill`) in order, all in the painted element's user space (the\n * `viewBox` in `attrs` matches the tile, so keep it). Conic and diamond gradients, and gradients along\n * or across a stroke, take this form.\n */\nexport interface VectorSvgPatternDef {\n\tid: string;\n\ttype: 'pattern';\n\t/** `x`, `y`, `width`, `height`, `patternUnits=\"userSpaceOnUse\"` and the matching `viewBox`. */\n\tattrs: Record<string, string | number>;\n\tgradients: SvgGradientDef[];\n\ttiles: { d: string; fill: string }[];\n}\n\n/** A paint server for `fill` / `stroke`: a gradient element or a pattern of gradient tiles. */\nexport type VectorPaintDef = SvgGradientDef | VectorSvgPatternDef;\n\nexport interface VectorGradientSvgOptions {\n\t/** The shape's box in its own space (for `objectBoundingBox` gradients). */\n\tbounds?: VectorBounds | null;\n\t/** The area the paint must cover (pattern tiles, spread periods); default `bounds` padded by 1. */\n\tarea?: VectorBounds | null;\n\t/** Wedges of a conic gradient (default 72: 5° each). */\n\twedges?: number;\n\tprecision?: number;\n}\n\nconst toSvgStops = (stops: readonly VectorGradientStop[]): SvgGradientStop[] =>\n\tstops.map((s) => ({ offset: `${fmt(s.offset * 100, 3)}%`, stopColor: s.color, ...(s.opacity !== undefined && s.opacity !== 1 ? { stopOpacity: Math.round(s.opacity * 1e4) / 1e4 } : {}) }));\n\nconst polygonD = (pts: readonly Vec2[], precision: number) => `M${pts.map((p) => `${fmt(p.x, precision)} ${fmt(p.y, precision)}`).join('L')}Z`;\n\nconst padBounds = (b: VectorBounds, pad: number): VectorBounds => ({ x: b.x - pad, y: b.y - pad, width: b.width + 2 * pad, height: b.height + 2 * pad });\n\n/** The area a gradient on a shape with box `bounds` paints (the box padded by 1). */\nexport const vectorGradientArea = (bounds: VectorBounds | null | undefined): VectorBounds => padBounds(bounds ?? { x: 0, y: 0, width: 1, height: 1 }, 1);\n\n/** The `gradientTransform` attribute of matrix `m` (none for the identity). */\nconst transformAttr = (m: VectorMatrix): Record<string, string> => (isIdentity(m) ? {} : { gradientTransform: fmtMatrix(m) });\n\n/** Smallest stretch of a matrix (the least singular value). */\nfunction minScale(m: VectorMatrix): number {\n\tconst [a, b, c, d] = m;\n\tconst p = a * a + b * b;\n\tconst q = c * c + d * d;\n\tconst r = a * c + b * d;\n\treturn Math.sqrt(Math.max(0, (p + q - Math.sqrt((p - q) ** 2 + 4 * r * r)) / 2));\n}\n\n/**\n * A user-space pattern tile over `area`. Without a `viewBox` SVG puts the content's origin at the\n * tile's corner; the matching `viewBox` keeps the content in the painted element's user space.\n */\nexport function patternAttrs(area: VectorBounds): Record<string, string> {\n\tconst [x, y, w, h] = [area.x, area.y, Math.max(area.width, 1e-3), Math.max(area.height, 1e-3)].map((n) => fmt(n, 3));\n\treturn { patternUnits: 'userSpaceOnUse', x, y, width: w, height: h, viewBox: `${x} ${y} ${w} ${h}` };\n}\n\n/** A pattern def over `area` with the given tiles. */\nfunction patternDef(id: string, area: VectorBounds, gradients: SvgGradientDef[], tiles: { d: string; fill: string }[]): VectorSvgPatternDef {\n\treturn {\n\t\tid,\n\t\ttype: 'pattern',\n\t\tattrs: patternAttrs(area),\n\t\tgradients,\n\t\ttiles\n\t};\n}\n\n/**\n * The SVG paint servers of a gradient on a shape: the first def's id is `id` (reference it as\n * `url(#id)`), any others are what it uses. All are in the user space of the element painted\n * (the node's own space).\n */\nexport function vectorGradientSvgDefs(g: VectorGradient, id: string, options: VectorGradientSvgOptions = {}): VectorPaintDef[] {\n\tconst precision = options.precision ?? 3;\n\tconst bounds = options.bounds ?? null;\n\tconst area = options.area ?? vectorGradientArea(bounds);\n\tconst spread = g.spread && VECTOR_GRADIENT_SPREADS.includes(g.spread) ? g.spread : 'pad';\n\tconst stops = expandVectorGradientStops(g);\n\tconst p = vectorGradientPoints(g);\n\tconst unitsM = vectorGradientUnitsMatrix(g, bounds);\n\tconst frameM = mul(framePointsMatrix(p), unitsM);\n\tconst spreadAttr = (s: VectorGradientSpread): Record<string, string> => (s === 'pad' ? {} : { spreadMethod: s });\n\tconst base = { gradientUnits: 'userSpaceOnUse' };\n\n\tswitch (g.type) {\n\t\tcase 'linear':\n\t\tcase 'reflected': {\n\t\t\tif (g.type === 'reflected' && spread !== 'reflect') {\n\t\t\t\t// Pad: mirrored stops over [2·start − end, end]; repeat: periods over the area, the ones before the start mirrored.\n\t\t\t\tconst ex = expandVectorGradientSpread(g, bounds, area);\n\t\t\t\tconst [a, b] = ex ? [ex.from, ex.to] : [-1, 1];\n\t\t\t\tconst st = ex?.stops ?? periodicVectorGradientStops(stops, -1, 1, (k) => k < 0);\n\t\t\t\treturn [{ id, type: 'linear', attrs: { ...base, x1: a, y1: 0, x2: b, y2: 0, gradientTransform: fmtMatrix(frameM) }, stops: toSvgStops(st) }];\n\t\t\t}\n\t\t\tconst u = sub(p.end, p.start);\n\t\t\tconst w = sub(p.width, p.start);\n\t\t\tconst square = Math.abs(dot(u, w)) <= 1e-9 * Math.max(dot(u, u), dot(w, w), 1e-18);\n\t\t\t// A skewed frame (a userSpaceOnUse gradient sheared with its shape) needs the frame as the transform.\n\t\t\tconst coords: Record<string, string | number> = square ? { x1: fmt(p.start.x, 6), y1: fmt(p.start.y, 6), x2: fmt(p.end.x, 6), y2: fmt(p.end.y, 6), ...transformAttr(unitsM) } : { x1: 0, y1: 0, x2: 1, y2: 0, gradientTransform: fmtMatrix(frameM) };\n\t\t\treturn [{ id, type: 'linear', attrs: { ...base, ...coords, ...spreadAttr(spread) }, stops: toSvgStops(stops) }];\n\t\t}\n\t\tcase 'radial': {\n\t\t\tconst f = unitFocal(g);\n\t\t\tconst attrs: Record<string, string | number> = { ...base, cx: 0, cy: 0, r: 1, gradientTransform: fmtMatrix(frameM), ...spreadAttr(spread) };\n\t\t\tif (f && (Math.abs(f.f.x) > 1e-9 || Math.abs(f.f.y) > 1e-9)) {\n\t\t\t\tattrs.fx = fmt(f.f.x, 6);\n\t\t\t\tattrs.fy = fmt(f.f.y, 6);\n\t\t\t}\n\t\t\tif (f && f.fr > 0) attrs.fr = fmt(f.fr, 6);\n\t\t\treturn [{ id, type: 'radial', attrs, stops: toSvgStops(stops) }];\n\t\t}\n\t\tcase 'diamond': {\n\t\t\tconst inv = invert(frameM);\n\t\t\tif (!inv) return [patternDef(id, area, [], [{ d: polygonD(boxCorners(area), precision), fill: stops[stops.length - 1]?.color ?? 'none' }])];\n\t\t\tconst reach = 2 * Math.max(...boxCorners(area).map((c) => {\n\t\t\t\tconst q = apply(inv, c);\n\t\t\t\treturn Math.abs(q.x) + Math.abs(q.y);\n\t\t\t})) + 1;\n\t\t\t// Each quadrant overlaps its neighbours by about 0.75 units, hiding anti-aliasing seams.\n\t\t\tconst delta = Math.min(0.05 * reach, 0.75 / Math.max(minScale(frameM), 1e-9));\n\t\t\tconst gradients: SvgGradientDef[] = [];\n\t\t\tconst tiles: { d: string; fill: string }[] = [];\n\t\t\t[[1, 1], [-1, 1], [-1, -1], [1, -1]].forEach(([sx, sy], k) => {\n\t\t\t\tconst gid = `${id}-q${k}`;\n\t\t\t\tgradients.push({ id: gid, type: 'linear', attrs: { ...base, x1: 0, y1: 0, x2: sx / 2, y2: sy / 2, gradientTransform: fmtMatrix(frameM), ...spreadAttr(spread) }, stops: toSvgStops(stops) });\n\t\t\t\tconst quad = [{ x: -delta * sx, y: -delta * sy }, { x: reach * sx, y: -delta * sy }, { x: -delta * sx, y: reach * sy }].map((q) => apply(frameM, q));\n\t\t\t\ttiles.push({ d: polygonD(quad, precision), fill: `url(#${gid})` });\n\t\t\t});\n\t\t\treturn [patternDef(id, area, gradients, tiles)];\n\t\t}\n\t\tcase 'conic':\n\t\t\treturn [conicPattern(id, frameM, stops, area, options.wedges ?? 72, precision)];\n\t}\n}\n\n/**\n * A conic gradient as thin wedges round the centre, each with a linear gradient across it\n * (along the tangent at its middle angle, exact on the unit circle of the frame: elsewhere a\n * point takes a colour from within its wedge). Stops inside a wedge keep sharp transitions.\n */\nfunction conicPattern(id: string, frameM: VectorMatrix, stops: readonly VectorGradientStop[], area: VectorBounds, wedges: number, precision: number): VectorSvgPatternDef {\n\tconst inv = invert(frameM);\n\tconst n = Math.max(8, Math.min(720, Math.round(wedges)));\n\tconst half = Math.PI / n;\n\tif (!inv || !stops.length) return patternDef(id, area, [], [{ d: polygonD(boxCorners(area), precision), fill: stops[0]?.color ?? 'none' }]);\n\tconst reach = (Math.max(...boxCorners(area).map((c) => Math.hypot(apply(inv, c).x, apply(inv, c).y))) + 1) / Math.cos(half);\n\tconst overlap = Math.min(half, 0.002);\n\tconst gradients: SvgGradientDef[] = [];\n\tconst tiles: { d: string; fill: string }[] = [];\n\tfor (let k = 0; k < n; k++) {\n\t\tconst a0 = (2 * Math.PI * k) / n;\n\t\tconst a1 = (2 * Math.PI * (k + 1)) / n;\n\t\tconst mid = (a0 + a1) / 2;\n\t\tconst tau = { x: -Math.sin(mid), y: Math.cos(mid) };\n\t\tconst s = Math.sin(half);\n\t\tconst at = (angle: number) => (Math.sin(angle - mid) / s + 1) / 2;\n\t\tconst t0 = k / n;\n\t\tconst t1 = (k + 1) / n;\n\t\tconst own: VectorGradientStop[] = [stopOf(0, samplePlainStops(stops, t0))];\n\t\tfor (const st of stops) if (st.offset > t0 && st.offset < t1) own.push({ ...st, offset: at(st.offset * 2 * Math.PI) });\n\t\town.push(stopOf(1, samplePlainStops(stops, t1)));\n\t\tconst gid = `${id}-w${k}`;\n\t\tgradients.push({\n\t\t\tid: gid,\n\t\t\ttype: 'linear',\n\t\t\tattrs: { gradientUnits: 'userSpaceOnUse', x1: fmt(-s * tau.x, 6), y1: fmt(-s * tau.y, 6), x2: fmt(s * tau.x, 6), y2: fmt(s * tau.y, 6), gradientTransform: fmtMatrix(frameM) },\n\t\t\tstops: toSvgStops(own)\n\t\t});\n\t\tconst from = a0 - (k === 0 ? 0 : overlap);\n\t\tconst pts = [{ x: 0, y: 0 }, { x: reach * Math.cos(from), y: reach * Math.sin(from) }, { x: reach * Math.cos(a1), y: reach * Math.sin(a1) }].map((q) => apply(frameM, q));\n\t\ttiles.push({ d: polygonD(pts, precision), fill: `url(#${gid})` });\n\t}\n\treturn patternDef(id, area, gradients, tiles);\n}\n\n// ---------------------------------------------------------------------------\n// Evaluating paint servers (tests, previews)\n// ---------------------------------------------------------------------------\n\nconst num = (v: string | number | undefined, fallback = 0) => {\n\tif (v === undefined) return fallback;\n\tconst n = typeof v === 'number' ? v : parseFloat(v);\n\treturn Number.isFinite(n) ? n : fallback;\n};\n\nconst parseMatrixAttr = (v: string | number | undefined): VectorMatrix => {\n\tconst m = typeof v === 'string' ? /^matrix\\(([^)]*)\\)$/.exec(v.trim()) : null;\n\tif (!m) return IDENTITY;\n\tconst n = m[1].split(/[\\s,]+/).map(Number);\n\treturn n.length === 6 && n.every(Number.isFinite) ? (n as unknown as VectorMatrix) : IDENTITY;\n};\n\nconst plainOf = (stops: readonly SvgGradientStop[]): VectorGradientStop[] =>\n\tstops.map((s) => ({ offset: parseFloat(s.offset) / (s.offset.endsWith('%') ? 100 : 1), color: s.stopColor, ...(s.stopOpacity !== undefined ? { opacity: s.stopOpacity } : {}) }));\n\n/** Point `p` inside a polygon tile (`M x y L … Z`), even-odd. */\nfunction inTile(d: string, p: Vec2): boolean {\n\tconst n = d.match(/-?[\\d.]+(?:e-?\\d+)?/gi)?.map(Number) ?? [];\n\tlet inside = false;\n\tfor (let i = 0, j = n.length - 2; i + 1 < n.length; j = i, i += 2) {\n\t\tconst [xi, yi, xj, yj] = [n[i], n[i + 1], n[j], n[j + 1]];\n\t\tif (yi > p.y !== yj > p.y && p.x < ((xj - xi) * (p.y - yi)) / (yj - yi) + xi) inside = !inside;\n\t}\n\treturn inside;\n}\n\n/**\n * What a `userSpaceOnUse` paint server from `vectorGradientSvgDefs` paints at point `p` (straight\n * alpha, 0–1) the way an SVG renderer would: a gradient's stops interpolated in sRGB, a pattern's\n * topmost tile containing `p`. Null for a point no tile covers.\n */\nexport function sampleVectorPaintDefAt(defs: readonly VectorPaintDef[], id: string, p: Vec2): VectorRgba | null {\n\tconst all = new Map<string, VectorPaintDef>();\n\tfor (const d of defs) {\n\t\tall.set(d.id, d);\n\t\tif (d.type === 'pattern') for (const gd of d.gradients) all.set(gd.id, gd);\n\t}\n\tconst paint = (ref: string, q: Vec2): VectorRgba | null => {\n\t\tconst url = /^url\\(#(.+)\\)$/.exec(ref);\n\t\tif (!url) return parseVectorColor(ref);\n\t\tconst def = all.get(url[1]);\n\t\tif (!def) return null;\n\t\tif (def.type === 'pattern') {\n\t\t\tfor (let i = def.tiles.length - 1; i >= 0; i--) if (inTile(def.tiles[i].d, q)) return paint(def.tiles[i].fill, q);\n\t\t\treturn null;\n\t\t}\n\t\tconst inv = invert(parseMatrixAttr(def.attrs.gradientTransform)) ?? IDENTITY;\n\t\tconst local = apply(inv, q);\n\t\tconst spread = (def.attrs.spreadMethod as VectorGradientSpread | undefined) ?? 'pad';\n\t\tlet t: number;\n\t\tif (def.type === 'radial') {\n\t\t\tconst r = num(def.attrs.r, 0.5);\n\t\t\tconst c = { x: num(def.attrs.cx), y: num(def.attrs.cy) };\n\t\t\tconst f = { x: num(def.attrs.fx, c.x), y: num(def.attrs.fy, c.y) };\n\t\t\tconst u = { x: (local.x - c.x) / r, y: (local.y - c.y) / r };\n\t\t\tt = vectorGradientFocalParam(u, { x: (f.x - c.x) / r, y: (f.y - c.y) / r }, num(def.attrs.fr) / r);\n\t\t} else {\n\t\t\tconst a = { x: num(def.attrs.x1), y: num(def.attrs.y1) };\n\t\t\tconst b = { x: num(def.attrs.x2, 1), y: num(def.attrs.y2) };\n\t\t\tconst v = sub(b, a);\n\t\t\tconst l2 = dot(v, v);\n\t\t\tt = l2 > 1e-18 ? dot(sub(local, a), v) / l2 : 0;\n\t\t}\n\t\treturn samplePlainStops(plainOf(def.stops), applyVectorGradientSpread(t, spread));\n\t};\n\treturn paint(`url(#${id})`, p);\n}\n\n// ---------------------------------------------------------------------------\n// Sanitizing (agents, import)\n// ---------------------------------------------------------------------------\n\nconst readPoint = (v: unknown): Vec2 | undefined => (finitePoint(v) ? { x: v.x, y: v.y } : undefined);\n\n/**\n * A gradient from untrusted input (agent commands, SVG data attributes), or null when it is not\n * one: unknown fields dropped, numbers clamped, at least one stop.\n */\nexport function sanitizeVectorGradient(input: unknown): VectorGradient | null {\n\tif (!input || typeof input !== 'object') return null;\n\tconst r = input as Record<string, unknown>;\n\tif (!VECTOR_GRADIENT_TYPES.includes(r.type as VectorGradientType) || !Array.isArray(r.stops)) return null;\n\tconst stops: VectorGradientStop[] = [];\n\tfor (const s of r.stops as unknown[]) {\n\t\tif (!s || typeof s !== 'object') continue;\n\t\tconst x = s as Record<string, unknown>;\n\t\tif (typeof x.color !== 'string' || typeof x.offset !== 'number' || !Number.isFinite(x.offset)) continue;\n\t\tconst stop: VectorGradientStop = { offset: clamp(x.offset, 0, 1), color: x.color.slice(0, 100) };\n\t\tif (typeof x.opacity === 'number' && Number.isFinite(x.opacity) && x.opacity !== 1) stop.opacity = clamp(x.opacity, 0, 1);\n\t\tif (typeof x.midpoint === 'number' && Number.isFinite(x.midpoint) && Math.abs(x.midpoint - 0.5) > 1e-6) stop.midpoint = clamp(x.midpoint, 0.05, 0.95);\n\t\tstops.push(stop);\n\t}\n\tif (!stops.length) return null;\n\tconst g: VectorGradient = { type: r.type as VectorGradientType, stops };\n\tfor (const k of ['angle', 'cx', 'cy', 'r'] as const) if (typeof r[k] === 'number' && Number.isFinite(r[k])) g[k] = r[k] as number;\n\tconst start = readPoint(r.start);\n\tconst end = readPoint(r.end);\n\tif (start && end) {\n\t\tg.start = start;\n\t\tg.end = end;\n\t\tconst width = readPoint(r.width);\n\t\tif (width) g.width = width;\n\t\tif (r.units === 'userSpaceOnUse' || r.units === 'objectBoundingBox') g.units = r.units;\n\t}\n\tconst focal = readPoint(r.focal);\n\tif (focal && g.type === 'radial') g.focal = focal;\n\tif (typeof r.focalRadius === 'number' && r.focalRadius > 0 && g.type === 'radial') g.focalRadius = clamp(r.focalRadius, 0, 0.99);\n\tif (VECTOR_GRADIENT_SPREADS.includes(r.spread as VectorGradientSpread) && r.spread !== 'pad') g.spread = r.spread as VectorGradientSpread;\n\tif (VECTOR_GRADIENT_INTERPOLATIONS.includes(r.interpolation as VectorGradientInterpolation) && r.interpolation !== 'srgb') g.interpolation = r.interpolation as VectorGradientInterpolation;\n\tif (typeof r.smoothness === 'number' && r.smoothness > 0) g.smoothness = clamp(r.smoothness, 0, 1);\n\tif (VECTOR_STROKE_GRADIENT_MODES.includes(r.strokeMode as never) && r.strokeMode !== 'within') g.strokeMode = r.strokeMode as VectorGradient['strokeMode'];\n\treturn g;\n}\n\n/**\n * A gradient changed to style `type`, keeping its stops, colour settings and placement: explicit\n * points stay where they are (a linear end becomes a radius), shorthand is redone for the style.\n */\nexport function convertVectorGradient(g: VectorGradient, type: VectorGradientType): VectorGradient {\n\tif (g.type === type) return g;\n\tconst next: VectorGradient = { ...g, type };\n\tif (type !== 'radial') {\n\t\tdelete next.focal;\n\t\tdelete next.focalRadius;\n\t}\n\tif (!hasExplicitGradientGeometry(g)) {\n\t\t// Shorthand fields mean different things per style: drop the ones the new style reads differently.\n\t\tif (isCentredVectorGradient(type) !== isCentredVectorGradient(g.type)) {\n\t\t\tdelete next.angle;\n\t\t\tdelete next.cx;\n\t\t\tdelete next.cy;\n\t\t\tdelete next.r;\n\t\t}\n\t}\n\treturn next;\n}\n\n/** A default gradient for a paint that was a colour (or nothing): the colour fading to white. */\nexport function defaultVectorGradient(type: VectorGradientType = 'linear', from?: VectorPaint): VectorGradient {\n\tif (isVectorGradient(from)) return convertVectorGradient(from, type);\n\tconst colour = typeof from === 'string' && parseVectorColor(from) ? from : '#000000';\n\treturn { type, stops: [{ offset: 0, color: colour }, { offset: 1, color: '#ffffff' }] };\n}\n\n/**\n * Changes to a gradient (`vector.setGradient`, the gradient editor): any gradient field, plus\n * `aspect` (the secondary axis' length over the main one, square to it) and `reverse`. `focal` or\n * `width` set to null removes them.\n */\nexport interface VectorGradientPatch extends Partial<Omit<VectorGradient, 'focal' | 'width'>> {\n\tfocal?: Vec2 | null;\n\twidth?: Vec2 | null;\n\taspect?: number;\n\treverse?: boolean;\n}\n\n/** `g` with `patch` applied (a style change converts it first), or null when the result is not a gradient. */\nexport function applyVectorGradientPatch(g: VectorGradient, patch: VectorGradientPatch): VectorGradient | null {\n\tconst { aspect, reverse, type, ...fields } = patch;\n\tlet next: VectorGradient = type && type !== g.type ? convertVectorGradient(g, type) : { ...g };\n\tconst record = next as unknown as Record<string, unknown>;\n\tfor (const [k, v] of Object.entries(fields)) {\n\t\tif (v === undefined) continue;\n\t\tif (v === null) delete record[k];\n\t\telse record[k] = v;\n\t}\n\t// Explicit points replace the shorthand (and the other way round).\n\tif ((fields.start || fields.end) && !hasExplicitGradientGeometry(next)) {\n\t\tconst p = vectorGradientPoints({ ...g, start: undefined, end: undefined });\n\t\tnext.start = next.start ?? p.start;\n\t\tnext.end = next.end ?? p.end;\n\t}\n\tif (aspect !== undefined && Number.isFinite(aspect)) {\n\t\tconst e = explicitVectorGradient(next);\n\t\tconst u = sub(e.end!, e.start!);\n\t\tconst a = Math.abs(aspect) < 0.01 ? (aspect < 0 ? -0.01 : 0.01) : aspect;\n\t\tnext = { ...e, width: add(e.start!, scale(perp(u), a)) };\n\t}\n\tif (reverse) next = reverseVectorGradient(next);\n\tconst clean = sanitizeVectorGradient(next);\n\tif (!clean) return null;\n\tclean.stops = sortedVectorGradientStops(clean);\n\treturn clean;\n}\n","/**\n * Affine matrices in SVG order (`[a, b, c, d, e, f]`), shared by the vector and image editors.\n * Angles are degrees, clockwise on screen (y points down).\n */\nimport type { AffineMatrix, Vec2 } from './types';\n\nexport type { AffineMatrix };\n\nexport const IDENTITY_MATRIX: AffineMatrix = [1, 0, 0, 1, 0, 0];\n\n/** `a` then `b` (apply `a` first). */\nexport function multiplyMatrices(a: AffineMatrix, b: AffineMatrix): AffineMatrix {\n const [a0, a1, a2, a3, a4, a5] = a;\n const [b0, b1, b2, b3, b4, b5] = b;\n return [b0 * a0 + b2 * a1, b1 * a0 + b3 * a1, b0 * a2 + b2 * a3, b1 * a2 + b3 * a3, b0 * a4 + b2 * a5 + b4, b1 * a4 + b3 * a5 + b5];\n}\n\nexport const translateMatrix = (dx: number, dy: number): AffineMatrix => [1, 0, 0, 1, dx, dy];\n\nexport function scaleMatrix(sx: number, sy: number, origin: Vec2 = { x: 0, y: 0 }): AffineMatrix {\n return [sx, 0, 0, sy, origin.x - sx * origin.x, origin.y - sy * origin.y];\n}\n\n/** Rotation by `degrees` clockwise (y points down) around `origin`. */\nexport function rotateMatrix(degrees: number, origin: Vec2 = { x: 0, y: 0 }): AffineMatrix {\n const r = (degrees * Math.PI) / 180;\n const cos = Math.cos(r);\n const sin = Math.sin(r);\n return [cos, sin, -sin, cos, origin.x - cos * origin.x + sin * origin.y, origin.y - sin * origin.x - cos * origin.y];\n}\n\n/** `m` applied about `origin` instead of the coordinate origin. */\nexport function matrixAbout(m: AffineMatrix, origin: Vec2): AffineMatrix {\n return multiplyMatrices(multiplyMatrices(translateMatrix(-origin.x, -origin.y), m), translateMatrix(origin.x, origin.y));\n}\n\n/**\n * A skew by `ax` degrees horizontally (vertical lines lean right for positive angles:\n * x' = x + tan(ax)·y) and `ay` degrees vertically (y' = y + tan(ay)·x), about `origin`.\n */\nexport function skewMatrix(ax: number, ay: number, origin: Vec2 = { x: 0, y: 0 }): AffineMatrix {\n const tx = Math.tan((ax * Math.PI) / 180);\n const ty = Math.tan((ay * Math.PI) / 180);\n return matrixAbout([1, ty, tx, 1, 0, 0], origin);\n}\n\nexport function applyMatrix(m: AffineMatrix, p: Vec2): Vec2 {\n return { x: m[0] * p.x + m[2] * p.y + m[4], y: m[1] * p.x + m[3] * p.y + m[5] };\n}\n\nexport function isIdentityMatrix(m: AffineMatrix, eps = 1e-12): boolean {\n return Math.abs(m[0] - 1) < eps && Math.abs(m[1]) < eps && Math.abs(m[2]) < eps && Math.abs(m[3] - 1) < eps && Math.abs(m[4]) < eps && Math.abs(m[5]) < eps;\n}\n\n/** The inverse matrix (the identity for a singular one). */\nexport function invertMatrix(m: AffineMatrix): AffineMatrix {\n const [a, b, c, d, e, f] = m;\n const det = a * d - b * c;\n if (!det || !Number.isFinite(det)) return IDENTITY_MATRIX;\n return [d / det, -b / det, -c / det, a / det, (c * f - d * e) / det, (b * e - a * f) / det];\n}\n\n/** Applies only the linear part (for directions and offsets). */\nexport function applyMatrixLinear(m: AffineMatrix, v: Vec2): Vec2 {\n return { x: m[0] * v.x + m[2] * v.y, y: m[1] * v.x + m[3] * v.y };\n}\n\n/**\n * The rotation of a matrix in degrees, clockwise (y down), in (−180, 180]. For a mirrored\n * matrix it is the rotation left after undoing a horizontal flip, so a flipped rotated shape\n * keeps its angle.\n */\nexport function matrixRotation(m: AffineMatrix): number {\n const [a, b, c, d] = m;\n const mirrored = a * d - b * c < 0;\n const deg = ((mirrored ? Math.atan2(-b - c, d - a) : Math.atan2(b - c, a + d)) * 180) / Math.PI;\n return Math.abs(deg) < 1e-9 ? 0 : deg;\n}\n\n/**\n * Splits `m` into `residual` then `rigid` (`m = residual × rigid` in apply order): `rigid` is\n * the nearest rotation plus the translation, `residual` the linear rest (scale, skew,\n * reflection). An unrotated `m` gives an identity `rigid` and everything in `residual`.\n */\nexport function decomposeRigid(m: AffineMatrix): { rigid: AffineMatrix; residual: AffineMatrix } {\n const [a, b, c, d, e, f] = m;\n const deg = matrixRotation(m);\n if (deg === 0) return { rigid: IDENTITY_MATRIX, residual: m };\n const r = (deg * Math.PI) / 180;\n const cos = Math.cos(r);\n const sin = Math.sin(r);\n return {\n rigid: [cos, sin, -sin, cos, e, f],\n residual: [cos * a + sin * b, -sin * a + cos * b, cos * c + sin * d, -sin * c + cos * d, 0, 0],\n };\n}\n","/**\n * Live corners: a radius stored on an anchor, drawn as a round, inverted or chamfered cut when\n * the path is turned into curves. The stored anchors never change; `expandVectorCorners` is the\n * one place the cut geometry is made, and `subpathsToBezier` calls it, so rendering,\n * hit-testing, bounds, booleans, stroke outlines and SVG export all see the same shape.\n *\n * Ported from ArtCraft (MIT OR Apache-2.0, see THIRD_PARTY_NOTICES.md):\n * - figcraft `crates/doc/src/vector.rs` — `VectorNetwork::rounded` / `corner` and `trim`: each\n * side is trimmed by arc length (the radius clamped so a cut takes at most half of each\n * side) and the round cut is a cubic with handles `4/3 · tan(φ/4) · ρ` along the sides'\n * directions at the cut, φ the turn between them and ρ the radius of the circle through\n * both ends. That is exact at any angle and works where a curve meets a corner.\n * - vectorcraft `crates/geom/src/corners.rs` — `path_corners`, `Corner` (setback, max radius,\n * bisector and radius change for the drag widget) and `cut_corners` (inverted round and\n * chamfer kinds, trimming curved sides between cuts, a closed subpath whose first corner is\n * cut starting where that cut ends).\n */\nimport type { Point } from '../canvas/types.js';\nimport { segmentDerivative, segmentLength, segmentParamAtLength, segmentPoint, subSegment } from '../canvas/pathops/bezier.js';\nimport type { VectorAnchor, VectorCornerKind, VectorSubpath, Vec2 } from './types.js';\n\nconst EPS = 1e-9;\n/** Sides closer than this to straight on (or folded back), as the sine of their angle, make no corner. */\nconst MIN_SINE = 1e-6;\n\nconst sub = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x - b.x, y: a.y - b.y });\nconst add = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x + b.x, y: a.y + b.y });\nconst mul = (a: Vec2, k: number): Vec2 => ({ x: a.x * k, y: a.y * k });\nconst dot = (a: Vec2, b: Vec2) => a.x * b.x + a.y * b.y;\nconst cross = (a: Vec2, b: Vec2) => a.x * b.y - a.y * b.x;\nconst len = (a: Vec2) => Math.hypot(a.x, a.y);\nconst pt = (p: Vec2): Point => [p.x, p.y];\nconst vec = (p: Point): Vec2 => ({ x: p[0], y: p[1] });\nconst onAnchor = (a: VectorAnchor, h: Vec2 | null | undefined) => !h || (Math.abs(h.x - a.x) < EPS && Math.abs(h.y - a.y) < EPS);\n\n/** A side of a corner: the segment from the corner's anchor to a neighbour, as a cubic leaving the corner. */\nclass Side {\n\treadonly curve: Point[];\n\treadonly straight: boolean;\n\treadonly length: number;\n\tconstructor(a: VectorAnchor, h1: Vec2 | null | undefined, h2: Vec2 | null | undefined, b: VectorAnchor) {\n\t\tthis.straight = onAnchor(a, h1) && onAnchor(b, h2);\n\t\tthis.curve = this.straight ? [pt(a), pt(b)] : [pt(a), pt(h1 ?? a), pt(h2 ?? b), pt(b)];\n\t\tthis.length = this.straight ? Math.hypot(b.x - a.x, b.y - a.y) : segmentLength(this.curve);\n\t}\n\n\t/** Unit direction the side leaves the corner in (towards its first control point off the corner). */\n\tdirection(): Vec2 | null {\n\t\tconst p0 = vec(this.curve[0]);\n\t\tfor (const q of this.curve.slice(1)) {\n\t\t\tconst d = sub(vec(q), p0);\n\t\t\tconst l = len(d);\n\t\t\tif (l > EPS) return mul(d, 1 / l);\n\t\t}\n\t\treturn null;\n\t}\n\n\t/** The point `s` along the side from the corner: its parameter, position and the direction the side runs on in there. */\n\tat(s: number, u: Vec2): { t: number; p: Vec2; dir: Vec2 } {\n\t\tif (this.straight) {\n\t\t\tconst t = this.length > EPS ? Math.min(1, Math.max(0, s / this.length)) : 0;\n\t\t\treturn { t, p: add(vec(this.curve[0]), mul(u, s)), dir: u };\n\t\t}\n\t\tconst t = segmentParamAtLength(this.curve, s, this.length);\n\t\tconst d = vec(segmentDerivative(this.curve, t));\n\t\tconst l = len(d);\n\t\treturn { t, p: vec(segmentPoint(this.curve, t)), dir: l > EPS ? mul(d, 1 / l) : u };\n\t}\n}\n\n/**\n * A corner a live radius can cut: an anchor that is not smooth, where two sides (straight or\n * curved) meet at an angle. Positions are in the path node's own space.\n */\nexport interface VectorCornerInfo {\n\tsubpath: number;\n\tindex: number;\n\t/** Where the sides meet. */\n\tat: Vec2;\n\t/** Unit directions the sides leave the corner in: towards the previous anchor, then the next one. */\n\tu: Vec2;\n\tv: Vec2;\n\t/** The sides' lengths (along curves), in the same order. */\n\tlu: number;\n\tlv: number;\n\t/** Cosine and sine of the angle between the sides. */\n\tcos: number;\n\tsin: number;\n\t/** The angle between the sides in degrees (90 at a rectangle's corners). */\n\tangle: number;\n\t/** The largest radius that fits: its cut then reaches halfway along the shorter side. */\n\tmaxRadius: number;\n}\n\ninterface CornerData extends VectorCornerInfo {\n\tsideU: Side;\n\tsideV: Side;\n}\n\nfunction cornerOf(sp: VectorSubpath, s: number, i: number): CornerData | null {\n\tconst n = sp.anchors.length;\n\tif (n < 2 || (!sp.closed && (i === 0 || i === n - 1))) return null;\n\tif (n === 2 && sp.closed) return null;\n\tconst a = sp.anchors[i];\n\tif (a.type === 'smooth' || a.type === 'symmetric') return null;\n\tconst prev = sp.anchors[(i - 1 + n) % n];\n\tconst next = sp.anchors[(i + 1) % n];\n\tconst sideU = new Side(a, a.in, prev.out, prev);\n\tconst sideV = new Side(a, a.out, next.in, next);\n\tconst u = sideU.direction();\n\tconst v = sideV.direction();\n\tif (!u || !v) return null;\n\tconst lu = sideU.length;\n\tconst lv = sideV.length;\n\tif (!(lu > EPS && lv > EPS) || !Number.isFinite(lu) || !Number.isFinite(lv)) return null;\n\tconst cos = Math.max(-1, Math.min(1, dot(u, v)));\n\tconst sin = Math.abs(cross(u, v));\n\tif (sin <= MIN_SINE) return null;\n\treturn { subpath: s, index: i, at: { x: a.x, y: a.y }, u, v, lu, lv, cos, sin, angle: (Math.atan2(sin, cos) * 180) / Math.PI, maxRadius: ((Math.min(lu, lv) / 2) * sin) / (1 + cos), sideU, sideV };\n}\n\nconst strip = ({ sideU: _u, sideV: _v, ...info }: CornerData): VectorCornerInfo => info;\n\n/** The corner at anchor `index` of a subpath, or null when the anchor makes none (an open end, smooth, or straight on). */\nexport function vectorCornerAt(sp: VectorSubpath, index: number, subpath = 0): VectorCornerInfo | null {\n\tconst c = cornerOf(sp, subpath, index);\n\treturn c ? strip(c) : null;\n}\n\n/** Every corner of the subpaths that a live radius can cut, in anchor order. */\nexport function vectorCorners(subpaths: readonly VectorSubpath[]): VectorCornerInfo[] {\n\tconst out: VectorCornerInfo[] = [];\n\tsubpaths.forEach((sp, s) => {\n\t\tfor (let i = 0; i < sp.anchors.length; i++) {\n\t\t\tconst c = cornerOf(sp, s, i);\n\t\t\tif (c) out.push(strip(c));\n\t\t}\n\t});\n\treturn out;\n}\n\n/** How far from the corner a round cut of radius `r` meets each side: r / tan(angle / 2). */\nexport const cornerSetback = (c: Pick<VectorCornerInfo, 'cos' | 'sin'>, r: number) => (r * (1 + c.cos)) / c.sin;\n\n/** `radius` clamped to what the corner can draw (0 for negative or non-finite radii). */\nexport const fitCornerRadius = (c: Pick<VectorCornerInfo, 'maxRadius'>, radius: number) => (Number.isFinite(radius) ? Math.min(Math.max(0, radius), c.maxRadius) : 0);\n\n/** The point `k` along the corner's bisector, measured in (u + v): a round cut of radius r is centred at k = r / sin. */\nexport const cornerBisectorPoint = (c: VectorCornerInfo, k: number): Vec2 => add(c.at, mul(add(c.u, c.v), k));\n\n/** How much the radius grows when the round cut's centre moves by `d` (its part along the bisector, in radius units). */\nexport const cornerRadiusChange = (c: VectorCornerInfo, d: Vec2) => (dot(d, add(c.u, c.v)) * c.sin) / (2 + 2 * c.cos);\n\n/** Handle length per unit radius of a cubic arc spanning the angle whose cosine is `cos`: 4/3 · tan(angle / 4). */\nfunction arcHandle(cos: number): number {\n\tconst c = Math.max(-1, Math.min(1, cos));\n\tconst sinHalf = Math.sqrt(Math.max(0, (1 - c) / 2));\n\tconst cosHalf = Math.sqrt(Math.max(0, (1 + c) / 2));\n\treturn ((4 / 3) * sinHalf) / (1 + cosHalf);\n}\n\n/** The unit direction square to unit `a`, on `b`'s side. */\nfunction squareTo(a: Vec2, b: Vec2): Vec2 {\n\tconst w = sub(b, mul(a, dot(a, b)));\n\tconst l = len(w);\n\treturn l > EPS ? mul(w, 1 / l) : { x: 0, y: 0 };\n}\n\ninterface Cut {\n\t/** Parameters along each side (from the corner) where the cut meets it. */\n\ttu: number;\n\ttv: number;\n\tstart: Vec2;\n\t/** Handles of the cut's own segment (absent for a chamfer). */\n\tout: Vec2 | null;\n\tin: Vec2 | null;\n\tend: Vec2;\n}\n\nfunction cutCorner(c: CornerData, radius: number, kind: VectorCornerKind): Cut | null {\n\t// figcraft `corner`: trim each side by arc length, at most half of it.\n\tconst s = Math.min(cornerSetback(c, radius), Math.min(c.lu, c.lv) / 2);\n\tif (!(s > EPS)) return null;\n\tconst a = c.sideU.at(s, c.u);\n\tconst b = c.sideV.at(s, c.v);\n\tif (kind === 'chamfer') return { tu: a.t, tv: b.t, start: a.p, out: null, in: null, end: b.p };\n\tif (kind === 'inverted') {\n\t\t// vectorcraft `cut`: an arc centred on the corner through both ends, spanning the corner's angle.\n\t\tconst h = s * arcHandle(dot(a.dir, b.dir));\n\t\treturn { tu: a.t, tv: b.t, start: a.p, out: add(a.p, mul(squareTo(a.dir, b.dir), h)), in: add(b.p, mul(squareTo(b.dir, a.dir), h)), end: b.p };\n\t}\n\t// Round: d1, d2 point back towards the corner at the cut's ends; φ is the turn between them\n\t// and ρ the radius of the circle through both ends.\n\tconst d1 = mul(a.dir, -1);\n\tconst d2 = mul(b.dir, -1);\n\tconst turn = Math.acos(Math.max(-1, Math.min(1, -dot(d1, d2))));\n\tconst chord = len(sub(b.p, a.p));\n\tconst k = turn < 1e-9 ? chord / 3 : (((4 / 3) * Math.tan(turn / 4) * chord) / (2 * Math.sin(turn / 2)));\n\tif (!Number.isFinite(k)) return null;\n\treturn { tu: a.t, tv: b.t, start: a.p, out: add(a.p, mul(d1, k)), in: add(b.p, mul(d2, k)), end: b.p };\n}\n\nconst radiusOf = (a: VectorAnchor) => {\n\tconst r = a.corner?.radius;\n\treturn typeof r === 'number' && r > 0 && Number.isFinite(r) ? r : 0;\n};\n\n/** True when any anchor of the subpaths has a live corner radius. */\nexport function hasVectorCorners(subpaths: readonly VectorSubpath[]): boolean {\n\treturn subpaths.some((sp) => sp.anchors.some((a) => radiusOf(a) > 0));\n}\n\n/** One subpath with its corners cut; `sources[i]` is the stored anchor each output anchor comes from. */\nexport function expandVectorCornersOf(sp: VectorSubpath, subpath = 0): { subpath: VectorSubpath; sources: number[] } {\n\tconst n = sp.anchors.length;\n\tconst cuts: (Cut | null)[] = sp.anchors.map((a, i) => {\n\t\tconst r = radiusOf(a);\n\t\tif (!r) return null;\n\t\tconst c = cornerOf(sp, subpath, i);\n\t\tif (!c) return null;\n\t\tconst fitted = fitCornerRadius(c, r);\n\t\treturn fitted > EPS ? cutCorner(c, fitted, a.corner?.kind ?? 'round') : null;\n\t});\n\tif (!cuts.some(Boolean)) return { subpath: { closed: sp.closed, anchors: sp.anchors.map(plain) }, sources: sp.anchors.map((_, i) => i) };\n\t// Each segment from anchor j trimmed to what the cuts at its ends leave: its handles, or\n\t// undefined when it is untouched (null handles: a straight segment).\n\tconst trimmed: ({ out: Vec2 | null; in: Vec2 | null } | undefined)[] = sp.anchors.map((a, j) => {\n\t\tconst k = (j + 1) % n;\n\t\tif (k === 0 && !sp.closed) return undefined;\n\t\tconst b = sp.anchors[k];\n\t\tconst from = cuts[j];\n\t\tconst to = cuts[k];\n\t\tif (!from && !to) return undefined;\n\t\tif (onAnchor(a, a.out) && onAnchor(b, b.in)) return { out: null, in: null };\n\t\tconst s0 = from ? from.tv : 0;\n\t\tconst s1 = to ? 1 - to.tu : 1;\n\t\tconst seg: Point[] = [pt(a), pt(a.out ?? a), pt(b.in ?? b), pt(b)];\n\t\tconst part = subSegment(seg, s0, Math.max(s0, s1));\n\t\treturn { out: vec(part[1]), in: vec(part[2]) };\n\t});\n\tconst anchors: VectorAnchor[] = [];\n\tconst sources: number[] = [];\n\tlet closing: VectorAnchor | null = null;\n\tconst handleIn = (i: number, a: VectorAnchor) => {\n\t\tconst t = trimmed[(i - 1 + n) % n];\n\t\treturn t ? t.in : (a.in ?? null);\n\t};\n\tconst handleOut = (i: number, a: VectorAnchor) => {\n\t\tconst t = trimmed[i];\n\t\treturn t ? t.out : (a.out ?? null);\n\t};\n\tsp.anchors.forEach((a, i) => {\n\t\tconst c = cuts[i];\n\t\tif (!c) {\n\t\t\tanchors.push(withHandles({ x: a.x, y: a.y, ...(a.type ? { type: a.type } : {}) }, handleIn(i, a), handleOut(i, a)));\n\t\t\tsources.push(i);\n\t\t\treturn;\n\t\t}\n\t\tconst start = withHandles({ x: c.start.x, y: c.start.y }, handleIn(i, a), c.out);\n\t\tconst end = withHandles({ x: c.end.x, y: c.end.y }, c.in, handleOut(i, a));\n\t\tif (i === 0 && sp.closed) closing = start;\n\t\telse {\n\t\t\tanchors.push(start);\n\t\t\tsources.push(i);\n\t\t}\n\t\tanchors.push(end);\n\t\tsources.push(i);\n\t});\n\tif (closing) {\n\t\tanchors.push(closing);\n\t\tsources.push(0);\n\t}\n\treturn { subpath: { closed: sp.closed, anchors }, sources };\n}\n\nfunction withHandles(a: VectorAnchor, hin: Vec2 | null, hout: Vec2 | null): VectorAnchor {\n\tif (hin && !onAnchor(a, hin)) a.in = { x: hin.x, y: hin.y };\n\tif (hout && !onAnchor(a, hout)) a.out = { x: hout.x, y: hout.y };\n\treturn a;\n}\n\nfunction plain(a: VectorAnchor): VectorAnchor {\n\tif (!('corner' in a)) return a;\n\tconst { corner: _c, ...rest } = a;\n\treturn rest;\n}\n\n/**\n * The subpaths with every live corner cut (round, inverted or chamfer), each radius no larger\n * than fits. A cut corner becomes two anchors and curved sides are trimmed to what the cuts\n * leave of them. Subpaths without corners come back unchanged.\n */\nexport function expandVectorCorners(subpaths: readonly VectorSubpath[]): VectorSubpath[] {\n\tif (!hasVectorCorners(subpaths)) return subpaths as VectorSubpath[];\n\treturn subpaths.map((sp, s) => (sp.anchors.some((a) => radiusOf(a) > 0) ? expandVectorCornersOf(sp, s).subpath : sp));\n}\n\n/**\n * Sets (or clears, with radius 0) the live corner of anchors. `kind` keeps each anchor's own\n * kind when omitted. Anchors that make no corner keep the radius too, so it applies once they do.\n */\nexport function setAnchorCorner(a: VectorAnchor, radius: number, kind?: VectorCornerKind): VectorAnchor {\n\tconst { corner, ...rest } = a;\n\tconst r = Number.isFinite(radius) ? Math.max(0, radius) : 0;\n\tconst k = kind ?? corner?.kind;\n\tif (r <= 0 && !kind) return rest;\n\treturn { ...rest, corner: { radius: r, ...(k && k !== 'round' ? { kind: k } : {}) } };\n}\n\n/** The next corner kind (Alt-clicking a corner widget cycles round → inverted → chamfer). */\nexport function nextVectorCornerKind(kind: VectorCornerKind | undefined): VectorCornerKind {\n\treturn kind === 'inverted' ? 'chamfer' : kind === 'chamfer' ? 'round' : 'inverted';\n}\n\n/** Every anchor of a subpath given the same live corner (radius 0 clears them). */\nexport function setSubpathCorners(sp: VectorSubpath, radius: number, kind?: VectorCornerKind): VectorSubpath {\n\treturn { closed: sp.closed, anchors: sp.anchors.map((a) => setAnchorCorner(a, radius, kind)) };\n}\n","/**\n * Variable-width stroke profiles: stroke widths at positions along a path (each subpath on its\n * own), interpolated smoothly and held flat before the first and after the last point. Each\n * point has a left and a right side scale (looking along the path on screen, y down), so a\n * stroke can grow on one side only.\n *\n * Ported from ArtCraft (MIT OR Apache-2.0, see THIRD_PARTY_NOTICES.md):\n * - figcraft `crates/doc/src/props.rs` — `WidthProfile` / `WidthPoint`: sanitising, side\n * scales, inserting and moving points, and the monotone cubic (Fritsch–Carlson) interpolation\n * that never overshoots its neighbouring points.\n * - vectorcraft `crates/doc/src/appearance.rs` — `WidthProfile` as `(t, left, right)` points,\n * discontinuous points (two points at one `t` make a step) and the profile presets.\n * - effectcraft `crates/path/src/varstroke.rs` — `width_factor`: the parametric Taper (lengths,\n * end widths, ease) and Wave (amount, cycles, phase) shapes, used here as profile generators.\n */\nimport type { VectorWidthPoint } from './types.js';\n\n/** The most points a profile keeps. */\nexport const VECTOR_WIDTH_PROFILE_MAX_POINTS = 64;\n/** The widest a side can be, as a multiple of the stroke width. */\nexport const VECTOR_WIDTH_PROFILE_MAX_SCALE = 1000;\n/** Positions closer than this are the same place (the two sides of a discontinuous point). */\nexport const VECTOR_WIDTH_SAME_T = 1e-6;\n\n/** Built-in profiles. `uniform` is the plain stroke (no profile). */\nexport type VectorWidthPreset = 'uniform' | 'taperStart' | 'taperEnd' | 'taperBoth' | 'bulge' | 'pinch' | 'teardrop' | 'wave' | 'pressure';\n\n/** One preset as a menu shows it. */\nexport interface VectorWidthPresetInfo {\n\tid: VectorWidthPreset;\n\tlabel: string;\n\tpoints: readonly VectorWidthPoint[];\n}\n\nconst sym = (t: number, s: number): VectorWidthPoint => ({ t, left: s, right: s });\n\n/** The built-in profiles, in menu order. */\nexport const VECTOR_WIDTH_PRESETS: readonly VectorWidthPresetInfo[] = [\n\t{ id: 'uniform', label: 'Uniform', points: [] },\n\t{ id: 'taperStart', label: 'Taper start', points: [sym(0, 0), sym(1, 1)] },\n\t{ id: 'taperEnd', label: 'Taper end', points: [sym(0, 1), sym(1, 0)] },\n\t{ id: 'taperBoth', label: 'Taper both', points: [sym(0, 0), sym(0.5, 1), sym(1, 0)] },\n\t// Full width at the ends, swelling to twice the width in the middle.\n\t{ id: 'bulge', label: 'Bulge', points: [sym(0, 1), sym(0.5, 2), sym(1, 1)] },\n\t// Full width at the ends, pinched to a quarter in the middle.\n\t{ id: 'pinch', label: 'Pinch', points: [sym(0, 1), sym(0.5, 0.25), sym(1, 1)] },\n\t// A round head a fifth of the way along, then a long taper to the end.\n\t{ id: 'teardrop', label: 'Teardrop', points: [sym(0, 0), sym(0.2, 1), sym(1, 0)] },\n\t// Two swells between narrow necks.\n\t{ id: 'wave', label: 'Wave', points: [sym(0, 0.3), sym(0.25, 1), sym(0.5, 0.3), sym(0.75, 1), sym(1, 0.3)] },\n\t// A pen stroke: a quick press, a slow lift.\n\t{ id: 'pressure', label: 'Pressure', points: [sym(0, 0.15), sym(0.12, 0.85), sym(0.45, 1), sym(0.8, 0.7), sym(1, 0.05)] }\n];\n\nexport const VECTOR_WIDTH_PRESET_IDS: readonly VectorWidthPreset[] = VECTOR_WIDTH_PRESETS.map((p) => p.id);\n\nconst clean = (v: unknown, max: number) => (typeof v === 'number' && Number.isFinite(v) ? Math.min(Math.max(v, 0), max) : null);\n\n/**\n * A profile as the outline uses it: finite points only, `t` in 0–1, side scales in 0–1000,\n * sorted by `t` (stable, so a step keeps its order), at most 64 points. Points missing a side\n * take the other side's scale.\n */\nexport function sanitizeWidthProfile(points: readonly Partial<VectorWidthPoint>[] | null | undefined): VectorWidthPoint[] {\n\tif (!Array.isArray(points)) return [];\n\tconst out: VectorWidthPoint[] = [];\n\tfor (const p of points) {\n\t\tif (!p || typeof p !== 'object') continue;\n\t\tconst t = clean(p.t, 1);\n\t\tconst l = clean(p.left, VECTOR_WIDTH_PROFILE_MAX_SCALE);\n\t\tconst r = clean(p.right, VECTOR_WIDTH_PROFILE_MAX_SCALE);\n\t\tif (t === null || (l === null && r === null)) continue;\n\t\tout.push({ t, left: l ?? r!, right: r ?? l! });\n\t\tif (out.length >= VECTOR_WIDTH_PROFILE_MAX_POINTS) break;\n\t}\n\treturn out.map((p, i) => [p, i] as const).sort((a, b) => a[0].t - b[0].t || a[1] - b[1]).map(([p]) => p);\n}\n\n/** True when the profile draws a plain stroke: no points, or every side at scale 1. */\nexport function isUniformWidthProfile(points: readonly VectorWidthPoint[] | null | undefined): boolean {\n\treturn !points?.length || points.every((p) => p.left === 1 && p.right === 1);\n}\n\n/** Slope of side `k` from point `i` to `i + 1` (0 when they share a position). */\nfunction secant(pts: readonly VectorWidthPoint[], i: number, k: 'left' | 'right'): number {\n\tconst a = pts[i];\n\tconst b = pts[i + 1];\n\treturn a && b && b.t - a.t > 1e-12 ? (b[k] - a[k]) / (b.t - a.t) : 0;\n}\n\n/** Fritsch–Carlson tangent: one-sided at the ends, the harmonic mean of the slopes inside, flat at local extremes. */\nfunction tangent(pts: readonly VectorWidthPoint[], i: number, k: 'left' | 'right'): number {\n\tconst last = pts.length - 1;\n\tif (i <= 0) return secant(pts, 0, k);\n\tif (i >= last) return secant(pts, last - 1, k);\n\tconst d0 = secant(pts, i - 1, k);\n\tconst d1 = secant(pts, i, k);\n\treturn d0 * d1 <= 0 ? 0 : (2 * d0 * d1) / (d0 + d1);\n}\n\nfunction interp(pts: readonly VectorWidthPoint[], t: number, k: 'left' | 'right'): number {\n\tconst first = pts[0];\n\tconst last = pts[pts.length - 1];\n\tif (!(t > first.t)) return first[k];\n\tif (t >= last.t) return last[k];\n\t// The last point at or before t (the second of a step at exactly t).\n\tlet i = 0;\n\twhile (i + 1 < pts.length && pts[i + 1].t <= t) i++;\n\tconst a = pts[i];\n\tconst b = pts[i + 1];\n\tconst h = b.t - a.t;\n\tif (h <= 1e-12) return b[k];\n\tconst u = (t - a.t) / h;\n\tconst u2 = u * u;\n\tconst u3 = u2 * u;\n\tconst w = (2 * u3 - 3 * u2 + 1) * a[k] + (u3 - 2 * u2 + u) * h * tangent(pts, i, k) + (3 * u2 - 2 * u3) * b[k] + (u3 - u2) * h * tangent(pts, i + 1, k);\n\treturn Math.max(0, w);\n}\n\n/**\n * The left and right side scales at `t` (0–1 along the subpath by length). Each side is\n * interpolated on its own with a monotone cubic, so the width never overshoots its points;\n * a profile without points is uniform (1, 1).\n */\nexport function widthProfileAt(points: readonly VectorWidthPoint[] | null | undefined, t: number): { left: number; right: number } {\n\tif (!points?.length) return { left: 1, right: 1 };\n\treturn { left: interp(points, t, 'left'), right: interp(points, t, 'right') };\n}\n\n/** The largest side scale (the interpolation never exceeds its points); 1 without a profile. */\nexport function widthProfileMaxScale(points: readonly VectorWidthPoint[] | null | undefined): number {\n\tif (!points?.length) return 1;\n\treturn points.reduce((m, p) => Math.max(m, p.left, p.right), 0);\n}\n\n/** The points of a preset (empty for `uniform`), or null for an unknown id. */\nexport function widthProfilePreset(id: string): VectorWidthPoint[] | null {\n\tconst p = VECTOR_WIDTH_PRESETS.find((q) => q.id === id);\n\treturn p ? p.points.map((q) => ({ ...q })) : null;\n}\n\n/** The preset a profile matches: `uniform` without one (or all at scale 1), `custom` when none matches. */\nexport function widthProfilePresetId(points: readonly VectorWidthPoint[] | null | undefined): VectorWidthPreset | 'custom' {\n\tif (isUniformWidthProfile(points)) return 'uniform';\n\tconst same = (a: readonly VectorWidthPoint[], b: readonly VectorWidthPoint[]) =>\n\t\ta.length === b.length && a.every((p, i) => Math.abs(p.t - b[i].t) < 1e-9 && Math.abs(p.left - b[i].left) < 1e-9 && Math.abs(p.right - b[i].right) < 1e-9);\n\treturn VECTOR_WIDTH_PRESETS.find((p) => p.points.length && same(points!, p.points))?.id ?? 'custom';\n}\n\n/** The profile of the reversed path: positions mirrored and the sides swapped. */\nexport function reverseWidthProfile(points: readonly VectorWidthPoint[]): VectorWidthPoint[] {\n\treturn points.map((p) => ({ t: 1 - p.t, left: p.right, right: p.left })).reverse();\n}\n\n/** The profile of a mirrored path (it runs the same way, but its sides swap). */\nexport function mirrorWidthProfile(points: readonly VectorWidthPoint[]): VectorWidthPoint[] {\n\treturn points.map((p) => ({ t: p.t, left: p.right, right: p.left }));\n}\n\n/** The points a profile edit starts from: the profile, or a uniform one with a point at each end. */\nfunction editable(points: readonly VectorWidthPoint[] | null | undefined): VectorWidthPoint[] {\n\treturn points?.length ? points.map((p) => ({ ...p })) : [sym(0, 1), sym(1, 1)];\n}\n\n/**\n * Adds a width point at `t` (side scales `left` / `right`, default: as wide as the stroke is\n * there) and returns the new profile and the point's index. Inserting at the position of an\n * existing point replaces it, unless `step` is set (which makes a discontinuous point).\n */\nexport function insertWidthPoint(\n\tpoints: readonly VectorWidthPoint[] | null | undefined,\n\tt: number,\n\tsides: { left?: number; right?: number } = {},\n\toptions: { step?: boolean } = {}\n): { points: VectorWidthPoint[]; index: number } {\n\tconst pts = editable(points);\n\tconst tt = Math.min(Math.max(Number.isFinite(t) ? t : 0, 0), 1);\n\tconst here = widthProfileAt(points?.length ? points : null, tt);\n\tconst p: VectorWidthPoint = {\n\t\tt: tt,\n\t\tleft: clean(sides.left, VECTOR_WIDTH_PROFILE_MAX_SCALE) ?? here.left,\n\t\tright: clean(sides.right, VECTOR_WIDTH_PROFILE_MAX_SCALE) ?? here.right\n\t};\n\tconst same = pts.findIndex((q) => Math.abs(q.t - tt) <= VECTOR_WIDTH_SAME_T);\n\tif (same >= 0 && !options.step) {\n\t\tpts[same] = { ...p, t: pts[same].t };\n\t\treturn { points: pts, index: same };\n\t}\n\tlet i = 0;\n\twhile (i < pts.length && pts[i].t <= tt) i++;\n\tif (pts.length >= VECTOR_WIDTH_PROFILE_MAX_POINTS) return { points: pts, index: Math.max(0, i - 1) };\n\tpts.splice(i, 0, p);\n\treturn { points: pts, index: i };\n}\n\n/**\n * Changes point `index`: moves it to `t` (kept between its neighbours, so indices stay put)\n * and / or sets its side scales. Out-of-range indices leave the profile as it is.\n */\nexport function setWidthPoint(points: readonly VectorWidthPoint[], index: number, patch: Partial<VectorWidthPoint>): VectorWidthPoint[] {\n\tconst pts = points.map((p) => ({ ...p }));\n\tconst p = pts[index];\n\tif (!p) return pts;\n\tif (typeof patch.t === 'number' && Number.isFinite(patch.t)) {\n\t\tconst lo = index > 0 ? pts[index - 1].t : 0;\n\t\tconst hi = index < pts.length - 1 ? pts[index + 1].t : 1;\n\t\tp.t = Math.min(Math.max(patch.t, lo), Math.max(hi, lo));\n\t}\n\tconst l = clean(patch.left, VECTOR_WIDTH_PROFILE_MAX_SCALE);\n\tconst r = clean(patch.right, VECTOR_WIDTH_PROFILE_MAX_SCALE);\n\tif (l !== null) p.left = l;\n\tif (r !== null) p.right = r;\n\treturn pts;\n}\n\n/** Removes the points at `indices`. */\nexport function removeWidthPoints(points: readonly VectorWidthPoint[], indices: readonly number[]): VectorWidthPoint[] {\n\tconst drop = new Set(indices);\n\treturn points.filter((_, i) => !drop.has(i)).map((p) => ({ ...p }));\n}\n\n// ---------------------------------------------------------------------------\n// Generators\n// ---------------------------------------------------------------------------\n\n/** effectcraft's ease from the tip (`u = 0`) to full width (`u = 1`): linear at 0, a quarter circle at 1. */\nfunction ease(u: number, e: number): number {\n\tconst x = Math.min(Math.max(u, 0), 1);\n\tconst round = Math.sqrt(Math.max(0, 1 - (1 - x) * (1 - x)));\n\treturn x + (round - x) * Math.min(Math.max(e, 0), 1);\n}\n\n/** A parametric taper (effectcraft's Stroke Taper), lengths as fractions of the path. */\nexport interface VectorTaperOptions {\n\t/** Fraction of the path the start taper covers (default 0). */\n\tstartLength?: number;\n\t/** Fraction the end taper covers (default 0). */\n\tendLength?: number;\n\t/** Width at the start as a fraction of the stroke width (default 0: a point). */\n\tstartWidth?: number;\n\tendWidth?: number;\n\t/** 0 linear, 1 a quarter circle bulging outwards (default 0). */\n\tstartEase?: number;\n\tendEase?: number;\n}\n\n/** A width wave (effectcraft's Stroke Wave): the width swings between `1 − amount` and 1. */\nexport interface VectorWaveOptions {\n\t/** 0–1 (default 0.5). */\n\tamount?: number;\n\t/** Whole cycles along the path (default 4). */\n\tcycles?: number;\n\t/** Degrees (default 0). */\n\tphase?: number;\n}\n\n/** The width factor at fraction `t` of a taper and / or a wave (effectcraft `width_factor`). */\nexport function taperWaveFactor(t: number, taper?: VectorTaperOptions | null, wave?: VectorWaveOptions | null): number {\n\tlet k = 1;\n\tif (taper) {\n\t\tlet ls = Math.max(0, taper.startLength ?? 0);\n\t\tlet le = Math.max(0, taper.endLength ?? 0);\n\t\t// Overlapping tapers share the path in proportion.\n\t\tif (ls + le > 1) {\n\t\t\tconst f = 1 / (ls + le);\n\t\t\tls *= f;\n\t\t\tle *= f;\n\t\t}\n\t\tconst sw = Math.min(Math.max(taper.startWidth ?? 0, 0), 1);\n\t\tconst ew = Math.min(Math.max(taper.endWidth ?? 0, 0), 1);\n\t\tif (ls > 0 && t < ls) k = Math.min(k, sw + (1 - sw) * ease(t / ls, taper.startEase ?? 0));\n\t\tif (le > 0 && t > 1 - le) k = Math.min(k, ew + (1 - ew) * ease((1 - t) / le, taper.endEase ?? 0));\n\t}\n\tif (wave) {\n\t\tconst cycles = wave.cycles ?? 4;\n\t\tconst amount = Math.min(Math.max(wave.amount ?? 0.5, 0), 1);\n\t\tif (cycles > 0 && amount > 0) {\n\t\t\tconst ph = 2 * Math.PI * t * cycles + ((wave.phase ?? 0) * Math.PI) / 180;\n\t\t\tk *= 1 - amount * (0.5 - 0.5 * Math.cos(ph));\n\t\t}\n\t}\n\treturn k;\n}\n\n/**\n * Samples a taper and / or wave into profile points (symmetric), simplified to within\n * `tolerance` of the factor (default 0.01). The monotone interpolation draws them back smoothly.\n */\nexport function generateWidthProfile(options: { taper?: VectorTaperOptions | null; wave?: VectorWaveOptions | null; samples?: number; tolerance?: number }): VectorWidthPoint[] {\n\tconst cycles = options.wave ? Math.max(0, options.wave.cycles ?? 4) : 0;\n\tconst n = Math.max(8, Math.min(VECTOR_WIDTH_PROFILE_MAX_POINTS * 4, options.samples ?? Math.ceil(32 + cycles * 16)));\n\tconst raw: [number, number][] = [];\n\tfor (let i = 0; i <= n; i++) raw.push([i / n, taperWaveFactor(i / n, options.taper, options.wave)]);\n\t// Keep the taper ends exactly.\n\tconst ts = [options.taper?.startLength, options.taper?.endLength !== undefined ? 1 - options.taper.endLength : undefined];\n\tfor (const t of ts) if (typeof t === 'number' && t > 0 && t < 1) raw.push([t, taperWaveFactor(t, options.taper, options.wave)]);\n\traw.sort((a, b) => a[0] - b[0]);\n\tconst kept = simplifySamples(raw, options.tolerance ?? 0.01, VECTOR_WIDTH_PROFILE_MAX_POINTS);\n\treturn kept.map(([t, k]) => sym(t, k));\n}\n\n/** Douglas–Peucker on (t, value) samples (vertical distance), then thinned to at most `max`. */\nfunction simplifySamples(samples: readonly [number, number][], tolerance: number, max: number): [number, number][] {\n\tif (samples.length <= 2) return samples.slice();\n\tconst keep = new Array(samples.length).fill(false);\n\tkeep[0] = keep[samples.length - 1] = true;\n\tconst stack: [number, number][] = [[0, samples.length - 1]];\n\twhile (stack.length) {\n\t\tconst [a, b] = stack.pop()!;\n\t\tconst [ta, va] = samples[a];\n\t\tconst [tb, vb] = samples[b];\n\t\tlet worst = -1;\n\t\tlet err = tolerance;\n\t\tfor (let i = a + 1; i < b; i++) {\n\t\t\tconst [t, v] = samples[i];\n\t\t\tconst lin = tb - ta > 1e-12 ? va + ((vb - va) * (t - ta)) / (tb - ta) : va;\n\t\t\tconst e = Math.abs(v - lin);\n\t\t\tif (e > err) {\n\t\t\t\terr = e;\n\t\t\t\tworst = i;\n\t\t\t}\n\t\t}\n\t\tif (worst >= 0) {\n\t\t\tkeep[worst] = true;\n\t\t\tstack.push([a, worst], [worst, b]);\n\t\t}\n\t}\n\tlet out = samples.filter((_, i) => keep[i]);\n\twhile (out.length > max) out = out.filter((_, i) => i === 0 || i === out.length - 1 || i % 2 === 0);\n\treturn out;\n}\n\n/** Pen pressure that draws the stroke's own width (a mouse reports 0.5 while a button is down). */\nexport const VECTOR_PRESSURE_NOMINAL = 0.5;\n\n/**\n * A profile from pen pressure recorded along a stroke: `(t, pressure 0–1)` samples in order.\n * The width scale is pressure ÷ 0.5 (so half pressure draws the stroke's width, full pressure\n * twice it), at least 0.05; the samples are simplified to within `tolerance` (default 0.02).\n * Returns an empty (uniform) profile when every sample is the same.\n */\nexport function pressureWidthProfile(samples: readonly { t: number; pressure: number }[], options: { tolerance?: number } = {}): VectorWidthPoint[] {\n\tconst raw: [number, number][] = samples\n\t\t.filter((s) => Number.isFinite(s.t) && Number.isFinite(s.pressure))\n\t\t.map((s) => [Math.min(Math.max(s.t, 0), 1), Math.max(0.05, Math.min(1, Math.max(0, s.pressure)) / VECTOR_PRESSURE_NOMINAL)] as [number, number]);\n\tif (raw.length < 2) return [];\n\tif (raw.every((s) => Math.abs(s[1] - raw[0][1]) < 1e-6)) return [];\n\treturn simplifySamples(raw, options.tolerance ?? 0.02, VECTOR_WIDTH_PROFILE_MAX_POINTS).map(([t, k]) => sym(t, Math.round(k * 1000) / 1000));\n}\n","/**\n * The outline of a variable-width stroke, as a clean filled Bézier path.\n *\n * Each subpath is flattened (finely enough for the width to vary smoothly) and the stroke is\n * the union of positively wound pieces: one trapezoid per flattened segment (its ends at the\n * local side widths), a wedge on the outer side of every bend (the style's join at the path's\n * own corners, round inside curves) and the caps. Filled with the non-zero rule the union is\n * exact whatever the profile does; it is built as the boundary those pieces add up to (see\n * `variableStrokeRings`), normalised with the polygon boolean engine, and every ring is refitted\n * with cubics (`fitCubics`) to within the tolerance — a real Bézier outline, not a polyline.\n *\n * Ported from ArtCraft effectcraft `crates/path/src/varstroke.rs` (`outline`, `dash_intervals`)\n * (MIT OR Apache-2.0, see THIRD_PARTY_NOTICES.md), with one-sided widths after figcraft\n * `crates/pathops/src/width.rs` (`variable_outline`).\n */\nimport type { Point } from '../canvas/types.js';\nimport { fitCubics, isStraightCubic } from '../canvas/curveFit.js';\nimport { polygonBoolean } from '../canvas/polygonBoolean.js';\nimport {\n\tflattenChain,\n\tpathToContours,\n\tsegmentLength,\n\tsegmentNearest,\n\tsegmentTangent,\n\ttype BezierPath,\n\ttype BezierSegment\n} from '../canvas/pathops/bezier.js';\nimport type { StrokeCap, StrokeJoin } from '../canvas/pathops/stroke.js';\nimport type { VectorWidthPoint } from './types.js';\nimport { widthProfileAt } from './width.js';\n\nexport interface VariableStrokeOptions {\n\t/** Stroke width: a side scale of 1 reaches half of it from the centre line. */\n\twidth: number;\n\tprofile: readonly VectorWidthPoint[];\n\t/** Joins at the path's own corners (default `miter`); bends inside curves are always round. */\n\tjoin?: StrokeJoin;\n\t/** Default `butt`. */\n\tcap?: StrokeCap;\n\t/** Default 4 (as SVG). */\n\tmiterLimit?: number;\n\t/** Dash pattern (as SVG); the profile still runs along the whole subpath. */\n\tdash?: readonly number[];\n\tdashOffset?: number;\n\t/** Largest distance of the result from the exact outline (default 0.05). */\n\ttolerance?: number;\n}\n\n/** Width samples per subpath at least (so the width varies smoothly along long straight runs). */\nconst SAMPLES_PER_SUBPATH = 128;\n/** The most dashes one subpath makes. */\nconst MAX_DASHES = 5000;\n\ntype Vec = [number, number];\nconst sub = (a: Point, b: Point): Vec => [a[0] - b[0], a[1] - b[1]];\nconst along = (p: Point, v: Vec, k: number): Point => [p[0] + v[0] * k, p[1] + v[1] * k];\nconst lerp = (a: Point, b: Point, u: number): Point => [a[0] + (b[0] - a[0]) * u, a[1] + (b[1] - a[1]) * u];\nconst dist = (a: Point, b: Point) => Math.hypot(a[0] - b[0], a[1] - b[1]);\nconst unitOf = (v: Vec): Vec => {\n\tconst l = Math.hypot(v[0], v[1]);\n\treturn l > 0 ? [v[0] / l, v[1] / l] : [1, 0];\n};\n/** The left normal of a direction on screen (y down): `(dy, −dx)`. */\nconst leftNormal = (d: Vec): Vec => [d[1], -d[0]];\n\n/** A flattened subpath: points, their arc lengths, and which are the path's own vertices. */\ninterface Poly {\n\tpts: Point[];\n\ts: number[];\n\tcorner: boolean[];\n\tclosed: boolean;\n}\n\nfunction flatten(segments: readonly BezierSegment[], closed: boolean, tol: number): Poly | null {\n\tconst pts: Point[] = [];\n\tconst corner: boolean[] = [];\n\tconst push = (p: Point, isCorner: boolean) => {\n\t\tconst last = pts[pts.length - 1];\n\t\tif (last && dist(last, p) <= 1e-9) {\n\t\t\tcorner[corner.length - 1] ||= isCorner;\n\t\t\treturn;\n\t\t}\n\t\tpts.push(p);\n\t\tcorner.push(isCorner);\n\t};\n\tfor (const seg of segments) {\n\t\tconst flat = flattenChain([seg], tol);\n\t\t// flattenChain drops a closing duplicate; segments that end where they start keep it.\n\t\tif (dist(seg[0], seg[seg.length - 1]) <= 1e-12 && flat.length > 1) flat.push(seg[seg.length - 1]);\n\t\tflat.forEach((p, i) => push(p, i === 0 || i === flat.length - 1));\n\t}\n\tif (closed && pts.length > 2 && dist(pts[0], pts[pts.length - 1]) > 1e-9) push(pts[0], true);\n\tif (pts.length < 2) return null;\n\t// Subdivide so no piece is longer than the width sampling step.\n\tlet total = 0;\n\tfor (let i = 1; i < pts.length; i++) total += dist(pts[i - 1], pts[i]);\n\tif (!(total > 0)) return null;\n\tconst step = Math.max(total / SAMPLES_PER_SUBPATH, tol);\n\tconst fine: Point[] = [pts[0]];\n\tconst fineCorner: boolean[] = [corner[0]];\n\tfor (let i = 1; i < pts.length; i++) {\n\t\tconst n = Math.max(1, Math.ceil(dist(pts[i - 1], pts[i]) / step));\n\t\tfor (let k = 1; k <= n; k++) {\n\t\t\tfine.push(k === n ? pts[i] : lerp(pts[i - 1], pts[i], k / n));\n\t\t\tfineCorner.push(k === n ? corner[i] : false);\n\t\t}\n\t}\n\tconst s = [0];\n\tfor (let i = 1; i < fine.length; i++) s.push(s[i - 1] + dist(fine[i - 1], fine[i]));\n\treturn { pts: fine, s, corner: fineCorner, closed };\n}\n\n/** Arc-length intervals that are \"on\" for a dash pattern on a path `len` long (effectcraft `dash_intervals`). */\nexport function dashIntervals(pattern: readonly number[], offset: number, len: number): [number, number][] {\n\tlet pat = pattern.map((v) => (Number.isFinite(v) ? Math.max(0, v) : 0));\n\tif (pat.length % 2 === 1) pat = [...pat, ...pat];\n\tconst period = pat.reduce((a, b) => a + b, 0);\n\tif (pat.length < 2 || !(period > 1e-9) || !(len > 0)) return [[0, len]];\n\tlet pos = (((Number.isFinite(offset) ? offset : 0) % period) + period) % period;\n\tlet idx = 0;\n\twhile (pos >= pat[idx]) {\n\t\tpos -= pat[idx];\n\t\tidx = (idx + 1) % pat.length;\n\t}\n\tconst out: [number, number][] = [];\n\tlet s = 0;\n\tlet guard = 0;\n\twhile (s < len && guard++ < MAX_DASHES * pat.length) {\n\t\tconst e = Math.min(s + pat[idx] - pos, len);\n\t\tif (idx % 2 === 0 && e >= s) out.push([s, e]);\n\t\ts += pat[idx] - pos;\n\t\tpos = 0;\n\t\tidx = (idx + 1) % pat.length;\n\t}\n\treturn out;\n}\n\n/** The point at arc length `t` of a polyline and the index of the segment it lies on. */\nfunction at(poly: Poly, t: number): [Point, number] {\n\tlet i = 1;\n\twhile (i < poly.pts.length - 1 && poly.s[i] <= t) i++;\n\tconst a = poly.s[i - 1];\n\tconst b = poly.s[i];\n\tconst u = b > a ? Math.min(Math.max((t - a) / (b - a), 0), 1) : 0;\n\treturn [lerp(poly.pts[i - 1], poly.pts[i], u), i];\n}\n\n/** Points of an arc around `c` from angle `a0` turning by `sweep`, radius going from `r0` to `r1` (ends excluded). */\nfunction arcPoints(c: Point, a0: number, sweep: number, r0: number, r1: number, tol: number): Point[] {\n\tconst r = Math.max(r0, r1);\n\tif (!(r > tol * 0.5) || !Number.isFinite(sweep)) return [];\n\tconst stepAngle = 2 * Math.acos(Math.min(Math.max(1 - tol / r, -1), 1));\n\tconst n = Math.min(128, Math.max(2, Math.ceil(Math.abs(sweep) / Math.max(stepAngle, 1e-3))));\n\tconst out: Point[] = [];\n\tfor (let k = 1; k < n; k++) {\n\t\tconst f = k / n;\n\t\tconst a = a0 + sweep * f;\n\t\tconst rr = r0 + (r1 - r0) * f;\n\t\tout.push([c[0] + Math.cos(a) * rr, c[1] + Math.sin(a) * rr]);\n\t}\n\treturn out;\n}\n\n/** Where segments `a0 → a1` and `b0 → b1` cross, if they do (strictly inside `b`, anywhere past the start of `a`). */\nfunction crossing(a0: Point, a1: Point, b0: Point, b1: Point): Point | null {\n\tconst r = sub(a1, a0);\n\tconst q = sub(b1, b0);\n\tconst den = r[0] * q[1] - r[1] * q[0];\n\tif (Math.abs(den) < 1e-12) return null;\n\tconst w = sub(b0, a0);\n\tconst t = (w[0] * q[1] - w[1] * q[0]) / den;\n\tconst u = (w[0] * r[1] - w[1] * r[0]) / den;\n\treturn t > 1e-9 && t <= 1 && u >= 0 && u < 1 - 1e-9 ? [a0[0] + r[0] * t, a0[1] + r[1] * t] : null;\n}\n\n/**\n * The rings of a variable-width stroke in the path's own space; filled with the non-zero rule\n * they are the stroke.\n *\n * effectcraft builds the stroke as a union of positively wound pieces: a trapezoid per flattened\n * segment (its ends at the local side widths), a wedge on the outer side of every bend and the\n * caps. Unioning thousands of overlapping pieces is slow, so each run is emitted as the boundary\n * those pieces add up to instead (winding numbers add, so the non-zero fill is the same): the\n * offset sides with the outer join between them, and on the inner side of a bend either the point\n * where the two offsets cross (the region cut off is covered by both trapezoids) or, when they do\n * not cross, a detour through the centre point (which keeps the winding right when segments are\n * shorter than the width). A closed subpath gives two rings, an open run one.\n */\nexport function variableStrokeRings(path: BezierPath, options: VariableStrokeOptions): Point[][] {\n\tconst half = options.width / 2;\n\tif (!(half > 0) || !Number.isFinite(half)) return [];\n\tconst tol = options.tolerance && options.tolerance > 0 ? options.tolerance : 0.05;\n\tconst join = options.join ?? 'miter';\n\tconst cap = options.cap ?? 'butt';\n\tconst miterLimit = options.miterLimit && options.miterLimit >= 1 ? options.miterLimit : 4;\n\tconst rings: Point[][] = [];\n\tconst push = (out: Point[], p: Point) => {\n\t\tconst last = out[out.length - 1];\n\t\tif (!last || dist(last, p) > 1e-12) out.push(p);\n\t};\n\tfor (const contour of pathToContours(path)) {\n\t\tif (!contour.segments.length) continue;\n\t\t// Chords of the offsets lose area on the outer side of a curve; a quarter of the tolerance keeps that well inside it.\n\t\tconst poly = flatten(contour.segments, contour.closed, Math.min(tol, half) / 4);\n\t\tif (!poly) continue;\n\t\tconst len = poly.s[poly.s.length - 1];\n\t\tconst sides = (s: number): [number, number] => {\n\t\t\tconst w = widthProfileAt(options.profile, s / len);\n\t\t\treturn [w.left * half, w.right * half];\n\t\t};\n\t\tconst intervals = options.dash?.some((v) => v > 0) ? dashIntervals(options.dash, options.dashOffset ?? 0, len) : [[0, len] as [number, number]];\n\t\tconst whole = intervals.length === 1 && intervals[0][0] <= 0 && intervals[0][1] >= len;\n\t\tfor (const [a, b] of intervals) {\n\t\t\tconst [pa, ia] = at(poly, a);\n\t\t\tconst [pb, ib] = at(poly, b);\n\t\t\tconst pts: { p: Point; s: number; corner: boolean }[] = [{ p: pa, s: a, corner: poly.corner[0] && a <= 0 }];\n\t\t\tfor (let i = ia; i < ib; i++) pts.push({ p: poly.pts[i], s: poly.s[i], corner: poly.corner[i] });\n\t\t\tpts.push({ p: pb, s: b, corner: false });\n\t\t\tconst run = pts.filter((q, i) => i === 0 || dist(q.p, pts[i - 1].p) > 1e-9);\n\t\t\tif (run.length < 2) {\n\t\t\t\t// A zero-length dash: only its caps show.\n\t\t\t\tconst [l, r] = sides(a);\n\t\t\t\tconst w = (l + r) / 2;\n\t\t\t\tif (cap === 'round' && w > 0) rings.push([[pa[0] + w, pa[1]], ...arcPoints(pa, 0, 2 * Math.PI, w, w, tol)]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst closed = whole && poly.closed;\n\t\t\tconst m = run.length - 1;\n\t\t\tconst dirs: Vec[] = [];\n\t\t\tfor (let i = 0; i < m; i++) dirs.push(unitOf(sub(run[i + 1].p, run[i].p)));\n\t\t\tconst normals = dirs.map(leftNormal);\n\t\t\tconst w = run.map((q) => sides(q.s));\n\n\t\t\t/** One side (`sigma` +1 left, −1 right) along the run, joins included. */\n\t\t\tconst side = (sigma: 1 | -1): Point[] => {\n\t\t\t\tconst k = sigma > 0 ? 0 : 1;\n\t\t\t\tconst S = (i: number) => along(run[i].p, normals[i], sigma * w[i][k]);\n\t\t\t\tconst E = (i: number) => along(run[i + 1].p, normals[i], sigma * w[i + 1][k]);\n\t\t\t\tconst out: Point[] = [S(0)];\n\t\t\t\tfor (let i = 0; i < m; i++) {\n\t\t\t\t\tconst seam = i === m - 1;\n\t\t\t\t\tif (seam && !closed) {\n\t\t\t\t\t\tpush(out, E(i));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tconst j = seam ? 0 : i + 1;\n\t\t\t\t\tconst p = run[i + 1].p;\n\t\t\t\t\tconst d0 = dirs[i];\n\t\t\t\t\tconst d1 = dirs[j];\n\t\t\t\t\tconst cross = d0[0] * d1[1] - d0[1] * d1[0];\n\t\t\t\t\tconst dot = d0[0] * d1[0] + d0[1] * d1[1];\n\t\t\t\t\tconst r0 = w[i + 1][k];\n\t\t\t\t\tconst r1 = w[j][k];\n\t\t\t\t\tconst e = E(i);\n\t\t\t\t\tconst st = S(j);\n\t\t\t\t\tif (Math.abs(cross) < 1e-12 && dot > 0) {\n\t\t\t\t\t\tpush(out, e);\n\t\t\t\t\t\tif (!seam) push(out, st);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst uturn = Math.abs(cross) < 1e-12;\n\t\t\t\t\t// Turning right on screen puts the left side outside the bend (a U-turn: the left side).\n\t\t\t\t\tconst outer = uturn ? sigma > 0 : cross * sigma > 0;\n\t\t\t\t\tif (!outer) {\n\t\t\t\t\t\tconst x = seam ? null : crossing(out[out.length - 1], e, st, E(j));\n\t\t\t\t\t\tif (x) push(out, x);\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tpush(out, e);\n\t\t\t\t\t\t\tpush(out, p);\n\t\t\t\t\t\t\tif (!seam) push(out, st);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tpush(out, e);\n\t\t\t\t\tconst theta = uturn ? Math.PI : Math.atan2(cross, dot);\n\t\t\t\t\tconst r = (r0 + r1) / 2;\n\t\t\t\t\tconst kind: StrokeJoin = run[i + 1].corner || (seam && poly.corner[0]) ? join : 'round';\n\t\t\t\t\tif (r > 1e-9) {\n\t\t\t\t\t\tif (kind === 'round') {\n\t\t\t\t\t\t\tif (r * (1 - Math.cos(Math.abs(theta) / 2)) > tol * 0.25) {\n\t\t\t\t\t\t\t\tfor (const q of arcPoints(p, Math.atan2(e[1] - p[1], e[0] - p[0]), theta, r0, r1, tol)) push(out, q);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (kind === 'miter') {\n\t\t\t\t\t\t\tconst halfCos = Math.cos(theta / 2);\n\t\t\t\t\t\t\tconst bis: Vec = [normals[i][0] + normals[j][0], normals[i][1] + normals[j][1]];\n\t\t\t\t\t\t\tconst bl = Math.hypot(bis[0], bis[1]);\n\t\t\t\t\t\t\tif (halfCos > 1e-6 && 1 / halfCos <= miterLimit && bl > 1e-9) push(out, along(p, bis, (sigma * r) / halfCos / bl));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!seam) push(out, st);\n\t\t\t\t}\n\t\t\t\tif (closed && out.length > 1 && dist(out[0], out[out.length - 1]) <= 1e-12) out.pop();\n\t\t\t\treturn out;\n\t\t\t};\n\t\t\tconst left = side(1);\n\t\t\tconst right = side(-1);\n\t\t\tif (closed) {\n\t\t\t\trings.push(left, right.reverse());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Caps: round or square around each end, from one side to the other.\n\t\t\tconst capPoints = (atStart: boolean): Point[] => {\n\t\t\t\tif (cap === 'butt') return [];\n\t\t\t\tconst i = atStart ? 0 : m;\n\t\t\t\tconst d = atStart ? dirs[0] : dirs[m - 1];\n\t\t\t\tconst [l, r] = w[i];\n\t\t\t\tif (!(l + r > 1e-9)) return [];\n\t\t\t\tconst p = run[i].p;\n\t\t\t\tconst n = leftNormal(d);\n\t\t\t\tconst L = along(p, n, l);\n\t\t\t\tconst R = along(p, n, -r);\n\t\t\t\tif (cap === 'round') {\n\t\t\t\t\t// Half a turn around the outside: right side to left at the start, left to right at the end.\n\t\t\t\t\tconst a0 = Math.atan2(d[1], d[0]) + (atStart ? Math.PI / 2 : -Math.PI / 2);\n\t\t\t\t\treturn arcPoints(p, a0, Math.PI, atStart ? r : l, atStart ? l : r, tol);\n\t\t\t\t}\n\t\t\t\tconst ext = (l + r) / 2;\n\t\t\t\tconst o: Vec = atStart ? [-d[0], -d[1]] : d;\n\t\t\t\treturn atStart ? [along(R, o, ext), along(L, o, ext)] : [along(L, o, ext), along(R, o, ext)];\n\t\t\t};\n\t\t\tconst ring: Point[] = [];\n\t\t\tfor (const q of [...left, ...capPoints(false), ...right.reverse(), ...capPoints(true)]) push(ring, q);\n\t\t\tif (ring.length > 2) rings.push(ring);\n\t\t}\n\t}\n\treturn rings;\n}\n\n/**\n * The outline of a variable-width stroke of `path` (side widths from `profile`), as a clean\n * Bézier path: overlaps removed, outer rings and holes, each refitted with cubics to within\n * `tolerance` of the exact outline. Fill it with the non-zero rule (either rule works).\n */\nexport function variableStrokeOutline(path: BezierPath, options: VariableStrokeOptions): BezierPath {\n\tconst pieces = variableStrokeRings(path, options);\n\tif (!pieces.length) return [];\n\tconst tol = options.tolerance && options.tolerance > 0 ? options.tolerance : 0.05;\n\tlet polygons;\n\ttry {\n\t\tpolygons = polygonBoolean('union', [{ rings: pieces, fillRule: 'nonzero' }]);\n\t} catch {\n\t\treturn [];\n\t}\n\tconst out: BezierPath = [];\n\tfor (const polygon of polygons) {\n\t\tfor (const ring of polygon) {\n\t\t\tif (ring.length < 3) continue;\n\t\t\tconst cubics = fitCubics(ring, tol, { closed: true, cornerAngleDeg: 25 });\n\t\t\tif (!cubics.length) continue;\n\t\t\tout.push({ type: 'M', x: cubics[0].p0[0], y: cubics[0].p0[1] });\n\t\t\tcubics.forEach((c, i) => {\n\t\t\t\tif (isStraightCubic(c, tol * 0.02)) {\n\t\t\t\t\tif (i < cubics.length - 1) out.push({ type: 'L', x: c.p3[0], y: c.p3[1] });\n\t\t\t\t} else out.push({ type: 'C', x1: c.p1[0], y1: c.p1[1], x2: c.p2[0], y2: c.p2[1], x: c.p3[0], y: c.p3[1] });\n\t\t\t});\n\t\t\tout.push({ type: 'Z' });\n\t\t}\n\t}\n\treturn out;\n}\n\n/**\n * Where point `p` lies relative to the stroke's centre line: the nearest point's contour,\n * its position `t` by length (0–1), the distance, and the side (`left` looking along the\n * path on screen) — what hit-testing and the width tool need.\n */\nexport function nearestStrokePosition(\n\tpath: BezierPath,\n\tp: Point,\n\t/** Only this contour (subpath) of the path. */\n\tonly?: number\n): { contour: number; t: number; distance: number; side: 'left' | 'right'; point: Point; tangent: Vec; length: number } | null {\n\tlet best: ReturnType<typeof nearestStrokePosition> = null;\n\tpathToContours(path).forEach((c, ci) => {\n\t\tif (!c.segments.length || (only !== undefined && ci !== only)) return;\n\t\tconst lengths = c.segments.map((s) => segmentLength(s));\n\t\tconst total = lengths.reduce((a, b) => a + b, 0);\n\t\tif (!(total > 0)) return;\n\t\tlet acc = 0;\n\t\tc.segments.forEach((seg, si) => {\n\t\t\tconst near = segmentNearest(seg, p);\n\t\t\tif (!best || near.distance < best.distance) {\n\t\t\t\tconst s = acc + segmentLength(seg, 0, near.t);\n\t\t\t\tconst tan = segmentTangent(seg, near.t);\n\t\t\t\tconst pt = seg.length === 2 ? lerp(seg[0], seg[1], near.t) : evalSeg(seg, near.t);\n\t\t\t\tconst n = leftNormal([tan[0], tan[1]]);\n\t\t\t\tconst side = (p[0] - pt[0]) * n[0] + (p[1] - pt[1]) * n[1] >= 0 ? 'left' : 'right';\n\t\t\t\tbest = { contour: ci, t: Math.min(Math.max(s / total, 0), 1), distance: near.distance, side, point: pt, tangent: [tan[0], tan[1]], length: total };\n\t\t\t}\n\t\t\tacc += lengths[si];\n\t\t});\n\t});\n\treturn best;\n}\n\nfunction evalSeg(seg: BezierSegment, t: number): Point {\n\t// de Casteljau\n\tlet pts = seg.map((q) => [q[0], q[1]] as Point);\n\twhile (pts.length > 1) pts = pts.slice(1).map((q, i) => lerp(pts[i], q, t));\n\treturn pts[0];\n}\n\n/** The point and unit tangent at position `t` (0–1 by length) of contour `index` of `path`. */\nexport function strokePositionPoint(path: BezierPath, index: number, t: number): { point: Point; tangent: Vec } | null {\n\tconst c = pathToContours(path)[index];\n\tif (!c?.segments.length) return null;\n\tconst lengths = c.segments.map((s) => segmentLength(s));\n\tconst total = lengths.reduce((a, b) => a + b, 0);\n\tlet want = Math.min(Math.max(t, 0), 1) * total;\n\tfor (let i = 0; i < c.segments.length; i++) {\n\t\tconst seg = c.segments[i];\n\t\tif (want <= lengths[i] + 1e-12 || i === c.segments.length - 1) {\n\t\t\t// Bisect the parameter for the remaining length.\n\t\t\tlet lo = 0;\n\t\t\tlet hi = 1;\n\t\t\tconst target = Math.min(want, lengths[i]);\n\t\t\tfor (let k = 0; k < 40; k++) {\n\t\t\t\tconst mid = (lo + hi) / 2;\n\t\t\t\tif (segmentLength(seg, 0, mid) < target) lo = mid;\n\t\t\t\telse hi = mid;\n\t\t\t}\n\t\t\tconst u = (lo + hi) / 2;\n\t\t\tconst tan = segmentTangent(seg, u);\n\t\t\treturn { point: evalSeg(seg, u), tangent: [tan[0], tan[1]] };\n\t\t}\n\t\twant -= lengths[i];\n\t}\n\treturn null;\n}\n","/**\n * Stroke options of vector paths: alignment (centre, inside, outside) and arrowheads at the\n * ends of open paths. Everything here works on a path's Bézier outline in one space (the\n * node's own, or the document's), so the canvases, hit-testing, SVG export and Outline Stroke\n * share it.\n *\n * Ported from ArtCraft (MIT OR Apache-2.0, see THIRD_PARTY_NOTICES.md):\n * - figcraft `crates/pathops/src/lib.rs` — `stroke_outline_of`: an inside stroke is a stroke of\n * twice the width intersected with the fill, an outside one twice the width minus the fill,\n * and only closed shapes have an inside (open paths stroke centred).\n * - vectorcraft `crates/effects/src/stroke/arrow.rs` — arrowhead shapes, sizes and insets (where\n * the stroke stops under each head), `tip` vs `extend` alignment and trimming the stroke by\n * arc length under the head.\n */\nimport type { Point } from '../canvas/types.js';\nimport {\n\tcontoursToPath,\n\tdistanceToBezierPath,\n\tpathToContours,\n\tpointInBezierPath,\n\tsegmentLength,\n\tsegmentTangent,\n\ttrimSegments,\n\ttype BezierContour,\n\ttype BezierPath,\n\ttype BezierSegment\n} from '../canvas/pathops/bezier.js';\nimport { pathBoolean, type PathOperandInput } from '../canvas/pathops/boolean.js';\nimport { outlineStroke } from '../canvas/pathops/stroke.js';\nimport type { VectorArrowhead, VectorStrokeAlign, VectorStyle, VectorWidthPoint, Vec2 } from './types.js';\nimport { nearestStrokePosition, variableStrokeOutline } from './varstroke.js';\nimport { isUniformWidthProfile, sanitizeWidthProfile, widthProfileAt, widthProfileMaxScale } from './width.js';\n\n/** Handle length that makes a cubic approximate a quarter circle. */\nconst KAPPA = 0.5522847498307936;\n/** Where the notch of the (notched) arrow sits, as a fraction of the head's length. */\nconst NOTCH = 0.7;\n\n/** One arrowhead: a filled outline (nonzero) painted with the stroke's paint. */\nexport interface VectorArrowheadShape {\n\tend: 'start' | 'end';\n\tkind: VectorArrowhead;\n\ttip: Vec2;\n\t/** Unit direction the head points in. */\n\tdir: Vec2;\n\t/** Distance from the tip back to where the stroke ends under the head. */\n\tinset: number;\n\tpath: BezierPath;\n}\n\n/** What the stroke of a path draws. */\nexport interface VectorStrokeParts {\n\t/** Where the stroke sits (`center` for open shapes, whatever the style says). */\n\talign: VectorStrokeAlign;\n\t/** The line the stroke follows: the outline, shortened under `tip`-aligned heads. */\n\tline: BezierPath;\n\t/** The stroke width to draw `line` with: twice the style's width for inside / outside (half is clipped away). */\n\tdrawWidth: number;\n\theads: VectorArrowheadShape[];\n}\n\n/** True when the path has subpaths and all of them are closed (only such shapes have an inside). */\nexport function isClosedBezierShape(path: BezierPath): boolean {\n\tconst contours = pathToContours(path).filter((c) => c.segments.length > 0);\n\treturn contours.length > 0 && contours.every((c) => c.closed);\n}\n\n/** The alignment a stroke is drawn with: the style's, or `center` for open shapes. */\nexport function effectiveStrokeAlign(style: Pick<VectorStyle, 'strokeAlign'>, closedShape: boolean): VectorStrokeAlign {\n\tconst a = style.strokeAlign ?? 'center';\n\treturn closedShape ? a : 'center';\n}\n\n/** The style's width profile, sanitised, or null when the stroke is uniform. */\nexport function strokeWidthProfileOf(style: Pick<VectorStyle, 'strokeWidthProfile'>): VectorWidthPoint[] | null {\n\tif (!style.strokeWidthProfile?.length) return null;\n\tconst p = sanitizeWidthProfile(style.strokeWidthProfile);\n\treturn isUniformWidthProfile(p) ? null : p;\n}\n\n/** True when the style asks for more than a plain centred stroke (an alignment, arrowheads or a width profile). */\nexport function hasStrokeExtras(style: VectorStyle): boolean {\n\treturn (style.strokeAlign ?? 'center') !== 'center' || !!style.startArrow || !!style.endArrow || !!strokeWidthProfileOf(style);\n}\n\n/**\n * The area of the stroke along `parts.line` before alignment clipping: SVG's stroke for a\n * uniform width, the variable-width outline (`variableStrokeOutline`) for a profiled one.\n */\nexport function vectorStrokeLineArea(parts: Pick<VectorStrokeParts, 'line' | 'drawWidth'>, style: VectorStyle, tolerance?: number): BezierPath {\n\tconst profile = strokeWidthProfileOf(style);\n\tconst dash = style.strokeDasharray?.length ? { dash: style.strokeDasharray } : {};\n\tconst join = style.strokeLinejoin ?? 'miter';\n\tconst cap = style.strokeLinecap ?? 'butt';\n\tif (profile) return variableStrokeOutline(parts.line, { width: parts.drawWidth, profile, join, cap, ...dash, ...(tolerance ? { tolerance } : {}) });\n\treturn outlineStroke(parts.line, { width: parts.drawWidth, join, cap, ...dash, ...(tolerance ? { tolerance } : {}) });\n}\n\nconst capExtent = (style: VectorStyle, width: number) => (style.strokeLinecap === 'round' || style.strokeLinecap === 'square' ? width / 2 : 0);\n\n/**\n * The weight of a head: the stroke's width just before it times the head's scale (at least\n * 0.25). A head is 4 weights long and wide. On a variable-width stroke the width there is the\n * profile's (the mean of its two sides at that end), floored at the stroke width, so a stroke\n * that tapers to nothing still gets a full-size head and one that swells gets a bigger one.\n */\nexport function arrowheadWeight(style: VectorStyle, end: 'start' | 'end'): number {\n\tconst scale = end === 'start' ? style.startArrowScale : style.endArrowScale;\n\tconst s = typeof scale === 'number' && scale > 0 && Number.isFinite(scale) ? scale : 1;\n\tconst width = style.strokeWidth ?? 1;\n\tconst profile = strokeWidthProfileOf(style);\n\tconst at = profile ? widthProfileAt(profile, end === 'start' ? 0 : 1) : null;\n\tconst here = at ? Math.max(width, (width * (at.left + at.right)) / 2) : width;\n\treturn Math.max(0.25, here * s);\n}\n\n/** Distance from the tip where the stroke ends, for a stroke whose cap reaches `cap` past its end. */\nexport function arrowheadInset(kind: VectorArrowhead, hw: number, cap: number): number {\n\tconst l = 4 * hw;\n\tconst solid = (back: number) => Math.max(back / 2, cap);\n\tswitch (kind) {\n\t\tcase 'triangle':\n\t\tcase 'circle':\n\t\tcase 'square':\n\t\t\treturn solid(l);\n\t\tcase 'arrow':\n\t\t\treturn solid(NOTCH * l);\n\t\tcase 'bar':\n\t\t\treturn solid(0.75 * hw);\n\t\tcase 'open':\n\t\t\t// The inner corner of the chevron: arm / sin(half angle).\n\t\t\treturn Math.max((hw * Math.sqrt(l * l + (l * l) / 4)) / (l / 2), cap);\n\t}\n}\n\nconst v = (x: number, y: number): Vec2 => ({ x, y });\nconst plus = (a: Vec2, b: Vec2, k = 1): Vec2 => ({ x: a.x + b.x * k, y: a.y + b.y * k });\nconst unit = (a: Vec2): Vec2 => {\n\tconst l = Math.hypot(a.x, a.y);\n\treturn l > 0 ? { x: a.x / l, y: a.y / l } : { x: 1, y: 0 };\n};\n\nfunction polygon(pts: Vec2[]): BezierPath {\n\treturn [{ type: 'M', x: pts[0].x, y: pts[0].y }, ...pts.slice(1).map((p) => ({ type: 'L' as const, x: p.x, y: p.y })), { type: 'Z' }];\n}\n\nfunction circle(c: Vec2, r: number): BezierPath {\n\tconst k = r * KAPPA;\n\tconst { x, y } = c;\n\treturn [\n\t\t{ type: 'M', x: x + r, y },\n\t\t{ type: 'C', x1: x + r, y1: y + k, x2: x + k, y2: y + r, x, y: y + r },\n\t\t{ type: 'C', x1: x - k, y1: y + r, x2: x - r, y2: y + k, x: x - r, y },\n\t\t{ type: 'C', x1: x - r, y1: y - k, x2: x - k, y2: y - r, x, y: y - r },\n\t\t{ type: 'C', x1: x + k, y1: y - r, x2: x + r, y2: y - k, x: x + r, y },\n\t\t{ type: 'Z' }\n\t];\n}\n\n/** The outline of a `kind` head of weight `hw` with its tip at `tip`, pointing along unit `dir`. */\nexport function arrowheadPath(kind: VectorArrowhead, tip: Vec2, dir: Vec2, hw: number): BezierPath {\n\tconst n = v(-dir.y, dir.x);\n\tconst l = 4 * hw;\n\tconst half = l / 2;\n\tconst base = plus(tip, dir, -l);\n\tswitch (kind) {\n\t\tcase 'triangle':\n\t\t\treturn polygon([tip, plus(base, n, half), plus(base, n, -half)]);\n\t\tcase 'arrow':\n\t\t\treturn polygon([tip, plus(base, n, half), plus(tip, dir, -NOTCH * l), plus(base, n, -half)]);\n\t\tcase 'open': {\n\t\t\t// Arms `hw` thick from the tip to the base corners, cut square at their ends.\n\t\t\tconst t = hw;\n\t\t\tconst a = plus(base, n, half);\n\t\t\tconst b = plus(base, n, -half);\n\t\t\tconst ua = unit(plus(a, tip, -1));\n\t\t\tconst ub = unit(plus(b, tip, -1));\n\t\t\tconst na = v(-ua.y, ua.x);\n\t\t\tconst nb = v(ub.y, -ub.x);\n\t\t\tconst inner = plus(tip, dir, -(t * Math.hypot(a.x - tip.x, a.y - tip.y)) / half);\n\t\t\treturn polygon([tip, a, plus(a, na, t), inner, plus(b, nb, t), b]);\n\t\t}\n\t\tcase 'circle':\n\t\t\treturn circle(plus(tip, dir, -half), half);\n\t\tcase 'square':\n\t\t\treturn polygon([plus(tip, n, half), plus(base, n, half), plus(base, n, -half), plus(tip, n, -half)]);\n\t\tcase 'bar': {\n\t\t\tconst t = 0.75 * hw;\n\t\t\treturn polygon([plus(tip, n, half), plus(plus(tip, n, half), dir, -t), plus(plus(tip, n, -half), dir, -t), plus(tip, n, -half)]);\n\t\t}\n\t}\n}\n\nconst toVec = (p: Point): Vec2 => ({ x: p[0], y: p[1] });\nconst segLen = (s: BezierSegment) => segmentLength(s);\n\n/** The end point of a contour and the unit direction pointing out of it there. */\nfunction endOf(segs: readonly BezierSegment[], atStart: boolean): { p: Vec2; out: Vec2 } {\n\tconst long = (s: BezierSegment) => segLen(s) > 1e-9;\n\tif (atStart) {\n\t\tconst s = segs.find(long) ?? segs[0];\n\t\tconst t = segmentTangent(s, 0);\n\t\treturn { p: toVec(segs[0][0]), out: v(-t[0], -t[1]) };\n\t}\n\tconst s = [...segs].reverse().find(long) ?? segs[segs.length - 1];\n\tconst t = segmentTangent(s, 1);\n\tconst last = segs[segs.length - 1];\n\treturn { p: toVec(last[last.length - 1]), out: v(t[0], t[1]) };\n}\n\n/** The point `dist` along the contour from its start (or back from its end), if it is that long. */\nfunction pointAlong(segs: readonly BezierSegment[], fromStart: boolean, dist: number): Vec2 | null {\n\tconst order = fromStart ? segs : [...segs].reverse();\n\tlet acc = 0;\n\tfor (const s of order) {\n\t\tconst l = segLen(s);\n\t\tif (acc + l >= dist) {\n\t\t\tconst want = fromStart ? dist - acc : l - (dist - acc);\n\t\t\tconst pts = trimSegments([s], 0, want);\n\t\t\tconst p = pts.length ? pts[0][pts[0].length - 1] : s[0];\n\t\t\treturn toVec(p);\n\t\t}\n\t\tacc += l;\n\t}\n\treturn null;\n}\n\n/**\n * The stroke of `path` as `style` draws it: its alignment, the line it follows (shortened under\n * `tip`-aligned heads) and its arrowheads. Heads go on the start of the first subpath and the\n * end of the last one, when those are open.\n */\nexport function vectorStrokeParts(path: BezierPath, style: VectorStyle): VectorStrokeParts {\n\tconst width = style.strokeWidth ?? 1;\n\tconst contours = pathToContours(path).filter((c) => c.segments.length > 0);\n\tconst closedShape = contours.length > 0 && contours.every((c) => c.closed);\n\tconst align = effectiveStrokeAlign(style, closedShape);\n\tconst drawWidth = align === 'center' ? width : width * 2;\n\tconst heads: VectorArrowheadShape[] = [];\n\tif (!contours.length || (!style.startArrow && !style.endArrow)) return { align, line: path, drawWidth, heads };\n\tconst first = contours[0];\n\tconst last = contours[contours.length - 1];\n\tconst cap = capExtent(style, width);\n\tconst tipMode = style.arrowAlign === 'tip';\n\tconst trims = contours.map(() => [0, 0]);\n\tconst place = (end: 'start' | 'end', contour: BezierContour, ci: number) => {\n\t\tconst kind = end === 'start' ? style.startArrow : style.endArrow;\n\t\tif (!kind || contour.closed) return;\n\t\tconst hw = arrowheadWeight(style, end);\n\t\tconst inset = arrowheadInset(kind, hw, cap);\n\t\tconst atStart = end === 'start';\n\t\tconst { p, out } = endOf(contour.segments, atStart);\n\t\tlet tip: Vec2;\n\t\tlet dir: Vec2;\n\t\tif (tipMode) {\n\t\t\t// Point along the chord from where the stroke now ends to the end point.\n\t\t\tconst q = pointAlong(contour.segments, atStart, inset);\n\t\t\tconst d = q ? v(p.x - q.x, p.y - q.y) : null;\n\t\t\tdir = d && Math.hypot(d.x, d.y) > 1e-9 ? unit(d) : out;\n\t\t\ttip = p;\n\t\t\ttrims[ci][atStart ? 0 : 1] = inset;\n\t\t} else {\n\t\t\ttip = plus(p, out, inset);\n\t\t\tdir = out;\n\t\t}\n\t\theads.push({ end, kind, tip, dir, inset, path: arrowheadPath(kind, tip, dir, hw) });\n\t};\n\tplace('start', first, 0);\n\tplace('end', last, contours.length - 1);\n\tif (!tipMode || !heads.length) return { align, line: path, drawWidth, heads };\n\tconst trimmed: BezierContour[] = contours.map((c, i) => {\n\t\tconst [s0, s1] = trims[i];\n\t\tif (!s0 && !s1) return c;\n\t\tconst lengths = c.segments.map(segLen);\n\t\tconst total = lengths.reduce((a, b) => a + b, 0);\n\t\treturn { closed: false, segments: total - s1 > s0 ? trimSegments(c.segments, s0, total - s1, lengths) : [] };\n\t});\n\treturn { align, line: contoursToPath(trimmed), drawWidth, heads };\n}\n\n/**\n * The area the stroke paints, as one filled path: the outlined stroke (joins, caps and dashes\n * as SVG) clipped by the alignment (against the fill, read with the style's `fillRule`), plus\n * the arrowheads.\n */\nexport function vectorStrokeOutlinePath(path: BezierPath, style: VectorStyle): BezierPath {\n\tconst parts = vectorStrokeParts(path, style);\n\tconst stroke = vectorStrokeLineArea(parts, style);\n\tconst fill: PathOperandInput = { path, fillRule: style.fillRule ?? 'nonzero' };\n\tlet area = stroke;\n\tif (parts.align === 'inside') area = pathBoolean('intersection', [stroke, fill]).path;\n\telse if (parts.align === 'outside') area = pathBoolean('difference', [stroke, fill]).path;\n\tif (!parts.heads.length) return area;\n\treturn pathBoolean('union', [area, ...parts.heads.map((h) => h.path)]).path;\n}\n\n/**\n * Whether point `p` hits the stroke of `path` (`tolerance` added on every side): within half\n * the width of the outline for a centred stroke, within the whole width on the inside or the\n * outside of the fill for an aligned one, or on an arrowhead.\n */\nexport function hitTestVectorStroke(path: BezierPath, p: Vec2, style: VectorStyle, tolerance = 0): boolean {\n\tconst parts = vectorStrokeParts(path, style);\n\tconst point: Point = [p.x, p.y];\n\tconst width = style.strokeWidth ?? 1;\n\tfor (const h of parts.heads) {\n\t\tif (pointInBezierPath(h.path, point) || (tolerance > 0 && distanceToBezierPath(h.path, point) <= tolerance)) return true;\n\t}\n\tif (!parts.line.length) return false;\n\tconst profile = strokeWidthProfileOf(style);\n\tlet d: number;\n\tlet reach = width / 2;\n\tif (profile) {\n\t\t// The side width at the nearest point of the centre line (twice it when aligned).\n\t\tconst near = nearestStrokePosition(parts.line, point);\n\t\tif (!near) return false;\n\t\td = near.distance;\n\t\tconst w = widthProfileAt(profile, near.t);\n\t\treach = (width / 2) * (near.side === 'left' ? w.left : w.right);\n\t\tif (parts.align !== 'center') reach *= 2;\n\t\tconst atEnd = near.t <= 1e-9 || near.t >= 1 - 1e-9;\n\t\tif (atEnd && (style.strokeLinecap === 'round' || style.strokeLinecap === 'square') && d > reach) {\n\t\t\t// Past an open end the cap reaches as far as the width there.\n\t\t\treach = Math.max(reach, ((width / 2) * (w.left + w.right)) / 2);\n\t\t}\n\t} else {\n\t\td = distanceToBezierPath(parts.line, point);\n\t\tif (parts.align !== 'center') reach = width;\n\t}\n\tif (parts.align === 'center') return d <= reach + tolerance;\n\tif (d > reach + tolerance) return false;\n\tif (d <= tolerance) return true;\n\tconst inside = pointInBezierPath(path, point, style.fillRule ?? 'nonzero');\n\treturn parts.align === 'inside' ? inside : !inside;\n}\n\n/** How far the stroke can reach past the outline (for padding bounds and masks). */\nexport function vectorStrokeReach(style: VectorStyle): number {\n\tconst width = (style.strokeWidth ?? 1) * widthProfileMaxScale(strokeWidthProfileOf(style));\n\tconst align = style.strokeAlign ?? 'center';\n\tlet reach = align === 'center' ? width / 2 : align === 'outside' ? width : 0;\n\tif (style.strokeLinejoin !== 'round' && style.strokeLinejoin !== 'bevel') reach *= 4;\n\tfor (const end of ['start', 'end'] as const) {\n\t\tif (end === 'start' ? style.startArrow : style.endArrow) reach = Math.max(reach, 8 * arrowheadWeight(style, end) + width);\n\t}\n\treturn reach;\n}\n","/**\n * Fill and stroke stacks: several paints per path, each with its own opacity, blend mode and\n * visibility, and each stroke with its own width, alignment, dashes, arrowheads and profile.\n *\n * The stacks live in `fills` / `strokes`, bottom to top; fills draw under strokes. The single\n * `fill` / `stroke` fields (and the stroke settings) stay as shorthands that mirror the top layer\n * of each stack, so everything written against one fill and one stroke — booleans, blends, the\n * gradient tool, agent commands, old documents — keeps working:\n *\n * - A node without `fills` has the one-layer stack its `fill` says (none without a paint); the\n * same for strokes. Stacks of one plain layer are stored that way, so old documents and simple\n * nodes look exactly as before.\n * - `normalizeVectorPaintStacks` reconciles the two forms. Loading prefers the stacks (the\n * shorthand is re-derived); editing prefers the shorthand: a node whose `fill` no longer matches\n * its top fill was written by shorthand code, so the top layer takes the new paint (`null`\n * clears the stack). The controller runs it after every change.\n *\n * Paint layers are drawn, hit-tested and exported through `vectorPaintLayerNodes`: one plain path\n * node per layer (the node with only that fill, or only that stroke and its settings), so the\n * existing paint, stroke-part and gradient code serves each layer unchanged.\n *\n * The data model follows figcraft `crates/color/src/lib.rs` (`Paint { kind, opacity, visible,\n * blend }` in a list per node) and vectorcraft `crates/doc/src/appearance.rs` (`FillLayer` /\n * `StrokeLayer`, each stroke with its own settings). Ported from ArtCraft (MIT OR Apache-2.0,\n * © ArtCraft Team and contributors; see THIRD_PARTY_NOTICES.md).\n */\nimport { pointInBezierPath, distanceToBezierPath, type BezierPath } from '../canvas/pathops/bezier.js';\nimport { isVectorGradient, sanitizeVectorGradient } from './gradient.js';\nimport { hitTestVectorStroke, vectorStrokeReach } from './stroke.js';\nimport { sanitizeWidthProfile } from './width.js';\nimport {\n\tVECTOR_ARROWHEADS,\n\tVECTOR_BLEND_MODES,\n\ttype VectorArrowhead,\n\ttype VectorBlendMode,\n\ttype VectorPaint,\n\ttype VectorPaintLayer,\n\ttype VectorPathNode,\n\ttype VectorStrokeLayer,\n\ttype VectorStrokeSettings,\n\ttype VectorStyle,\n\ttype Vec2\n} from './types.js';\n\n/** The stroke settings each stroke layer has of its own, in `VectorStyle` field names. */\nexport const VECTOR_STROKE_SETTING_KEYS: readonly (keyof VectorStrokeSettings)[] = [\n\t'strokeWidth',\n\t'strokeLinecap',\n\t'strokeLinejoin',\n\t'strokeDasharray',\n\t'strokeAlign',\n\t'startArrow',\n\t'endArrow',\n\t'arrowAlign',\n\t'startArrowScale',\n\t'endArrowScale',\n\t'strokeWidthProfile'\n];\n\nexport const VECTOR_BLEND_MODE_LABELS: Readonly<Record<VectorBlendMode, string>> = {\n\tnormal: 'Normal',\n\tdarken: 'Darken',\n\tmultiply: 'Multiply',\n\t'color-burn': 'Color Burn',\n\tlighten: 'Lighten',\n\tscreen: 'Screen',\n\t'color-dodge': 'Color Dodge',\n\t'linear-dodge': 'Linear Dodge (Add)',\n\toverlay: 'Overlay',\n\t'soft-light': 'Soft Light',\n\t'hard-light': 'Hard Light',\n\tdifference: 'Difference',\n\texclusion: 'Exclusion',\n\thue: 'Hue',\n\tsaturation: 'Saturation',\n\tcolor: 'Color',\n\tluminosity: 'Luminosity'\n};\n\nexport function isVectorBlendMode(value: unknown): value is VectorBlendMode {\n\treturn typeof value === 'string' && (VECTOR_BLEND_MODES as readonly string[]).includes(value);\n}\n\n/** A blend mode as a CSS `mix-blend-mode` value, or undefined for `normal` (nothing to write). */\nexport function vectorBlendModeCss(mode: VectorBlendMode | null | undefined): string | undefined {\n\tif (!mode || mode === 'normal' || !isVectorBlendMode(mode)) return undefined;\n\treturn mode === 'linear-dodge' ? 'plus-lighter' : mode;\n}\n\n/** A CSS `mix-blend-mode` value back to a blend mode (`plus-lighter` is `linear-dodge`), or null when SVG offers it but we don't. */\nexport function vectorBlendModeFromCss(value: string | null | undefined): VectorBlendMode | null {\n\tconst v = (value ?? '').trim().toLowerCase();\n\tif (v === 'plus-lighter') return 'linear-dodge';\n\treturn isVectorBlendMode(v) ? v : null;\n}\n\n/** True when the paint draws something (not `null`, `'none'`, `'transparent'` or empty). */\nconst draws = (paint: VectorPaint | undefined): boolean => {\n\tif (paint === undefined || paint === null) return false;\n\tif (typeof paint === 'string') {\n\t\tconst p = paint.trim().toLowerCase();\n\t\treturn p !== '' && p !== 'none' && p !== 'transparent';\n\t}\n\treturn true;\n};\n\n/** A layer with full opacity, `normal` blending, visible and (strokes) a plain paint: what the shorthand alone can say. */\nexport function isPlainVectorPaintLayer(layer: VectorPaintLayer | VectorStrokeLayer): boolean {\n\treturn (\n\t\t(layer.opacity ?? 1) >= 1 &&\n\t\t(layer.blendMode ?? 'normal') === 'normal' &&\n\t\tlayer.visible !== false &&\n\t\t((layer as VectorStrokeLayer).kind ?? 'paint') === 'paint'\n\t);\n}\n\n/** Whether a layer is drawn: visible, a plain paint (strokes), a paint that draws something, above zero opacity. */\nexport function isDrawnVectorPaintLayer(layer: VectorPaintLayer | VectorStrokeLayer): boolean {\n\treturn layer.visible !== false && ((layer as VectorStrokeLayer).kind ?? 'paint') === 'paint' && draws(layer.paint) && (layer.opacity ?? 1) > 0;\n}\n\n/** The fill stack of a path (or style), bottom to top: `fills`, or the one layer `fill` makes. */\nexport function vectorFills(style: VectorStyle): VectorPaintLayer[] {\n\tif (Array.isArray(style.fills)) return style.fills;\n\treturn draws(style.fill) ? [{ paint: style.fill! }] : [];\n}\n\n/** The stroke settings a style gives its shorthand stroke (only those set). */\nexport function vectorStrokeSettings(style: VectorStyle): VectorStrokeSettings {\n\tconst out: VectorStrokeSettings = {};\n\tfor (const key of VECTOR_STROKE_SETTING_KEYS) {\n\t\tconst v = style[key];\n\t\tif (v !== undefined && v !== null) (out as Record<string, unknown>)[key] = v;\n\t}\n\treturn out;\n}\n\n/** The stroke stack of a path (or style), bottom to top: `strokes`, or the one layer `stroke` and the stroke settings make. */\nexport function vectorStrokes(style: VectorStyle): VectorStrokeLayer[] {\n\tif (Array.isArray(style.strokes)) return style.strokes;\n\treturn draws(style.stroke) ? [{ paint: style.stroke!, ...vectorStrokeSettings(style) }] : [];\n}\n\n/** Whether a style stores a stack (more than its shorthand can say). */\nexport function hasVectorPaintStacks(style: VectorStyle): boolean {\n\treturn Array.isArray(style.fills) || Array.isArray(style.strokes);\n}\n\n/** The node with `fills` as its fill stack, stored canonically (see the module comment). */\nexport function withVectorFills<T extends VectorStyle>(node: T, fills: readonly VectorPaintLayer[]): T {\n\tconst next = { ...node };\n\tif (fills.length === 0 || (fills.length === 1 && isPlainVectorPaintLayer(fills[0]))) {\n\t\tdelete next.fills;\n\t\tnext.fill = fills[0]?.paint ?? null;\n\t\treturn next;\n\t}\n\tnext.fills = fills.map((l) => ({ ...l }));\n\tnext.fill = fills[fills.length - 1].paint;\n\treturn next;\n}\n\n/** The node with `strokes` as its stroke stack, stored canonically; the shorthand mirrors the top layer. */\nexport function withVectorStrokes<T extends VectorStyle>(node: T, strokes: readonly VectorStrokeLayer[]): T {\n\tconst next = { ...node };\n\tif (strokes.length === 0) {\n\t\t// The settings stay, for a stroke added later through the shorthand.\n\t\tdelete next.strokes;\n\t\tnext.stroke = null;\n\t\treturn next;\n\t}\n\tconst top = strokes[strokes.length - 1];\n\tfor (const key of VECTOR_STROKE_SETTING_KEYS) delete next[key];\n\tObject.assign(next, vectorStrokeSettings(top as VectorStyle));\n\tnext.stroke = top.paint;\n\tif (strokes.length === 1 && isPlainVectorPaintLayer(top)) delete next.strokes;\n\telse next.strokes = strokes.map((l) => ({ ...l }));\n\treturn next;\n}\n\nconst json = (v: unknown) => JSON.stringify(v ?? null);\n\n/** The stroke fields of `node` that differ from what its top stroke layer says. */\nfunction strokeShorthandDiff(node: VectorStyle, top: VectorStrokeLayer | undefined): (keyof VectorStrokeSettings | 'stroke')[] {\n\tconst out: (keyof VectorStrokeSettings | 'stroke')[] = [];\n\tif (json(node.stroke) !== json(top?.paint)) out.push('stroke');\n\tfor (const key of VECTOR_STROKE_SETTING_KEYS) if (json(node[key]) !== json(top?.[key])) out.push(key);\n\treturn out;\n}\n\nconst checked = new WeakSet<object>();\n\n/**\n * A node with its stacks and shorthands reconciled and stored canonically (the same object when\n * they already are). `prefer: 'stack'` (loading) re-derives the shorthand from the stacks;\n * `'shorthand'` (after an edit, the default) reads a shorthand that disagrees with its stack's\n * top layer as an edit of that layer: a paint repaints it, a stroke setting changes it, `null`\n * clears the stack.\n */\nexport function normalizeVectorPaintStacks<T extends VectorStyle>(node: T, prefer: 'stack' | 'shorthand' = 'shorthand'): T {\n\tif (!hasVectorPaintStacks(node)) {\n\t\tif (!('fills' in node) && !('strokes' in node)) return node;\n\t\t// `fills: null` / `strokes: null`: no stack.\n\t\tconst next = { ...node };\n\t\tdelete next.fills;\n\t\tdelete next.strokes;\n\t\treturn next;\n\t}\n\tif (checked.has(node)) return node;\n\tlet next: T = node;\n\tif (Array.isArray(node.fills)) {\n\t\tlet fills: VectorPaintLayer[] = node.fills;\n\t\tconst top = fills[fills.length - 1];\n\t\tif (prefer === 'shorthand' && json(node.fill) !== json(top?.paint)) {\n\t\t\tif (!draws(node.fill)) fills = [];\n\t\t\telse fills = top ? [...fills.slice(0, -1), { ...top, paint: node.fill! }] : [{ paint: node.fill! }];\n\t\t}\n\t\tnext = withVectorFills(next, fills);\n\t}\n\tif (Array.isArray(node.strokes)) {\n\t\tlet strokes: VectorStrokeLayer[] = node.strokes;\n\t\tconst top = strokes[strokes.length - 1];\n\t\tconst diff = prefer === 'shorthand' ? strokeShorthandDiff(node, top) : [];\n\t\tif (diff.length) {\n\t\t\tif (diff.includes('stroke') && !draws(node.stroke)) strokes = [];\n\t\t\telse {\n\t\t\t\tconst layer: VectorStrokeLayer = top ? { ...top } : { paint: node.stroke ?? null };\n\t\t\t\tfor (const key of diff) {\n\t\t\t\t\tif (key === 'stroke') layer.paint = node.stroke ?? null;\n\t\t\t\t\telse if (node[key] === undefined || node[key] === null) delete layer[key];\n\t\t\t\t\telse (layer as unknown as Record<string, unknown>)[key] = node[key];\n\t\t\t\t}\n\t\t\t\tstrokes = top ? [...strokes.slice(0, -1), layer] : [layer];\n\t\t\t}\n\t\t}\n\t\tnext = withVectorStrokes(next, strokes);\n\t}\n\tconst keys = ['fill', 'fills', 'stroke', 'strokes', ...VECTOR_STROKE_SETTING_KEYS] as const;\n\tconst same = keys.every((k) => k in next === k in node && json(next[k]) === json(node[k]));\n\tconst out = same ? node : next;\n\tchecked.add(out);\n\treturn out;\n}\n\n// ---------------------------------------------------------------------------\n// Sanitizing\n// ---------------------------------------------------------------------------\n\nfunction sanitizePaint(value: unknown): VectorPaint {\n\tif (value === null || value === undefined) return null;\n\tif (typeof value === 'string') return value;\n\treturn sanitizeVectorGradient(value);\n}\n\nfunction sanitizeLayerBase(raw: Record<string, unknown>): VectorPaintLayer {\n\tconst out: VectorPaintLayer = { paint: sanitizePaint(raw.paint) };\n\tif (typeof raw.opacity === 'number' && Number.isFinite(raw.opacity) && raw.opacity < 1) out.opacity = Math.max(0, raw.opacity);\n\tif (isVectorBlendMode(raw.blendMode) && raw.blendMode !== 'normal') out.blendMode = raw.blendMode;\n\tif (raw.visible === false) out.visible = false;\n\treturn out;\n}\n\n/** Reads a fill stack from untrusted data (JSON, agent input, SVG): malformed layers are dropped. */\nexport function sanitizeVectorFills(value: unknown): VectorPaintLayer[] {\n\tif (!Array.isArray(value)) return [];\n\treturn value.filter((l): l is Record<string, unknown> => !!l && typeof l === 'object').map(sanitizeLayerBase);\n}\n\nconst ARROW_ALIGNS = ['extend', 'tip'];\n\n/** Stroke settings from untrusted data: wrong types and out-of-range values are dropped. */\nexport function sanitizeVectorStrokeSettings(raw: Record<string, unknown>): VectorStrokeSettings {\n\tconst out: VectorStrokeSettings = {};\n\tconst num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : undefined);\n\tconst width = num(raw.strokeWidth);\n\tif (width !== undefined && width >= 0) out.strokeWidth = width;\n\tif (raw.strokeLinecap === 'butt' || raw.strokeLinecap === 'round' || raw.strokeLinecap === 'square') out.strokeLinecap = raw.strokeLinecap;\n\tif (raw.strokeLinejoin === 'miter' || raw.strokeLinejoin === 'round' || raw.strokeLinejoin === 'bevel') out.strokeLinejoin = raw.strokeLinejoin;\n\tif (Array.isArray(raw.strokeDasharray)) {\n\t\tconst dash = raw.strokeDasharray.filter((n): n is number => typeof n === 'number' && Number.isFinite(n) && n >= 0);\n\t\tif (dash.length && dash.some((n) => n > 0)) out.strokeDasharray = dash;\n\t}\n\tif (raw.strokeAlign === 'center' || raw.strokeAlign === 'inside' || raw.strokeAlign === 'outside') out.strokeAlign = raw.strokeAlign;\n\tfor (const key of ['startArrow', 'endArrow'] as const) if (VECTOR_ARROWHEADS.includes(raw[key] as VectorArrowhead)) out[key] = raw[key] as VectorArrowhead;\n\tif (ARROW_ALIGNS.includes(raw.arrowAlign as string)) out.arrowAlign = raw.arrowAlign as 'extend' | 'tip';\n\tfor (const key of ['startArrowScale', 'endArrowScale'] as const) {\n\t\tconst n = num(raw[key]);\n\t\tif (n !== undefined && n > 0) out[key] = n;\n\t}\n\tif (Array.isArray(raw.strokeWidthProfile)) {\n\t\tconst p = sanitizeWidthProfile(raw.strokeWidthProfile as never);\n\t\tif (p.length) out.strokeWidthProfile = p;\n\t}\n\treturn out;\n}\n\n/**\n * Reads a stroke stack from untrusted data. Layers of a kind this version does not know are kept\n * as they are (a later version's brushstroke, say), so a round trip does not lose them.\n */\nexport function sanitizeVectorStrokes(value: unknown): VectorStrokeLayer[] {\n\tif (!Array.isArray(value)) return [];\n\treturn value\n\t\t.filter((l): l is Record<string, unknown> => !!l && typeof l === 'object')\n\t\t.map((raw) => {\n\t\t\tif (raw.kind !== undefined && raw.kind !== 'paint') return { ...(raw as unknown as VectorStrokeLayer) };\n\t\t\treturn { ...sanitizeLayerBase(raw), ...sanitizeVectorStrokeSettings(raw) };\n\t\t});\n}\n\n// ---------------------------------------------------------------------------\n// Layer nodes: one plain path per layer\n// ---------------------------------------------------------------------------\n\n/** One layer of a path's paint as a plain path node (see `vectorPaintLayerNodes`). */\nexport interface VectorPaintLayerNode {\n\tkind: 'fill' | 'stroke';\n\t/** Index in its stack, bottom to top. */\n\tindex: number;\n\tlayer: VectorPaintLayer | VectorStrokeLayer;\n\t/** The path with only this fill, or only this stroke and its settings (no stacks). */\n\tnode: VectorPathNode;\n\t/** Visible, a plain paint, painting something, above zero opacity. */\n\tdrawn: boolean;\n}\n\nconst layerNodeCache = new WeakMap<VectorPathNode, VectorPaintLayerNode[]>();\n\n/**\n * Every fill then every stroke of a path, bottom to top, each as the path painted by that layer\n * alone. Cached per node object (and the layer nodes are the same objects while it is), so the\n * paint and stroke-part caches keyed by node keep working per layer.\n */\nexport function vectorPaintLayerNodes(node: VectorPathNode): VectorPaintLayerNode[] {\n\tconst hit = layerNodeCache.get(node);\n\tif (hit) return hit;\n\tconst { fills: _f, strokes: _s, ...base } = node;\n\tconst plain = { ...base } as VectorPathNode;\n\tfor (const key of VECTOR_STROKE_SETTING_KEYS) delete plain[key];\n\tconst out: VectorPaintLayerNode[] = [];\n\tvectorFills(node).forEach((layer, index) => {\n\t\tout.push({ kind: 'fill', index, layer, node: { ...plain, fill: layer.paint, stroke: null }, drawn: isDrawnVectorPaintLayer(layer) });\n\t});\n\tvectorStrokes(node).forEach((layer, index) => {\n\t\tconst settings = (layer.kind ?? 'paint') === 'paint' ? vectorStrokeSettings(layer as VectorStyle) : {};\n\t\tout.push({ kind: 'stroke', index, layer, node: { ...plain, fill: null, ...settings, stroke: layer.paint }, drawn: isDrawnVectorPaintLayer(layer) });\n\t});\n\tlayerNodeCache.set(node, out);\n\treturn out;\n}\n\n/** Whether a path draws through its stacks rather than one fill and one stroke (several layers, or one with its own opacity, blend or visibility). */\nexport function needsVectorPaintLayers(node: VectorPathNode): boolean {\n\tif (!hasVectorPaintStacks(node)) return false;\n\tconst fills = vectorFills(node);\n\tconst strokes = vectorStrokes(node);\n\treturn fills.length > 1 || strokes.length > 1 || fills.some((l) => !isPlainVectorPaintLayer(l)) || strokes.some((l) => !isPlainVectorPaintLayer(l));\n}\n\n/** How far the drawn strokes of a path reach past its outline (the widest layer's reach; 0 without strokes). */\nexport function vectorStrokeStackReach(node: VectorPathNode): number {\n\tlet reach = 0;\n\tfor (const l of vectorPaintLayerNodes(node)) if (l.kind === 'stroke' && l.drawn) reach = Math.max(reach, vectorStrokeReach(l.node));\n\treturn reach;\n}\n\n/** The layer a point hits (see `hitTestVectorPaintLayer`). */\nexport interface VectorPaintLayerHit {\n\tkind: 'fill' | 'stroke';\n\tindex: number;\n}\n\n/**\n * The topmost drawn layer of a path that `p` hits, or null: strokes top to bottom (their\n * alignment, arrowheads and profiles respected, `tolerance` added), then fills. `path` is the\n * node's outline in the same space as `p` (`vectorPathWorldBezier`).\n */\nexport function hitTestVectorPaintLayer(node: VectorPathNode, path: BezierPath, p: Vec2, tolerance = 0): VectorPaintLayerHit | null {\n\tif (!path.length) return null;\n\tconst layers = vectorPaintLayerNodes(node);\n\tfor (let i = layers.length - 1; i >= 0; i--) {\n\t\tconst l = layers[i];\n\t\tif (!l.drawn) continue;\n\t\tif (l.kind === 'stroke') {\n\t\t\tif ((l.node.strokeWidth ?? 1) > 0 && hitTestVectorStroke(path, p, l.node, tolerance)) return { kind: 'stroke', index: l.index };\n\t\t} else if (pointInBezierPath(path, [p.x, p.y], node.fillRule ?? 'nonzero')) return { kind: 'fill', index: l.index };\n\t}\n\treturn null;\n}\n\n/**\n * Whether `p` hits a path as drawn by its stacks: on a drawn layer, or, when it draws no stroke,\n * within `tolerance` of its outline (so unpainted paths stay pickable).\n */\nexport function hitTestVectorPaintStack(node: VectorPathNode, path: BezierPath, p: Vec2, tolerance = 0): boolean {\n\tif (hitTestVectorPaintLayer(node, path, p, tolerance)) return true;\n\tif (vectorPaintLayerNodes(node).some((l) => l.kind === 'stroke' && l.drawn)) return false;\n\treturn distanceToBezierPath(path, [p.x, p.y]) <= tolerance;\n}\n\n/** Whether a fill or stroke stack holds a gradient anywhere (for transforms that move gradients). */\nexport function vectorStacksHaveGradient(style: VectorStyle): boolean {\n\treturn [...(style.fills ?? []), ...(style.strokes ?? [])].some((l) => isVectorGradient(l.paint));\n}\n\n/** Defaults of a new layer added to a stack (a stroke takes the settings of the stack's top stroke). */\nexport function newVectorStrokeLayer(node: VectorStyle, patch: Partial<VectorStrokeLayer> = {}): VectorStrokeLayer {\n\tconst top = vectorStrokes(node).at(-1);\n\tconst settings = top && (top.kind ?? 'paint') === 'paint' ? vectorStrokeSettings(top as VectorStyle) : { strokeWidth: node.strokeWidth ?? 1 };\n\treturn { paint: '#000000', ...settings, ...patch };\n}\n\n/**\n * The paint the gradient tool and editor work on: layer `layer` of the fill or stroke stack, or\n * (null, or an index the stack doesn't have) the shorthand, which is the top layer.\n */\nexport function vectorTargetPaint(style: VectorStyle, target: 'fill' | 'stroke', layer: number | null = null): VectorPaint | undefined {\n\tif (layer === null) return style[target];\n\tconst stack = target === 'fill' ? vectorFills(style) : vectorStrokes(style);\n\treturn stack[layer] ? stack[layer].paint : style[target];\n}\n\n/** The node with `paint` in the place `vectorTargetPaint` reads (stored canonically). */\nexport function withVectorTargetPaint<T extends VectorStyle>(node: T, target: 'fill' | 'stroke', layer: number | null, paint: VectorPaint): T {\n\tconst stack = target === 'fill' ? vectorFills(node) : vectorStrokes(node);\n\tif (layer === null || !stack[layer]) {\n\t\tif (!stack.length) return { ...node, [target]: paint };\n\t\tlayer = stack.length - 1;\n\t}\n\tconst next = stack.map((l, i) => (i === layer ? { ...l, paint } : l));\n\treturn target === 'fill' ? withVectorFills(node, next) : withVectorStrokes(node, next as VectorStrokeLayer[]);\n}\n","/**\n * Non-affine maps of paths, so shapes stay Bézier paths through Free Distort (a projective map)\n * and envelope warps.\n *\n * - `mapVectorPoints` sends every anchor and handle through the map and keeps the anchors as they\n * are. Under a projective map straight segments stay exactly straight; a curve keeps its exact\n * end tangents and approximates the (rational) image between.\n * - `mapVectorSubpaths` follows any smooth map: each segment is halved until its mapped control\n * points follow the mapped curve within a tolerance, so the result gains anchors where the map\n * bends it. Runs of pieces are then refitted with fewer cubics (`fitCubicRun`) where that stays\n * within the tolerance.\n *\n * Ported from ArtCraft (MIT OR Apache-2.0, © ArtCraft Team and contributors; see\n * THIRD_PARTY_NOTICES.md): photocraft `crates/vector/src/map.rs` (`map_points`, `map_path`,\n * `map_subpath`, `map_segment`, `split_mapped`, `halves`, `off_line`).\n */\nimport { fitCubicRun, type CubicSegment } from '../canvas/curveFit.js';\nimport { segmentNearest, type BezierPath, type BezierPathInput } from '../canvas/pathops/bezier.js';\nimport { bezierToSubpaths, subpathsToBezier } from './geometry.js';\nimport type { Vec2, VectorAnchor, VectorSubpath } from './types.js';\n\n/** A map of the plane (document or node space). */\nexport type VectorPointMap = (p: Vec2) => Vec2;\n\ntype Cubic = [Vec2, Vec2, Vec2, Vec2];\n\n/** Pieces a path may be split into in total: bounds the work on hostile input. */\nconst MAX_PIECES = 1 << 20;\n/** Deepest split of one segment (2^6 = 64 pieces). */\nconst MAX_DEPTH = 6;\nconst PROBES = [0.25, 0.5, 0.75];\n\nconst lerp = (a: Vec2, b: Vec2, t: number): Vec2 => ({ x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t });\nconst dist = (a: Vec2, b: Vec2) => Math.hypot(a.x - b.x, a.y - b.y);\nconst same = (a: Vec2, b: Vec2) => Math.abs(a.x - b.x) < 1e-9 && Math.abs(a.y - b.y) < 1e-9;\n\nfunction evalCubic(s: Cubic, t: number): Vec2 {\n\tconst ab = lerp(s[0], s[1], t);\n\tconst bc = lerp(s[1], s[2], t);\n\tconst cd = lerp(s[2], s[3], t);\n\treturn lerp(lerp(ab, bc, t), lerp(bc, cd, t), t);\n}\n\n/** De Casteljau split at t = ½. */\nfunction halves(s: Cubic): [Cubic, Cubic] {\n\tconst ab = lerp(s[0], s[1], 0.5);\n\tconst bc = lerp(s[1], s[2], 0.5);\n\tconst cd = lerp(s[2], s[3], 0.5);\n\tconst abc = lerp(ab, bc, 0.5);\n\tconst bcd = lerp(bc, cd, 0.5);\n\tconst m = lerp(abc, bcd, 0.5);\n\treturn [\n\t\t[s[0], ab, abc, m],\n\t\t[m, bcd, cd, s[3]]\n\t];\n}\n\n/** Distance from `p` to the line through `a` and `b` (to `a` when they coincide). */\nfunction offLine(p: Vec2, a: Vec2, b: Vec2): number {\n\tconst l = dist(a, b);\n\treturn l < 1e-12 ? dist(p, a) : Math.abs((b.x - a.x) * (a.y - p.y) - (a.x - p.x) * (b.y - a.y)) / l;\n}\n\nconst mapAnchorPoints = (a: VectorAnchor, f: VectorPointMap): VectorAnchor => {\n\tconst p = f(a);\n\treturn {\n\t\tx: p.x,\n\t\ty: p.y,\n\t\t...(a.in ? { in: f(a.in) } : {}),\n\t\t...(a.out ? { out: f(a.out) } : {}),\n\t\t...(a.type && a.type !== 'corner' ? { type: a.type } : {}),\n\t\t...(a.corner ? { corner: { ...a.corner } } : {})\n\t};\n};\n\n/** Every anchor and handle of `subpaths` through `f` (no subdivision). */\nexport function mapVectorPoints(subpaths: readonly VectorSubpath[], f: VectorPointMap): VectorSubpath[] {\n\treturn subpaths.map((sp) => ({ closed: sp.closed, anchors: sp.anchors.map((a) => mapAnchorPoints(a, f)) }));\n}\n\nfunction splitMapped(seg: Cubic, f: VectorPointMap, tol: number, depth: number, out: Cubic[]) {\n\tconst mapped = seg.map(f) as Cubic;\n\tconst fits = PROBES.every((t) => dist(f(evalCubic(seg, t)), evalCubic(mapped, t)) <= tol);\n\tif (fits || depth === 0) {\n\t\tout.push(mapped);\n\t\treturn;\n\t}\n\tconst [a, b] = halves(seg);\n\tsplitMapped(a, f, tol, depth - 1, out);\n\tsplitMapped(b, f, tol, depth - 1, out);\n}\n\nconst toPoint = (p: Vec2): [number, number] => [p.x, p.y];\nconst toVec = (p: readonly number[]): Vec2 => ({ x: p[0], y: p[1] });\n\n/**\n * The image of `seg` through `f` as fewer cubics than `pieces` when they stay within `tol` of it\n * (fitted to samples of the mapped curve with the pieces' end tangents), else `pieces`.\n */\nfunction refit(seg: Cubic, pieces: Cubic[], f: VectorPointMap, tol: number): Cubic[] {\n\tif (pieces.length < 3) return pieces;\n\tconst n = pieces.length * 4;\n\tconst samples: [number, number][] = [];\n\tfor (let i = 0; i <= n; i++) samples.push(toPoint(f(evalCubic(seg, i / n))));\n\tconst first = pieces[0];\n\tconst last = pieces[pieces.length - 1];\n\tconst t0 = !same(first[1], first[0]) ? first[1] : first[2];\n\tconst t1 = !same(last[2], last[3]) ? last[2] : last[1];\n\tconst fitted: CubicSegment[] = fitCubicRun(samples, tol / 2, [t0.x - first[0].x, t0.y - first[0].y], [last[3].x - t1.x, last[3].y - t1.y]);\n\tif (!fitted.length || fitted.length >= pieces.length) return pieces;\n\t// Check between the fitted samples too.\n\tconst chain = fitted.map((c) => [c.p0, c.p1, c.p2, c.p3]);\n\tfor (let i = 0; i < n; i++) {\n\t\tconst q = toPoint(f(evalCubic(seg, (i + 0.5) / n)));\n\t\tlet best = Infinity;\n\t\tfor (const c of chain) best = Math.min(best, segmentNearest(c, q).distance);\n\t\tif (best > tol) return pieces;\n\t}\n\treturn fitted.map((c) => [toVec(c.p0), toVec(c.p1), toVec(c.p2), toVec(c.p3)]);\n}\n\nfunction mapSegment(seg: Cubic, f: VectorPointMap, tol: number, depth: number, fit: boolean): Cubic[] {\n\t// A straight segment whose image is straight stays one.\n\tif (same(seg[1], seg[0]) && same(seg[2], seg[3])) {\n\t\tconst a = f(seg[0]);\n\t\tconst b = f(seg[3]);\n\t\tif (PROBES.every((t) => offLine(f(lerp(seg[0], seg[3], t)), a, b) <= tol)) return [[a, a, b, b]];\n\t\t// Bent by the map: the same line as an evenly parametrised cubic, then split.\n\t\tconst line: Cubic = [seg[0], lerp(seg[0], seg[3], 1 / 3), lerp(seg[0], seg[3], 2 / 3), seg[3]];\n\t\tconst out: Cubic[] = [];\n\t\tsplitMapped(line, f, tol, depth, out);\n\t\treturn fit ? refit(line, out, f, tol) : out;\n\t}\n\tconst out: Cubic[] = [];\n\tsplitMapped(seg, f, tol, depth, out);\n\treturn fit ? refit(seg, out, f, tol) : out;\n}\n\n/** Makes a smooth anchor's handles collinear again (a curved map can kink them slightly), keeping their lengths. */\nfunction realign(a: VectorAnchor): VectorAnchor {\n\tif (!a.in || !a.out || same(a.in, a) || same(a.out, a)) return a;\n\tconst li = dist(a.in, a);\n\tconst lo = dist(a.out, a);\n\tconst dx = (a.x - a.in.x) / li + (a.out.x - a.x) / lo;\n\tconst dy = (a.y - a.in.y) / li + (a.out.y - a.y) / lo;\n\tconst l = Math.hypot(dx, dy);\n\tif (l < 1e-12) return a;\n\tconst u = { x: dx / l, y: dy / l };\n\tconst type = a.type === 'symmetric' && Math.abs(li - lo) > 1e-6 * Math.max(li, lo) ? 'smooth' : a.type;\n\treturn { ...a, in: { x: a.x - u.x * li, y: a.y - u.y * li }, out: { x: a.x + u.x * lo, y: a.y + u.y * lo }, ...(type ? { type } : {}) };\n}\n\nconst segmentOf = (sp: VectorSubpath, i: number): Cubic => {\n\tconst a = sp.anchors[i];\n\tconst b = sp.anchors[(i + 1) % sp.anchors.length];\n\treturn [{ x: a.x, y: a.y }, a.out ?? { x: a.x, y: a.y }, b.in ?? { x: b.x, y: b.y }, { x: b.x, y: b.y }];\n};\n\nfunction mapSubpath(sp: VectorSubpath, f: VectorPointMap, tol: number, depth: number, fit: boolean): VectorSubpath {\n\tconst n = sp.anchors.length;\n\tconst count = n < 2 ? 0 : sp.closed ? n : n - 1;\n\tif (!count) return mapVectorPoints([sp], f)[0];\n\tconst pieces: Cubic[][] = [];\n\tfor (let i = 0; i < count; i++) pieces.push(mapSegment(segmentOf(sp, i), f, tol, depth, fit));\n\tconst anchors: VectorAnchor[] = [];\n\tconst put = (a: VectorAnchor) => {\n\t\tif (a.in && same(a.in, a)) delete a.in;\n\t\tif (a.out && same(a.out, a)) delete a.out;\n\t\tanchors.push(a.type === 'smooth' || a.type === 'symmetric' ? realign(a) : a);\n\t};\n\tsp.anchors.forEach((k, i) => {\n\t\tconst incoming = i > 0 ? pieces[i - 1] : sp.closed ? pieces[n - 1] : undefined;\n\t\tconst outgoing = pieces[i];\n\t\tconst p = f(k);\n\t\tconst a: VectorAnchor = { x: p.x, y: p.y };\n\t\tconst inCtrl = incoming ? incoming[incoming.length - 1][2] : k.in ? f(k.in) : null;\n\t\tconst outCtrl = outgoing ? outgoing[0][1] : k.out ? f(k.out) : null;\n\t\tif (inCtrl) a.in = inCtrl;\n\t\tif (outCtrl) a.out = outCtrl;\n\t\tif (k.type && k.type !== 'corner') a.type = k.type;\n\t\tif (k.corner) a.corner = { ...k.corner };\n\t\tput(a);\n\t\t// The anchors a split added inside segment i: smooth, as the curve runs through them.\n\t\tif (outgoing) for (let w = 1; w < outgoing.length; w++) put({ x: outgoing[w][0].x, y: outgoing[w][0].y, in: outgoing[w - 1][2], out: outgoing[w][1], type: 'smooth' });\n\t});\n\treturn { closed: sp.closed, anchors };\n}\n\nexport interface MapVectorSubpathsOptions {\n\t/** Refit runs of split pieces with fewer cubics where they stay within the tolerance (default true). */\n\trefit?: boolean;\n}\n\n/**\n * `subpaths` through a smooth, possibly non-linear map `f`: each segment is split in halves until\n * its mapped control points follow the mapped curve within `tolerance` (at most 64 pieces a\n * segment, fewer for huge paths), then refitted with fewer cubics where possible. A straight\n * segment whose image is straight stays a straight segment; anchors keep their types and live\n * corners, and the anchors added are smooth.\n */\nexport function mapVectorSubpaths(subpaths: readonly VectorSubpath[], f: VectorPointMap, tolerance = 0.1, options: MapVectorSubpathsOptions = {}): VectorSubpath[] {\n\tconst tol = Number.isFinite(tolerance) && tolerance > 0 ? tolerance : 0.1;\n\tconst segments = subpaths.reduce((s, sp) => s + sp.anchors.length, 0);\n\tlet depth = MAX_DEPTH;\n\twhile (depth > 0 && segments * 2 ** depth > MAX_PIECES) depth--;\n\treturn subpaths.map((sp) => mapSubpath(sp, f, tol, depth, options.refit !== false));\n}\n\n/** `mapVectorSubpaths` for Bézier commands (live corners are not involved). */\nexport function mapBezierPath(path: BezierPathInput, f: VectorPointMap, tolerance = 0.1, options: MapVectorSubpathsOptions = {}): BezierPath {\n\treturn subpathsToBezier(mapVectorSubpaths(bezierToSubpaths(path), f, tolerance, options), { corners: false });\n}\n","/**\n * Knife and eraser on Bézier paths, built on the curve booleans and `outlineStroke`.\n *\n * The knife cuts filled regions along a polyline with no gap: each stretch of the polyline\n * that crosses a region from boundary to boundary (a chord) splits the boundary loop it starts\n * and ends on into two loops sharing that chord, or, when it joins two loops (an outline and a\n * hole), merges them into one. Crossings are exact (line–cubic roots), and the pieces share\n * the cut edge exactly.\n *\n * The eraser removes the area of a round-capped stroke along a polyline: filled shapes lose it\n * by a boolean difference; outlines are cut where they cross the stroke's outline (exact\n * curve–curve intersections) and keep the parts outside it.\n *\n * Modelled on vectorcraft-main/crates/engine/src/cmd/draw2.rs (`knife`, `erase_region`,\n * `erase_outline`, `cut_subpath`; MIT OR Apache-2.0, © ArtCraft Team and contributors; see\n * THIRD_PARTY_NOTICES.md), without its fixed knife slit and its sampled crossing search.\n */\nimport type { Point } from '../canvas/types.js';\nimport {\n\tbezierPathBounds,\n\tcloseContour,\n\tcontourSignedArea,\n\tcontoursToPath,\n\tpathToContours,\n\tpointInBezierPath,\n\tsegmentBounds,\n\tsegmentPoint,\n\tsubSegment,\n\twindingNumber,\n\ttype BezierPath,\n\ttype BezierPathInput\n} from '../canvas/pathops/bezier.js';\nimport { normalizeBezierPath, pathBoolean, segmentIntersections } from '../canvas/pathops/boolean.js';\nimport { outlineStroke } from '../canvas/pathops/stroke.js';\nimport { inferAnchorType, subpathSegment, subpathSegmentCount } from './geometry.js';\nimport type { VectorAnchor, VectorSubpath } from './types.js';\n\ntype FillRule = 'nonzero' | 'evenodd';\n\n// ---------------------------------------------------------------------------\n// Faces: an outer loop with its holes\n// ---------------------------------------------------------------------------\n\ninterface Loop {\n\tsegs: Point[][];\n\t/** Which segments came from a knife chord (not sampled for containment). */\n\tchord: boolean[];\n}\n\ninterface Face {\n\tloops: Loop[];\n}\n\nconst loopArea = (l: Loop) => contourSignedArea(l.segs);\n\n/** A point on the loop that is not on a chord (chords are shared with a neighbouring piece). */\nfunction loopSample(l: Loop): Point {\n\tconst k = l.chord.findIndex((c) => !c);\n\treturn segmentPoint(l.segs[k >= 0 ? k : 0], 0.5);\n}\n\nconst contains = (l: Loop, p: Point) => windingNumber([l.segs], p) !== 0;\n\n/**\n * Groups non-crossing loops into faces: loops turning like the largest one are outlines, the\n * others holes of the smallest outline around them.\n */\nfunction groupFaces(loops: Loop[]): Face[] {\n\tconst usable = loops.filter((l) => l.segs.length && Math.abs(loopArea(l)) > 1e-12);\n\tif (!usable.length) return [];\n\tconst largest = usable.reduce((a, b) => (Math.abs(loopArea(b)) > Math.abs(loopArea(a)) ? b : a));\n\tconst sign = Math.sign(loopArea(largest));\n\tconst outers = usable.filter((l) => Math.sign(loopArea(l)) === sign).sort((a, b) => Math.abs(loopArea(a)) - Math.abs(loopArea(b)));\n\tconst faces = new Map<Loop, Face>(outers.map((o) => [o, { loops: [o] }]));\n\tfor (const hole of usable.filter((l) => Math.sign(loopArea(l)) !== sign)) {\n\t\tconst p = loopSample(hole);\n\t\tconst parent = outers.find((o) => Math.abs(loopArea(o)) > Math.abs(loopArea(hole)) && contains(o, p));\n\t\tif (parent) faces.get(parent)!.loops.push(hole);\n\t}\n\treturn outers.reverse().map((o) => faces.get(o)!);\n}\n\nfunction faceToPath(face: Face): BezierPath {\n\treturn contoursToPath(face.loops.map((l) => ({ segments: l.segs, closed: true })));\n}\n\n/** Simple, consistently oriented faces of a filled path. */\nfunction facesOf(path: BezierPathInput, fillRule: FillRule): Face[] {\n\tconst normalized = normalizeBezierPath(path, fillRule);\n\tconst loops = pathToContours(normalized).map((c) => {\n\t\tconst segs = closeContour(c, true).map((s) => s.slice());\n\t\treturn { segs, chord: segs.map(() => false) };\n\t});\n\treturn groupFaces(loops);\n}\n\n/** One path per face (an outline with its holes) of a filled path, largest first. */\nexport function splitIntoFaces(path: BezierPathInput, fillRule: FillRule = 'nonzero'): BezierPath[] {\n\treturn facesOf(path, fillRule).map(faceToPath);\n}\n\n// ---------------------------------------------------------------------------\n// Line × segment crossings\n// ---------------------------------------------------------------------------\n\n/** Real roots in [0, 1] of `a·t³ + b·t² + c·t + d` (monotone pieces, bisection). */\nfunction rootsInUnit(a: number, b: number, c: number, d: number, scale: number): number[] {\n\tconst f = (t: number) => ((a * t + b) * t + c) * t + d;\n\tconst tol = 1e-12 * Math.max(1, scale);\n\t// Critical points split [0, 1] into monotone pieces.\n\tconst cuts = [0];\n\tconst qa = 3 * a;\n\tconst qb = 2 * b;\n\tif (Math.abs(qa) > 1e-18) {\n\t\tconst disc = qb * qb - 4 * qa * c;\n\t\tif (disc >= 0) {\n\t\t\tconst r = Math.sqrt(disc);\n\t\t\tfor (const t of [(-qb - r) / (2 * qa), (-qb + r) / (2 * qa)].sort((x, y) => x - y)) if (t > 0 && t < 1) cuts.push(t);\n\t\t}\n\t} else if (Math.abs(qb) > 1e-18) {\n\t\tconst t = -c / qb;\n\t\tif (t > 0 && t < 1) cuts.push(t);\n\t}\n\tcuts.push(1);\n\tconst roots: number[] = [];\n\tconst push = (t: number) => {\n\t\tif (!roots.some((r) => Math.abs(r - t) < 1e-9)) roots.push(t);\n\t};\n\tfor (let i = 0; i < cuts.length - 1; i++) {\n\t\tlet lo = cuts[i];\n\t\tlet hi = cuts[i + 1];\n\t\tlet flo = f(lo);\n\t\tconst fhi = f(hi);\n\t\tif (Math.abs(flo) <= tol) push(lo);\n\t\tif (Math.abs(fhi) <= tol) push(hi);\n\t\tif (flo * fhi >= 0) continue;\n\t\tfor (let k = 0; k < 80; k++) {\n\t\t\tconst m = (lo + hi) / 2;\n\t\t\tconst fm = f(m);\n\t\t\tif (fm === 0) {\n\t\t\t\tlo = hi = m;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (fm * flo < 0) hi = m;\n\t\t\telse {\n\t\t\t\tlo = m;\n\t\t\t\tflo = fm;\n\t\t\t}\n\t\t}\n\t\tpush((lo + hi) / 2);\n\t}\n\treturn roots.sort((x, y) => x - y);\n}\n\n/** Where the line `p → q` crosses a segment: `s` on the line (0–1), `t` on the segment. Parallel overlaps are not crossings. */\nfunction lineHits(p: Point, q: Point, seg: readonly Point[]): { s: number; t: number; point: Point }[] {\n\tconst dx = q[0] - p[0];\n\tconst dy = q[1] - p[1];\n\tconst len2 = dx * dx + dy * dy;\n\tif (len2 < 1e-24) return [];\n\t// Signed distance (times |d|) of the segment from the line, as a polynomial in t.\n\tconst h = (pt: Point) => (pt[0] - p[0]) * -dy + (pt[1] - p[1]) * dx;\n\tlet coeffs: [number, number, number, number];\n\tif (seg.length === 2) coeffs = [0, 0, h(seg[1]) - h(seg[0]), h(seg[0])];\n\telse {\n\t\tconst [h0, h1, h2, h3] = seg.map(h);\n\t\tcoeffs = [-h0 + 3 * h1 - 3 * h2 + h3, 3 * h0 - 6 * h1 + 3 * h2, -3 * h0 + 3 * h1, h0];\n\t}\n\tif (coeffs.every((c) => Math.abs(c) < 1e-12 * Math.max(1, len2))) return [];\n\tconst scale = Math.sqrt(len2) * Math.max(1, ...seg.map((pt) => Math.abs(pt[0]) + Math.abs(pt[1])));\n\tconst out: { s: number; t: number; point: Point }[] = [];\n\tfor (const t of rootsInUnit(...coeffs, scale)) {\n\t\tconst point = segmentPoint(seg, t);\n\t\tconst s = ((point[0] - p[0]) * dx + (point[1] - p[1]) * dy) / len2;\n\t\tif (s >= -1e-9 && s <= 1 + 1e-9) out.push({ s: Math.min(1, Math.max(0, s)), t, point });\n\t}\n\treturn out;\n}\n\n// ---------------------------------------------------------------------------\n// Knife\n// ---------------------------------------------------------------------------\n\ninterface Hit {\n\t/** Knife position: segment index + parameter. */\n\ts: number;\n\tloop: number;\n\tseg: number;\n\tt: number;\n\tpoint: Point;\n}\n\nconst near = (a: Point, b: Point, eps: number) => Math.abs(a[0] - b[0]) <= eps && Math.abs(a[1] - b[1]) <= eps;\nconst degenerate = (seg: readonly Point[], eps: number) => seg.every((p) => near(p, seg[0], eps));\n\n/** The loop's pieces from (seg a, t a) forward to (seg b, t b); `full` goes all the way round when they coincide. */\nfunction arc(l: Loop, a: { seg: number; t: number }, b: { seg: number; t: number }, eps: number): { segs: Point[][]; chord: boolean[] } {\n\tconst n = l.segs.length;\n\tconst segs: Point[][] = [];\n\tconst chord: boolean[] = [];\n\tconst push = (k: number, t0: number, t1: number) => {\n\t\tconst piece = t0 <= 0 && t1 >= 1 ? l.segs[k].slice() : subSegment(l.segs[k], t0, t1);\n\t\tif (!degenerate(piece, eps)) {\n\t\t\tsegs.push(piece);\n\t\t\tchord.push(l.chord[k]);\n\t\t}\n\t};\n\tif (a.seg === b.seg && b.t >= a.t + 1e-12) {\n\t\tpush(a.seg, a.t, b.t);\n\t\treturn { segs, chord };\n\t}\n\tpush(a.seg, a.t, 1);\n\tfor (let k = (a.seg + 1) % n; k !== b.seg; k = (k + 1) % n) push(k, 0, 1);\n\tpush(b.seg, 0, b.t);\n\treturn { segs, chord };\n}\n\n/** Line segments through `points`. */\nfunction polySegs(points: readonly Point[], eps: number): Point[][] {\n\tconst out: Point[][] = [];\n\tfor (let i = 1; i < points.length; i++) if (!near(points[i - 1], points[i], eps)) out.push([points[i - 1], points[i]]);\n\treturn out;\n}\n\n/**\n * Cuts the filled path along the open polyline `knife`. Returns one path per resulting face\n * (an outline with its holes), or null when the knife crossed nothing from edge to edge. A\n * stretch of the knife that starts or ends inside the shape does not cut.\n */\nexport function knifePath(path: BezierPathInput, fillRule: FillRule, knife: readonly Point[]): BezierPath[] | null {\n\tconst pts = knife.filter((p) => Number.isFinite(p[0]) && Number.isFinite(p[1]));\n\tif (pts.length < 2) return null;\n\tlet faces = facesOf(path, fillRule);\n\tif (!faces.length) return null;\n\tconst b = bezierPathBounds(path);\n\tconst size = b ? Math.max(b.maxX - b.minX, b.maxY - b.minY, 1) : 1;\n\tconst eps = size * 1e-9;\n\tlet cursor = -Infinity;\n\tlet cuts = 0;\n\tfor (let guard = 0; guard < 512; guard++) {\n\t\tlet best: { face: number; from: Hit; to: Hit } | null = null;\n\t\tfaces.forEach((face, fi) => {\n\t\t\tconst hits: Hit[] = [];\n\t\t\tfor (let m = 0; m < pts.length - 1; m++) {\n\t\t\t\tif (m + 1 < cursor - 1e-9) continue;\n\t\t\t\tconst kb = { minX: Math.min(pts[m][0], pts[m + 1][0]), maxX: Math.max(pts[m][0], pts[m + 1][0]), minY: Math.min(pts[m][1], pts[m + 1][1]), maxY: Math.max(pts[m][1], pts[m + 1][1]) };\n\t\t\t\tface.loops.forEach((l, li) =>\n\t\t\t\t\tl.segs.forEach((seg, si) => {\n\t\t\t\t\t\tconst sb = segmentBounds(seg);\n\t\t\t\t\t\tif (sb.maxX < kb.minX - eps || sb.minX > kb.maxX + eps || sb.maxY < kb.minY - eps || sb.minY > kb.maxY + eps) return;\n\t\t\t\t\t\tfor (const h of lineHits(pts[m], pts[m + 1], seg)) {\n\t\t\t\t\t\t\tconst s = m + h.s;\n\t\t\t\t\t\t\tif (s >= cursor - 1e-9) hits.push({ s, loop: li, seg: si, t: h.t, point: h.point });\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t);\n\t\t\t}\n\t\t\thits.sort((x, y) => x.s - y.s);\n\t\t\tconst unique = hits.filter((h, i) => i === 0 || h.s - hits[i - 1].s > 1e-9 || !near(h.point, hits[i - 1].point, eps * 10));\n\t\t\tconst inside = (s: number) => {\n\t\t\t\tconst m = Math.min(pts.length - 2, Math.floor(s));\n\t\t\t\tconst u = s - m;\n\t\t\t\tconst q: Point = [pts[m][0] + (pts[m + 1][0] - pts[m][0]) * u, pts[m][1] + (pts[m + 1][1] - pts[m][1]) * u];\n\t\t\t\treturn windingNumber(face.loops.map((l) => l.segs), q) !== 0;\n\t\t\t};\n\t\t\tfor (let i = 0; i < unique.length - 1; i++) {\n\t\t\t\tconst from = unique[i];\n\t\t\t\tconst to = unique[i + 1];\n\t\t\t\tif (near(from.point, to.point, eps * 10) || !inside((from.s + to.s) / 2)) continue;\n\t\t\t\tif (!best || from.s < best.from.s) best = { face: fi, from, to };\n\t\t\t\tbreak;\n\t\t\t}\n\t\t});\n\t\tif (!best) break;\n\t\tconst { face: fi, from, to } = best as { face: number; from: Hit; to: Hit };\n\t\tconst face = faces[fi];\n\t\t// The chord: the crossing points with the knife's corners between them.\n\t\tconst corners: Point[] = [from.point];\n\t\tfor (let m = Math.floor(from.s) + 1; m <= to.s - 1e-12 && m < pts.length; m++) if (m > from.s) corners.push(pts[m]);\n\t\tcorners.push(to.point);\n\t\tconst forward = polySegs(corners, eps);\n\t\tconst back = polySegs(corners.slice().reverse(), eps);\n\t\tconst la = face.loops[from.loop];\n\t\tconst loops = face.loops.filter((_, i) => i !== from.loop && i !== to.loop);\n\t\tif (from.loop === to.loop) {\n\t\t\tconst ab = arc(la, from, to, eps);\n\t\t\tconst ba = arc(la, to, from, eps);\n\t\t\tloops.push(\n\t\t\t\t{ segs: [...ab.segs, ...back], chord: [...ab.chord, ...back.map(() => true)] },\n\t\t\t\t{ segs: [...ba.segs, ...forward], chord: [...ba.chord, ...forward.map(() => true)] }\n\t\t\t);\n\t\t} else {\n\t\t\t// The chord joins two loops into one, with the chord on both sides of a zero-width slit.\n\t\t\tconst lb = face.loops[to.loop];\n\t\t\tconst roundA = arc(la, from, from, eps);\n\t\t\tconst roundB = arc(lb, to, to, eps);\n\t\t\tloops.push({\n\t\t\t\tsegs: [...roundA.segs, ...forward, ...roundB.segs, ...back],\n\t\t\t\tchord: [...roundA.chord, ...forward.map(() => true), ...roundB.chord, ...back.map(() => true)]\n\t\t\t});\n\t\t}\n\t\tfaces = [...faces.slice(0, fi), ...groupFaces(loops), ...faces.slice(fi + 1)];\n\t\tcursor = to.s;\n\t\tcuts++;\n\t}\n\treturn cuts ? faces.map(faceToPath) : null;\n}\n\n// ---------------------------------------------------------------------------\n// Eraser\n// ---------------------------------------------------------------------------\n\n/** The area a round eraser of diameter `width` covers along `points` (a disc for one point). */\nexport function eraserRegion(points: readonly Point[], width: number): BezierPath {\n\tconst pts = points.filter((p) => Number.isFinite(p[0]) && Number.isFinite(p[1]));\n\tconst r = width / 2;\n\tif (!pts.length || !(r > 0)) return [];\n\tconst moved = pts.some((p) => !near(p, pts[0], 1e-9));\n\tif (!moved) {\n\t\tconst [cx, cy] = pts[0];\n\t\tconst k = r * 0.5522847498307936;\n\t\treturn [\n\t\t\t{ type: 'M', x: cx, y: cy - r },\n\t\t\t{ type: 'C', x1: cx + k, y1: cy - r, x2: cx + r, y2: cy - k, x: cx + r, y: cy },\n\t\t\t{ type: 'C', x1: cx + r, y1: cy + k, x2: cx + k, y2: cy + r, x: cx, y: cy + r },\n\t\t\t{ type: 'C', x1: cx - k, y1: cy + r, x2: cx - r, y2: cy + k, x: cx - r, y: cy },\n\t\t\t{ type: 'C', x1: cx - r, y1: cy - k, x2: cx - k, y2: cy - r, x: cx, y: cy - r },\n\t\t\t{ type: 'Z' }\n\t\t];\n\t}\n\tconst line: BezierPath = [{ type: 'M', x: pts[0][0], y: pts[0][1] }, ...pts.slice(1).map((p) => ({ type: 'L' as const, x: p[0], y: p[1] }))];\n\treturn outlineStroke(line, { width, cap: 'round', join: 'round' });\n}\n\n/**\n * A filled path with `region` removed: one path per remaining face, or null when the region\n * does not overlap the fill.\n */\nexport function eraseFromFill(path: BezierPathInput, fillRule: FillRule, region: BezierPathInput): BezierPath[] | null {\n\tconst overlap = pathBoolean('intersection', [{ path, fillRule }, { path: region }]).path;\n\tif (!pathToContours(overlap).some((c) => Math.abs(contourSignedArea(closeContour(c, true))) > 1e-9)) return null;\n\tconst rest = pathBoolean('difference', [{ path, fillRule }, { path: region }]).path;\n\treturn splitIntoFaces(rest);\n}\n\n/**\n * The parts of a subpath's outline outside `region`, as open subpaths that keep the original\n * curves exactly; null when the outline does not enter the region. A closed subpath's last\n * and first parts join at its first anchor. With `keep: 'inside'` the parts inside the region are\n * kept instead (null when the outline never leaves it), as a clipping mask clips an open path.\n */\nexport function eraseFromOutline(sp: VectorSubpath, region: BezierPathInput, options: { keep?: 'outside' | 'inside'; fillRule?: FillRule } = {}): VectorSubpath[] | null {\n\tconst regionSegs = pathToContours(region).flatMap((c) => closeContour(c, true));\n\tif (!regionSegs.length) return null;\n\tconst rb = bezierPathBounds(region);\n\tconst count = subpathSegmentCount(sp);\n\tif (!rb || count === 0) return null;\n\tconst inside = options.keep === 'inside';\n\tconst removed = (p: Point) => pointInBezierPath(region, p, options.fillRule ?? 'nonzero') !== inside;\n\ttype Piece = { seg: number; t0: number; t1: number };\n\tconst runs: Piece[][] = [];\n\tlet cur: Piece[] = [];\n\tlet any = false;\n\tfor (let i = 0; i < count; i++) {\n\t\tconst seg = subpathSegment(sp, i);\n\t\tconst sb = segmentBounds(seg);\n\t\tconst ts = [0, 1];\n\t\tif (!(sb.maxX < rb.minX || sb.minX > rb.maxX || sb.maxY < rb.minY || sb.minY > rb.maxY)) {\n\t\t\tfor (const r of regionSegs) {\n\t\t\t\tconst b = segmentBounds(r);\n\t\t\t\tif (b.maxX < sb.minX || b.minX > sb.maxX || b.maxY < sb.minY || b.minY > sb.maxY) continue;\n\t\t\t\tfor (const hit of segmentIntersections(seg, r)) if (hit.ta > 1e-9 && hit.ta < 1 - 1e-9) ts.push(hit.ta);\n\t\t\t}\n\t\t}\n\t\tts.sort((a, b) => a - b);\n\t\tfor (let k = 0; k < ts.length - 1; k++) {\n\t\t\tconst t0 = ts[k];\n\t\t\tconst t1 = ts[k + 1];\n\t\t\tif (t1 - t0 < 1e-9) continue;\n\t\t\tif (removed(segmentPoint(seg, (t0 + t1) / 2))) {\n\t\t\t\tany = true;\n\t\t\t\tif (cur.length) runs.push(cur);\n\t\t\t\tcur = [];\n\t\t\t} else cur.push({ seg: i, t0, t1 });\n\t\t}\n\t}\n\tif (cur.length) runs.push(cur);\n\tif (!any) return null;\n\t// A closed path's last and first runs meet at anchor 0.\n\tif (sp.closed && runs.length >= 2) {\n\t\tconst first = runs[0][0];\n\t\tconst lastRun = runs[runs.length - 1];\n\t\tconst last = lastRun[lastRun.length - 1];\n\t\tif (first.seg === 0 && first.t0 === 0 && last.seg === count - 1 && last.t1 === 1) lastRun.push(...runs.shift()!);\n\t}\n\tconst out: VectorSubpath[] = [];\n\tfor (const run of runs) {\n\t\tconst anchors: VectorAnchor[] = [];\n\t\tfor (const { seg, t0, t1 } of run) {\n\t\t\tconst c = subSegment(subpathSegment(sp, seg), t0, t1);\n\t\t\tconst line = c.length === 2;\n\t\t\tconst start = c[0];\n\t\t\tconst end = c[c.length - 1];\n\t\t\tif (!anchors.length) anchors.push({ x: start[0], y: start[1] });\n\t\t\tif (!line) anchors[anchors.length - 1].out = { x: c[1][0], y: c[1][1] };\n\t\t\tconst next: VectorAnchor = { x: end[0], y: end[1] };\n\t\t\tif (!line) next.in = { x: c[2][0], y: c[2][1] };\n\t\t\tanchors.push(next);\n\t\t}\n\t\tif (anchors.length < 2) continue;\n\t\tfor (const a of anchors) {\n\t\t\tconst type = inferAnchorType(a);\n\t\t\tif (type !== 'corner') a.type = type;\n\t\t}\n\t\tout.push({ anchors, closed: false });\n\t}\n\treturn out;\n}\n\n/** Bounds of a point list (for picking the paths a knife or eraser stroke can reach). */\nexport function polylineBounds(points: readonly Point[], pad = 0): { x: number; y: number; width: number; height: number } | null {\n\tif (!points.length) return null;\n\tlet minX = Infinity;\n\tlet minY = Infinity;\n\tlet maxX = -Infinity;\n\tlet maxY = -Infinity;\n\tfor (const [x, y] of points) {\n\t\tminX = Math.min(minX, x);\n\t\tminY = Math.min(minY, y);\n\t\tmaxX = Math.max(maxX, x);\n\t\tmaxY = Math.max(maxY, y);\n\t}\n\treturn { x: minX - pad, y: minY - pad, width: maxX - minX + 2 * pad, height: maxY - minY + 2 * pad };\n}\n\n/** Ramer–Douglas–Peucker reduction of a polyline (keeps both ends). */\nexport function simplifyPolyline(points: readonly Point[], tolerance: number): Point[] {\n\tconst n = points.length;\n\tif (n < 3) return points.slice();\n\tconst keep = new Array<boolean>(n).fill(false);\n\tkeep[0] = keep[n - 1] = true;\n\tconst stack: [number, number][] = [[0, n - 1]];\n\twhile (stack.length) {\n\t\tconst [a, b] = stack.pop()!;\n\t\tconst [ax, ay] = points[a];\n\t\tconst dx = points[b][0] - ax;\n\t\tconst dy = points[b][1] - ay;\n\t\tconst len = Math.hypot(dx, dy);\n\t\tlet far = -1;\n\t\tlet farD = 0;\n\t\tfor (let i = a + 1; i < b; i++) {\n\t\t\tconst [px, py] = points[i];\n\t\t\tconst d = len < 1e-12 ? Math.hypot(px - ax, py - ay) : Math.abs((px - ax) * dy - (py - ay) * dx) / len;\n\t\t\tif (d > farD) {\n\t\t\t\tfarD = d;\n\t\t\t\tfar = i;\n\t\t\t}\n\t\t}\n\t\tif (far >= 0 && farD > tolerance) {\n\t\t\tkeep[far] = true;\n\t\t\tstack.push([a, far], [far, b]);\n\t\t}\n\t}\n\treturn points.filter((_, i) => keep[i]);\n}\n\n","/**\n * Visual filters of vector nodes: drop shadow, inner shadow, outer and inner glow, layer blur and\n * feather, drawn as one SVG `<filter>` per node (in the canvases and in SVG export alike).\n *\n * The filter takes everything the node draws (`SourceGraphic`) and its silhouette\n * (`SourceAlpha`) in the node's own space, and builds, in this order:\n *\n * 1. Inner shadows and inner glows, in stack order, over the body: the inverse of the silhouette\n * (offset for a shadow), grown by `spread` (which chokes the shadow inwards), blurred, coloured\n * and clipped to the silhouette.\n * 2. Feather: the body kept where the silhouette, eroded by half the radius and blurred by a\n * quarter of it, is, so the edge fades from about nothing at the outline to full strength\n * `radius` inside.\n * 3. Drop shadows and outer glows, in stack order, under the body: the silhouette grown by\n * `spread`, blurred, offset (shadows) and coloured.\n * 4. Layer blurs, over the whole result (shadows included).\n *\n * Blur radii are CSS / Figma blur radii: the Gaussian's standard deviation is half the radius, and\n * it reaches about 1.5 radii. Background blur needs the backdrop, which an SVG filter cannot read\n * (`BackgroundImage` was dropped from browsers) and which other SVG readers cannot either, so it is\n * left to the planned lens objects.\n *\n * The construction of feather, glows and inner shadows from blur, offset and clip follows\n * designcraft `crates/render/src/fx.rs` (`draw_item_fx`, `inner_edge`, `split`); the effect set,\n * defaults and reach follow figcraft `crates/doc/src/props.rs` (`EffectKind`, `Shadow`,\n * `Effect::reach`). Ported from ArtCraft (MIT OR Apache-2.0, © ArtCraft Team and contributors; see\n * THIRD_PARTY_NOTICES.md).\n */\nimport type { VectorEffectParamSpec } from './appearance.js';\nimport { VECTOR_FILTER_TYPES, type VectorBounds, type VectorFilter, type VectorFilterParamsMap, type VectorFilterType, type VectorNode } from './types.js';\n\n/** Default parameters of each filter type. */\nexport const VECTOR_FILTER_DEFAULTS: { readonly [K in VectorFilterType]: VectorFilterParamsMap[K] } = {\n\tdropShadow: { color: '#000000', opacity: 0.25, offsetX: 0, offsetY: 4, blur: 4, spread: 0 },\n\tinnerShadow: { color: '#000000', opacity: 0.25, offsetX: 0, offsetY: 4, blur: 4, spread: 0 },\n\touterGlow: { color: '#ffffbe', opacity: 0.75, blur: 10, spread: 0 },\n\tinnerGlow: { color: '#ffffbe', opacity: 0.75, blur: 10, spread: 0 },\n\tlayerBlur: { radius: 4 },\n\tfeather: { radius: 8 }\n};\n\nexport const VECTOR_FILTER_LABELS: Readonly<Record<VectorFilterType, string>> = {\n\tdropShadow: 'Drop Shadow',\n\tinnerShadow: 'Inner Shadow',\n\touterGlow: 'Outer Glow',\n\tinnerGlow: 'Inner Glow',\n\tlayerBlur: 'Layer Blur',\n\tfeather: 'Feather'\n};\n\n/** How a panel edits one filter parameter: an effect parameter spec, or a colour. */\nexport type VectorFilterParamSpec = VectorEffectParamSpec | { key: string; label: string; kind: 'color' };\n\nconst SHADOW_SPECS: VectorFilterParamSpec[] = [\n\t{ key: 'color', label: 'Color', kind: 'color' },\n\t{ key: 'opacity', label: 'Opacity', kind: 'number', min: 0, max: 1, step: 0.01, slider: true },\n\t{ key: 'offsetX', label: 'X', kind: 'number', min: -1000, max: 1000, step: 1 },\n\t{ key: 'offsetY', label: 'Y', kind: 'number', min: -1000, max: 1000, step: 1 },\n\t{ key: 'blur', label: 'Blur', kind: 'number', min: 0, max: 500, step: 1 },\n\t{ key: 'spread', label: 'Spread', kind: 'number', min: 0, max: 500, step: 1 }\n];\nconst GLOW_SPECS = SHADOW_SPECS.filter((s) => s.key !== 'offsetX' && s.key !== 'offsetY');\n\n/** The editable parameters of each filter type, in panel order. */\nexport const VECTOR_FILTER_PARAM_SPECS: Readonly<Record<VectorFilterType, readonly VectorFilterParamSpec[]>> = {\n\tdropShadow: SHADOW_SPECS,\n\tinnerShadow: SHADOW_SPECS.map((s) => (s.key === 'spread' ? { ...s, label: 'Choke' } : s)),\n\touterGlow: GLOW_SPECS,\n\tinnerGlow: GLOW_SPECS.map((s) => (s.key === 'spread' ? { ...s, label: 'Choke' } : s)),\n\tlayerBlur: [{ key: 'radius', label: 'Radius', kind: 'number', min: 0, max: 500, step: 1, slider: true }],\n\tfeather: [{ key: 'radius', label: 'Radius', kind: 'number', min: 0, max: 500, step: 1, slider: true }]\n};\n\nexport function isVectorFilterType(value: unknown): value is VectorFilterType {\n\treturn typeof value === 'string' && (VECTOR_FILTER_TYPES as readonly string[]).includes(value);\n}\n\n/**\n * Filter parameters with defaults (or `base`) filled in; values of the wrong type are dropped,\n * numbers clamped to their range, unknown keys ignored. Null for an unknown type.\n */\nexport function normalizeVectorFilterParams<K extends VectorFilterType>(type: K, params: Record<string, unknown> | null | undefined, base?: VectorFilterParamsMap[K]): VectorFilterParamsMap[K] | null {\n\tif (!isVectorFilterType(type)) return null;\n\tconst out: Record<string, unknown> = { ...VECTOR_FILTER_DEFAULTS[type], ...((base as Record<string, unknown> | undefined) ?? {}) };\n\tfor (const spec of VECTOR_FILTER_PARAM_SPECS[type]) {\n\t\tconst v = params?.[spec.key];\n\t\tif (v === undefined) continue;\n\t\tif (spec.kind === 'number' && typeof v === 'number' && Number.isFinite(v)) out[spec.key] = Math.min(spec.max ?? Infinity, Math.max(spec.min ?? -Infinity, v));\n\t\telse if (spec.kind === 'color' && typeof v === 'string' && v.trim()) out[spec.key] = v.trim();\n\t}\n\treturn out as VectorFilterParamsMap[K];\n}\n\n/** The parameter keys a filter type takes (for error messages). */\nexport function vectorFilterParamKeys(type: VectorFilterType): string[] {\n\treturn VECTOR_FILTER_PARAM_SPECS[type].map((s) => s.key);\n}\n\n/** A new filter of `type` (defaults merged with `params`), or null for an unknown type. */\nexport function createVectorFilter<K extends VectorFilterType>(type: K, id: string, params?: Partial<VectorFilterParamsMap[K]> | Record<string, unknown>): Extract<VectorFilter, { type: K }> | null {\n\tconst p = normalizeVectorFilterParams(type, params as Record<string, unknown>);\n\treturn p ? ({ id, type, params: p } as unknown as Extract<VectorFilter, { type: K }>) : null;\n}\n\n/**\n * Reads filters from untrusted data (JSON, agent input, SVG): unknown types and malformed entries\n * are dropped, parameters normalized, ids made unique.\n */\nexport function sanitizeVectorFilters(value: unknown): VectorFilter[] {\n\tif (!Array.isArray(value)) return [];\n\tconst out: VectorFilter[] = [];\n\tconst used = new Set<string>();\n\tfor (const raw of value) {\n\t\tif (!raw || typeof raw !== 'object') continue;\n\t\tconst r = raw as Record<string, unknown>;\n\t\tif (!isVectorFilterType(r.type)) continue;\n\t\tlet id = typeof r.id === 'string' && r.id && !used.has(r.id) ? r.id : '';\n\t\tfor (let k = out.length + 1; !id; k++) if (!used.has(`filter${k}`)) id = `filter${k}`;\n\t\tused.add(id);\n\t\tconst filter = createVectorFilter(r.type, id, (r.params as Record<string, unknown>) ?? {})!;\n\t\tout.push(r.enabled === false ? { ...filter, enabled: false } : filter);\n\t}\n\treturn out;\n}\n\n/** The node's filters that draw something (enabled, known, with a visible result). */\nexport function activeVectorFilters(node: Pick<VectorNode, 'filters'>): VectorFilter[] {\n\treturn (node.filters ?? []).filter((f) => {\n\t\tif (f.enabled === false || !isVectorFilterType(f.type)) return false;\n\t\tif (f.type === 'layerBlur' || f.type === 'feather') return f.params.radius > 0;\n\t\treturn f.params.opacity > 0;\n\t});\n}\n\n/** How far a node's filters can paint past what it draws, in its own units. */\nexport function vectorFilterReach(filters: readonly VectorFilter[]): number {\n\tlet outer = 0;\n\tlet blur = 0;\n\tfor (const f of filters) {\n\t\tswitch (f.type) {\n\t\t\tcase 'dropShadow':\n\t\t\tcase 'innerShadow':\n\t\t\t\touter = Math.max(outer, Math.max(Math.abs(f.params.offsetX), Math.abs(f.params.offsetY)) + f.params.blur * 1.5 + f.params.spread);\n\t\t\t\tbreak;\n\t\t\tcase 'outerGlow':\n\t\t\tcase 'innerGlow':\n\t\t\t\touter = Math.max(outer, f.params.blur * 1.5 + f.params.spread);\n\t\t\t\tbreak;\n\t\t\tcase 'layerBlur':\n\t\t\t\tblur += f.params.radius * 1.5;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn outer + blur;\n}\n\n/** One SVG filter primitive as data: a tag (`feGaussianBlur`, …), its attributes and children. */\nexport interface VectorFilterPrimitive {\n\ttag: string;\n\tattrs: Readonly<Record<string, string | number>>;\n\tchildren?: VectorFilterPrimitive[];\n}\n\n/**\n * A node's filter as data: draw `<filter id filterUnits=\"userSpaceOnUse\" x y width height\n * color-interpolation-filters=\"sRGB\">` with the primitives inside, and reference it with\n * `filter=\"url(#id)\"` on the node's element. The region is in the node's own space.\n */\nexport interface VectorRenderFilter {\n\tid: string;\n\tx: number;\n\ty: number;\n\twidth: number;\n\theight: number;\n\tprimitives: VectorFilterPrimitive[];\n}\n\nconst round = (n: number) => Math.round(n * 1000) / 1000;\nconst fe = (tag: string, attrs: Record<string, string | number>, children?: VectorFilterPrimitive[]): VectorFilterPrimitive => ({ tag, attrs, ...(children ? { children } : {}) });\n\n/**\n * The SVG filter for `filters` over a node whose drawing covers `bounds` (its own space, strokes\n * included), or null when none of them draws.\n */\nexport function vectorFilterSvg(filters: readonly VectorFilter[], id: string, bounds: VectorBounds | null): VectorRenderFilter | null {\n\tconst active = filters.filter((f) => activeVectorFilters({ filters: [f] }).length);\n\tif (!active.length || !bounds) return null;\n\tconst primitives: VectorFilterPrimitive[] = [];\n\tlet body = 'SourceGraphic';\n\tlet n = 0;\n\tconst name = (part: string) => `${part}${n}`;\n\t// Inner shadows and glows, over the body and clipped to the silhouette.\n\tfor (const f of active) {\n\t\tif (f.type !== 'innerShadow' && f.type !== 'innerGlow') continue;\n\t\tn++;\n\t\tconst p = f.params;\n\t\tprimitives.push(fe('feComponentTransfer', { in: 'SourceAlpha', result: name('inv') }, [fe('feFuncA', { type: 'table', tableValues: '1 0' })]));\n\t\tlet last = name('inv');\n\t\tif (f.type === 'innerShadow' && (f.params.offsetX || f.params.offsetY)) {\n\t\t\tprimitives.push(fe('feOffset', { in: last, dx: round(f.params.offsetX), dy: round(f.params.offsetY), result: name('off') }));\n\t\t\tlast = name('off');\n\t\t}\n\t\tif (p.spread > 0) {\n\t\t\tprimitives.push(fe('feMorphology', { in: last, operator: 'dilate', radius: round(p.spread), result: name('grow') }));\n\t\t\tlast = name('grow');\n\t\t}\n\t\tif (p.blur > 0) {\n\t\t\tprimitives.push(fe('feGaussianBlur', { in: last, stdDeviation: round(p.blur / 2), result: name('blur') }));\n\t\t\tlast = name('blur');\n\t\t}\n\t\tprimitives.push(fe('feFlood', { 'flood-color': p.color, 'flood-opacity': round(p.opacity), result: name('color') }));\n\t\tprimitives.push(fe('feComposite', { in: name('color'), in2: last, operator: 'in', result: name('tint') }));\n\t\tprimitives.push(fe('feComposite', { in: name('tint'), in2: 'SourceAlpha', operator: 'in', result: name('inner') }));\n\t\tprimitives.push(fe('feComposite', { in: name('inner'), in2: body, operator: 'over', result: name('body') }));\n\t\tbody = name('body');\n\t}\n\t// Feather: keep the body where the eroded, blurred silhouette is.\n\tfor (const f of active) {\n\t\tif (f.type !== 'feather') continue;\n\t\tn++;\n\t\tconst r = f.params.radius;\n\t\tprimitives.push(fe('feMorphology', { in: 'SourceAlpha', operator: 'erode', radius: round(r / 2), result: name('core') }));\n\t\tprimitives.push(fe('feGaussianBlur', { in: name('core'), stdDeviation: round(r / 4), result: name('fade') }));\n\t\tprimitives.push(fe('feComposite', { in: body, in2: name('fade'), operator: 'in', result: name('body') }));\n\t\tbody = name('body');\n\t}\n\t// Drop shadows and outer glows, under the body.\n\tconst under: string[] = [];\n\tfor (const f of active) {\n\t\tif (f.type !== 'dropShadow' && f.type !== 'outerGlow') continue;\n\t\tn++;\n\t\tconst p = f.params;\n\t\tlet last = 'SourceAlpha';\n\t\tif (p.spread > 0) {\n\t\t\tprimitives.push(fe('feMorphology', { in: last, operator: 'dilate', radius: round(p.spread), result: name('grow') }));\n\t\t\tlast = name('grow');\n\t\t}\n\t\tif (p.blur > 0) {\n\t\t\tprimitives.push(fe('feGaussianBlur', { in: last, stdDeviation: round(p.blur / 2), result: name('blur') }));\n\t\t\tlast = name('blur');\n\t\t}\n\t\tif (f.type === 'dropShadow' && (f.params.offsetX || f.params.offsetY)) {\n\t\t\tprimitives.push(fe('feOffset', { in: last, dx: round(f.params.offsetX), dy: round(f.params.offsetY), result: name('off') }));\n\t\t\tlast = name('off');\n\t\t}\n\t\tprimitives.push(fe('feFlood', { 'flood-color': p.color, 'flood-opacity': round(p.opacity), result: name('color') }));\n\t\tprimitives.push(fe('feComposite', { in: name('color'), in2: last, operator: 'in', result: name('shadow') }));\n\t\tunder.push(name('shadow'));\n\t}\n\tif (under.length) {\n\t\tn++;\n\t\tprimitives.push(fe('feMerge', { result: name('merged') }, [...under, body].map((i) => fe('feMergeNode', { in: i }))));\n\t\tbody = name('merged');\n\t}\n\t// Layer blurs, over everything.\n\tfor (const f of active) {\n\t\tif (f.type !== 'layerBlur') continue;\n\t\tn++;\n\t\tprimitives.push(fe('feGaussianBlur', { in: body, stdDeviation: round(f.params.radius / 2), result: name('body') }));\n\t\tbody = name('body');\n\t}\n\t// The last primitive is the filter's result; make sure it is the body.\n\tconst lastResult = primitives[primitives.length - 1]?.attrs.result;\n\tif (lastResult !== body) primitives.push(fe('feMerge', {}, [fe('feMergeNode', { in: body })]));\n\tconst pad = vectorFilterReach(active) + 2;\n\treturn {\n\t\tid,\n\t\tx: round(bounds.x - pad),\n\t\ty: round(bounds.y - pad),\n\t\twidth: round(bounds.width + 2 * pad),\n\t\theight: round(bounds.height + 2 * pad),\n\t\tprimitives\n\t};\n}\n\nconst escapeAttr = (value: string) => value.replace(/&/g, '&').replace(/\"/g, '"').replace(/</g, '<').replace(/>/g, '>');\n\nfunction primitiveMarkup(p: VectorFilterPrimitive): string {\n\tconst attrs = Object.entries(p.attrs)\n\t\t.map(([k, v]) => ` ${k}=\"${escapeAttr(String(v))}\"`)\n\t\t.join('');\n\treturn p.children?.length ? `<${p.tag}${attrs}>${p.children.map(primitiveMarkup).join('')}</${p.tag}>` : `<${p.tag}${attrs}/>`;\n}\n\n/** A render filter as SVG markup (`extra` is added to the `<filter>` element's attributes). */\nexport function vectorFilterMarkup(filter: VectorRenderFilter, extra = ''): string {\n\treturn `<filter id=\"${escapeAttr(filter.id)}\" filterUnits=\"userSpaceOnUse\" x=\"${filter.x}\" y=\"${filter.y}\" width=\"${filter.width}\" height=\"${filter.height}\" color-interpolation-filters=\"sRGB\"${extra}>${filter.primitives.map(primitiveMarkup).join('')}</filter>`;\n}\n\n/** Labels of the filter types, for menus. */\nexport const VECTOR_FILTER_MENU: readonly { type: VectorFilterType; label: string }[] = VECTOR_FILTER_TYPES.map((type) => ({ type, label: VECTOR_FILTER_LABELS[type] }));\n","/**\n * Masks and clipping. A group with `mask` set is a mask group: its first (bottom) child is the\n * mask and the children above it (the contents) show only where the mask lets them.\n *\n * - `clip`: a clipping mask, by the mask's outline (every path inside it, filled by its own fill\n * rule, whatever its paint; the mask's paint is not drawn). Drawn as an SVG `<clipPath>`.\n * - `alpha` / `luminance`: an opacity mask, by the mask's drawn alpha or its brightness (times its\n * alpha). Drawn as an SVG `<mask>` holding the mask as drawn (`mask-type=\"alpha\"` for alpha).\n * - `invert` swaps what shows and what hides. An inverted clip is the even-odd clip of a large\n * rectangle with the mask's outline (its boolean union) cut out of it, as pdfcraft's redaction\n * clips content out of a region; an inverted opacity mask draws the mask through a colour\n * matrix filter that turns its alpha (or brightness) upside down.\n *\n * Geometry uses the masked result: the contents' shapes clipped by the mask's region (its outline\n * for clips, its painted area for opacity masks) with our booleans, open paths cut where they\n * cross it. Bounds, hit-testing, snapping, outlines, booleans and the Pathfinder all read it\n * through `vectorAppearanceShapes`. An opacity mask is hit and bounded by where it paints at all,\n * not by how strongly: a dark luminance mask still counts.\n *\n * A hidden mask child turns the mask off and the contents draw whole (figcraft\n * `crates/doc/src/geometry.rs`: a hidden mask doesn't clip). The group's own opacity, blend mode\n * and filters apply after masking (its drop shadow follows the masked silhouette), and its path\n * effects act on the contents only, not on the mask.\n *\n * Extension point for lens objects: a lens is a shape that changes what is beneath it (blur,\n * magnify, recolour). It will reuse this module's pieces rather than the mask group model: the\n * region of a shape (`vectorMaskRegionShapes` with the lens as the source) clips a filtered copy\n * of the backdrop the way `vectorMaskRenderData` clips the contents, and hit-testing and bounds\n * stay those of the lens shape itself. See `VectorMaskRenderData` for where a renderer draws it.\n *\n * The mask model (`is_mask`, `MaskType`: alpha, vector, luminance; hidden masks off) follows\n * figcraft `crates/doc/src/node.rs` and `geometry.rs`; clipping a node's drawing to a shape layer\n * by layer follows designcraft `crates/render/src/fx.rs` (`push_clip_layer` around each body); the\n * inverted clip follows pdfcraft `crates/redact/src/interp.rs` (`clip_out`). Ported from ArtCraft\n * (MIT OR Apache-2.0, © ArtCraft Team and contributors; see THIRD_PARTY_NOTICES.md).\n */\nimport { bezierPathBounds, bezierPathToSvg, distanceToBezierPath, transformBezierPath, pointInBezierPath, type AffineMatrix, type BezierPath } from '../canvas/pathops/bezier.js';\nimport { pathBoolean } from '../canvas/pathops/boolean.js';\nimport { IDENTITY_MATRIX, isIdentityMatrix, multiplyMatrices } from '../geom/affine.js';\nimport { applyVectorEffects, expandVectorAppearance, vectorAppearanceNodes, vectorAppearanceShapes, vectorChildAppearanceShapes, type VectorAppearanceShape } from './appearance.js';\nimport { bezierToSubpaths, hitTestVectorNode, nodeMatrix, subpathsToBezier, unionBounds, vectorNodeBounds } from './geometry.js';\nimport { vectorPaintLayerNodes, vectorStrokeStackReach } from './paintLayers.js';\nimport { eraseFromOutline } from './pathCut.js';\nimport { vectorStrokeOutlinePath } from './stroke.js';\nimport { activeVectorFilters, vectorFilterReach, type VectorFilterPrimitive, type VectorRenderFilter } from './filters.js';\nimport { VECTOR_MASK_TYPES, type VectorBounds, type VectorFillRule, type VectorGroupNode, type VectorMask, type VectorMaskType, type VectorNode, type Vec2 } from './types.js';\n\n/** A group whose `mask` takes effect (not a blend or live boolean, with a child to be the mask). */\nexport type VectorMaskGroup = VectorGroupNode & { mask: VectorMask };\n\n/** Whether `value` is a mask type. */\nexport function isVectorMaskType(value: unknown): value is VectorMaskType {\n\treturn typeof value === 'string' && (VECTOR_MASK_TYPES as readonly string[]).includes(value);\n}\n\n/** Reads mask settings from untrusted data (JSON, agent input, SVG data attributes); null when invalid. */\nexport function sanitizeVectorMask(value: unknown): VectorMask | null {\n\tif (!value || typeof value !== 'object') return null;\n\tconst r = value as Record<string, unknown>;\n\tif (!isVectorMaskType(r.type)) return null;\n\treturn r.invert === true ? { type: r.type, invert: true } : { type: r.type };\n}\n\n/** Whether a node is a mask group: a group with `mask`, at least one child, and not a blend or live boolean. */\nexport function isVectorMaskGroup(node: VectorNode | null | undefined): node is VectorMaskGroup {\n\treturn node?.type === 'group' && !!node.mask && isVectorMaskType(node.mask.type) && !node.blend && !node.liveBoolean && node.children.length > 0;\n}\n\n/** Whether a mask group's mask is on: its mask child is visible. */\nexport function isVectorMaskActive(node: VectorNode | null | undefined): node is VectorMaskGroup {\n\treturn isVectorMaskGroup(node) && node.children[0].visible !== false;\n}\n\n/** A mask group's mask (its first child), or null. */\nexport function vectorMaskSource(node: VectorNode | null | undefined): VectorNode | null {\n\treturn isVectorMaskGroup(node) ? node.children[0] : null;\n}\n\n/** The children a mask group masks (all but the first); a plain group's children. */\nexport function vectorMaskContents(group: VectorGroupNode): VectorNode[] {\n\treturn isVectorMaskGroup(group) ? group.children.slice(1) : group.children;\n}\n\n/** The mask group whose mask is `id`, or null. */\nexport function vectorMaskOwner(nodes: readonly VectorNode[], id: string): VectorMaskGroup | null {\n\tfor (const n of nodes) {\n\t\tif (n.type !== 'group') continue;\n\t\tif (isVectorMaskGroup(n) && n.children[0].id === id) return n;\n\t\tconst inner = vectorMaskOwner(n.children, id);\n\t\tif (inner) return inner;\n\t}\n\treturn null;\n}\n\n/** What agents and panels read about a mask group. */\nexport interface VectorMaskSummary {\n\ttype: VectorMaskType;\n\tinvert: boolean;\n\t/** Id of the mask (the group's first child). */\n\tmaskId: string;\n\t/** Ids of the masked contents, bottom to top. */\n\tcontents: string[];\n\t/** False while the mask child is hidden (the contents draw whole). */\n\tenabled: boolean;\n}\n\n/** A mask group's settings, mask and contents, or null for any other node. */\nexport function vectorMaskSummary(node: VectorNode | null | undefined): VectorMaskSummary | null {\n\tif (!isVectorMaskGroup(node)) return null;\n\treturn {\n\t\ttype: node.mask.type,\n\t\tinvert: !!node.mask.invert,\n\t\tmaskId: node.children[0].id,\n\t\tcontents: node.children.slice(1).map((c) => c.id),\n\t\tenabled: node.children[0].visible !== false\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Regions\n// ---------------------------------------------------------------------------\n\n/** One shape of a mask's region: a path (in the mask group's own space) and the rule that fills it. */\nexport interface VectorMaskRegionShape {\n\tpath: BezierPath;\n\tfillRule: VectorFillRule;\n}\n\nconst place = (path: BezierPath, m: AffineMatrix) => (isIdentityMatrix(m) ? path : transformBezierPath(path, m));\n\n/**\n * The area `node` covers as a mask of `type`, in the space `parent` maps it to: for a clip, the\n * outline of every visible path inside it (effects applied), whatever its paint; for an opacity\n * mask, where it paints (drawn fills, and drawn strokes as their outlines). A nested mask group\n * covers its masked result. `self` counts the node even when hidden (the mask itself).\n */\nexport function vectorMaskRegionShapes(node: VectorNode, type: VectorMaskType, parent: AffineMatrix = IDENTITY_MATRIX, self = true): VectorMaskRegionShape[] {\n\tif (!self && node.visible === false) return [];\n\tconst m = multiplyMatrices(nodeMatrix(node), parent);\n\tif (isVectorMaskActive(node) || (node.type === 'group' && node.effects?.length)) {\n\t\t// Drawn as shapes: a nested mask's masked result, or a group's effects applied.\n\t\treturn vectorAppearanceShapes(node).flatMap((s) => regionOfPath(s.path, s.source, type, m));\n\t}\n\tconst drawn = expandVectorAppearance(node);\n\tif (drawn.type === 'group') {\n\t\tconst inner = multiplyMatrices(nodeMatrix(drawn), parent);\n\t\treturn drawn.children.flatMap((c) => vectorMaskRegionShapes(c, type, inner, false));\n\t}\n\treturn regionOfPath(subpathsToBezier(drawn.subpaths), drawn, type, m);\n}\n\nfunction regionOfPath(path: BezierPath, style: VectorNode & { type: 'path' }, type: VectorMaskType, m: AffineMatrix): VectorMaskRegionShape[] {\n\tif (!path.length) return [];\n\tconst fillRule = style.fillRule ?? 'nonzero';\n\tif (type === 'clip') return [{ path: place(path, m), fillRule }];\n\tconst out: VectorMaskRegionShape[] = [];\n\tlet filled = false;\n\tfor (const l of vectorPaintLayerNodes(style)) {\n\t\tif (!l.drawn) continue;\n\t\tif (l.kind === 'fill') {\n\t\t\tif (!filled) out.push({ path: place(path, m), fillRule });\n\t\t\tfilled = true;\n\t\t} else if ((l.node.strokeWidth ?? 1) > 0) {\n\t\t\tconst area = vectorStrokeOutlinePath(path, l.node);\n\t\t\tif (area.length) out.push({ path: place(area, m), fillRule: 'nonzero' });\n\t\t}\n\t}\n\treturn out;\n}\n\nconst regionCache = new WeakMap<VectorMaskGroup, VectorMaskRegionShape[]>();\n\n/** The region of a mask group's mask in the group's own space (not inverted). Cached per group object. */\nexport function vectorMaskRegion(group: VectorMaskGroup): VectorMaskRegionShape[] {\n\tlet hit = regionCache.get(group);\n\tif (!hit) {\n\t\thit = vectorMaskRegionShapes(group.children[0], group.mask.type);\n\t\tregionCache.set(group, hit);\n\t}\n\treturn hit;\n}\n\nconst unionCache = new WeakMap<VectorMaskGroup, BezierPath>();\n\n/** The mask's region as one clean path (a boolean union, read nonzero or even-odd alike). Cached per group object. */\nexport function vectorMaskRegionPath(group: VectorMaskGroup): BezierPath {\n\tlet hit = unionCache.get(group);\n\tif (!hit) {\n\t\tconst shapes = vectorMaskRegion(group);\n\t\thit = !shapes.length ? [] : shapes.length === 1 && shapes[0].fillRule === 'nonzero' ? shapes[0].path : pathBoolean('union', shapes.map((s) => ({ path: s.path, fillRule: s.fillRule }))).path;\n\t\tunionCache.set(group, hit);\n\t}\n\treturn hit;\n}\n\n/** Whether a point (in the group's own space) is inside the mask's region, `tolerance` past its edge counting. */\nfunction inRegion(group: VectorMaskGroup, p: Vec2, tolerance: number): boolean {\n\tconst pt: [number, number] = [p.x, p.y];\n\tfor (const s of vectorMaskRegion(group)) {\n\t\tif (pointInBezierPath(s.path, pt, s.fillRule)) return true;\n\t\tif (tolerance > 0 && distanceToBezierPath(s.path, pt) <= tolerance) return true;\n\t}\n\treturn false;\n}\n\n/**\n * Whether a mask group's mask lets point `p` (the group's own space) through: inside its region,\n * or outside it when inverted. `tolerance` widens what counts as through (its edge, either way).\n * Always true while the mask is off.\n */\nexport function vectorMaskContains(group: VectorMaskGroup, p: Vec2, tolerance = 0): boolean {\n\tif (!isVectorMaskActive(group)) return true;\n\tif (group.mask.type !== 'clip') {\n\t\t// Opacity masks: where the mask paints, by its own hit-test (strokes, alignment, arrowheads).\n\t\tconst source = group.children[0];\n\t\tconst hit = hitTestVectorNode(source.visible === false ? { ...source, visible: true } : source, p, group.mask.invert ? 0 : tolerance);\n\t\treturn group.mask.invert ? !hit || (tolerance > 0 && hitNearEdge(group, p, tolerance)) : hit;\n\t}\n\tif (!group.mask.invert) return inRegion(group, p, tolerance);\n\treturn !inRegion(group, p, 0) || hitNearEdge(group, p, tolerance);\n}\n\nfunction hitNearEdge(group: VectorMaskGroup, p: Vec2, tolerance: number): boolean {\n\tif (tolerance <= 0) return false;\n\treturn vectorMaskRegion(group).some((s) => distanceToBezierPath(s.path, [p.x, p.y]) <= tolerance);\n}\n\n// ---------------------------------------------------------------------------\n// Masked shapes\n// ---------------------------------------------------------------------------\n\n/** A path's open subpaths cut by the region (kept inside it, or outside when inverted). */\nfunction clipOpen(path: BezierPath, region: BezierPath, invert: boolean): BezierPath {\n\tconst out: BezierPath = [];\n\tfor (const sp of bezierToSubpaths(path)) {\n\t\tconst pieces = eraseFromOutline(sp, region, { keep: invert ? 'outside' : 'inside' });\n\t\t// Null: the outline never crosses the region's edge, so it is all in or all out.\n\t\tif (pieces === null) {\n\t\t\tconst a = sp.anchors[0];\n\t\t\tconst inside = !!a && pointInBezierPath(region, [a.x, a.y], 'nonzero');\n\t\t\tif (inside !== invert) out.push(...subpathsToBezier([sp]));\n\t\t} else out.push(...subpathsToBezier(pieces));\n\t}\n\treturn out;\n}\n\n/** A shape's path clipped by the mask's region: booleans for its closed contours, cuts for its open ones. */\nfunction clipShapePath(path: BezierPath, fillRule: VectorFillRule, region: BezierPath, invert: boolean): BezierPath {\n\tconst subpaths = bezierToSubpaths(path);\n\tconst closed = subpaths.filter((sp) => sp.closed);\n\tconst open = subpaths.filter((sp) => !sp.closed);\n\tconst out: BezierPath = [];\n\tif (closed.length) {\n\t\tconst operands = [{ path: subpathsToBezier(closed), fillRule }, { path: region, fillRule: 'nonzero' as const }];\n\t\tout.push(...(region.length ? pathBoolean(invert ? 'difference' : 'intersection', operands).path : invert ? operands[0].path : []));\n\t}\n\tif (open.length) out.push(...(region.length ? clipOpen(subpathsToBezier(open), region, invert) : invert ? subpathsToBezier(open) : []));\n\treturn out;\n}\n\n/**\n * What a mask group draws as shapes in its own space: its contents' shapes (their own effects\n * applied, then the group's), each clipped by the mask's region. The appearance code calls this\n * for mask groups (`vectorAppearanceShapes`), so use that instead (it caches).\n */\nexport function vectorMaskedShapes(group: VectorMaskGroup): VectorAppearanceShape[] {\n\tconst contents = group.children.flatMap((c, i) => (i === 0 ? [] : vectorChildAppearanceShapes(c, i)));\n\tconst shapes = applyVectorEffects(contents, group.effects);\n\tif (!isVectorMaskActive(group)) return shapes;\n\tconst region = vectorMaskRegionPath(group);\n\tconst invert = !!group.mask.invert;\n\tconst out: VectorAppearanceShape[] = [];\n\tfor (const s of shapes) {\n\t\tconst path = clipShapePath(s.path, s.source.fillRule ?? 'nonzero', region, invert);\n\t\t// Keep the shape's evaluated paths in the clip's clean nonzero form.\n\t\tif (path.length) out.push({ ...s, path, source: s.source.fillRule === 'evenodd' ? { ...s.source, fillRule: 'nonzero' } : s.source });\n\t}\n\treturn out;\n}\n\n/**\n * The node with every working mask group inside it replaced by a plain group of its masked shapes\n * (ids `<group id>~fx<n>`, placement kept): the geometry booleans, the Pathfinder, the Shape\n * Builder and the paint bucket work with. The node itself when it holds no mask.\n */\nexport function vectorMaskedGeometry(node: VectorNode): VectorNode {\n\tif (node.type !== 'group') return node;\n\tif (isVectorMaskActive(node)) {\n\t\treturn {\n\t\t\tid: node.id,\n\t\t\ttype: 'group',\n\t\t\t...(node.transform ? { transform: node.transform } : {}),\n\t\t\t...(node.opacity !== undefined ? { opacity: node.opacity } : {}),\n\t\t\t...(node.visible === false ? { visible: false } : {}),\n\t\t\t...(node.locked ? { locked: true } : {}),\n\t\t\tchildren: vectorAppearanceNodes(node)\n\t\t};\n\t}\n\tlet changed = false;\n\tconst children = node.children.map((c) => {\n\t\tconst next = vectorMaskedGeometry(c);\n\t\tif (next !== c) changed = true;\n\t\treturn next;\n\t});\n\treturn changed ? { ...node, children } : node;\n}\n\n/** Bounds of a mask group's masked result in its own space (stroke widths not included), or null. */\nexport function vectorMaskedLocalBounds(group: VectorMaskGroup): VectorBounds | null {\n\tconst b = bezierPathBounds(vectorAppearanceShapes(group).flatMap((s) => s.path));\n\treturn b ? { x: b.minX, y: b.minY, width: b.maxX - b.minX, height: b.maxY - b.minY } : null;\n}\n\n// ---------------------------------------------------------------------------\n// Render data\n// ---------------------------------------------------------------------------\n\n/** How far anything inside a node draws past its geometry: strokes, and filters on the way down. */\nfunction paintReach(node: VectorNode): number {\n\tconst own = vectorFilterReach(activeVectorFilters(node));\n\tif (node.type === 'path') return own + vectorStrokeStackReach(node);\n\treturn own + Math.max(0, ...node.children.map(paintReach));\n}\n\n/**\n * The box a mask group's contents can draw over, in its own space (strokes and filters included,\n * with a margin): the `<mask>` region, the filter region of an inverted opacity mask and the\n * rectangle an inverted clip cuts the mask out of. Null without contents.\n */\nexport function vectorMaskContentBounds(group: VectorMaskGroup): VectorBounds | null {\n\tconst contents = group.children.slice(1);\n\tconst b = unionBounds(contents.map((c) => vectorNodeBounds(c, IDENTITY_MATRIX)));\n\tif (!b) return null;\n\tconst pad = Math.max(0, ...contents.map(paintReach)) + Math.max(b.width, b.height) * 0.05 + 4;\n\treturn { x: b.x - pad, y: b.y - pad, width: b.width + 2 * pad, height: b.height + 2 * pad };\n}\n\n/** One path of a clipping mask's `<clipPath>` (group space). */\nexport interface VectorMaskClipShape {\n\td: string;\n\tclipRule: VectorFillRule;\n}\n\n/**\n * How to draw a mask group's mask, in the group's own space. Draw the group's own `<g>` (transform,\n * opacity, blend mode, filter) holding an inner `<g>` with the contents, referencing:\n * - `clip`: a `<clipPath id>` holding each of `clip` as `<path d clip-rule>`;\n * - `alpha` / `luminance`: a `<mask id maskUnits=\"userSpaceOnUse\" x y width height>` over\n * `bounds` (with `mask-type=\"alpha\"` for alpha) holding the mask node as drawn, wrapped in\n * `<g filter={filter}>` when `filter` is set (an inverted mask).\n */\nexport interface VectorMaskRenderData {\n\ttype: VectorMaskType;\n\tinvert: boolean;\n\t/** Id of the `<clipPath>` or `<mask>` element. */\n\tid: string;\n\t/** Clip shapes (clipping masks). An inverted clip is one even-odd shape: a rectangle with the mask's outline cut out. */\n\tclip?: VectorMaskClipShape[];\n\t/** Region of the `<mask>` (opacity masks). */\n\tbounds?: VectorBounds;\n\t/** `url(#id)` of the inverting filter (inverted opacity masks; in `filters`). */\n\tfilter?: string;\n\t/** The inverting filter itself (inverted opacity masks). */\n\tinvertFilter?: VectorRenderFilter;\n}\n\nconst fe = (tag: string, attrs: Record<string, string | number>): VectorFilterPrimitive => ({ tag, attrs });\nconst LUMA = '-0.2125 -0.7154 -0.0721 0 1';\n\n/** The filter that inverts an opacity mask over `bounds`: alpha → 1 − alpha, or brightness → 1 − brightness over black. */\nfunction invertFilter(type: 'alpha' | 'luminance', id: string, bounds: VectorBounds): VectorRenderFilter {\n\tconst primitives =\n\t\ttype === 'alpha'\n\t\t\t? [fe('feColorMatrix', { in: 'SourceGraphic', type: 'matrix', values: '0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 1' })]\n\t\t\t: [\n\t\t\t\t\t// Over black first, so a transparent area reads as dark (hidden) before inverting.\n\t\t\t\t\tfe('feFlood', { 'flood-color': '#000000', result: 'black' }),\n\t\t\t\t\tfe('feComposite', { in: 'SourceGraphic', in2: 'black', operator: 'over', result: 'flat' }),\n\t\t\t\t\tfe('feColorMatrix', { in: 'flat', type: 'matrix', values: `${LUMA} ${LUMA} ${LUMA} 0 0 0 0 1` })\n\t\t\t\t];\n\tconst r = (n: number) => Math.round(n * 1000) / 1000;\n\treturn { id, x: r(bounds.x), y: r(bounds.y), width: r(bounds.width), height: r(bounds.height), primitives };\n}\n\nconst rectPath = (b: VectorBounds): BezierPath => [\n\t{ type: 'M', x: b.x, y: b.y },\n\t{ type: 'L', x: b.x + b.width, y: b.y },\n\t{ type: 'L', x: b.x + b.width, y: b.y + b.height },\n\t{ type: 'L', x: b.x, y: b.y + b.height },\n\t{ type: 'Z' }\n];\n\n/**\n * A mask group's mask as render data with element id `id` (and `filterId` for an inverting\n * filter), or null when the mask is off or the group has no contents. Shared by the canvases and\n * SVG export.\n */\nexport function vectorMaskRenderData(group: VectorMaskGroup, id: string, filterId: string, precision = 3): VectorMaskRenderData | null {\n\tif (!isVectorMaskActive(group) || group.children.length < 2) return null;\n\tconst invert = !!group.mask.invert;\n\tconst bounds = vectorMaskContentBounds(group);\n\tif (group.mask.type === 'clip') {\n\t\tconst shapes = vectorMaskRegion(group);\n\t\tif (!invert) return { type: 'clip', invert, id, clip: shapes.map((s) => ({ d: bezierPathToSvg(s.path, { precision }), clipRule: s.fillRule })) };\n\t\t// Inverted (pdfcraft `clip_out`): a rectangle round the contents with the mask's union cut out, even-odd.\n\t\tconst box = bounds ?? { x: 0, y: 0, width: 0, height: 0 };\n\t\tconst region = vectorMaskRegionPath(group);\n\t\treturn { type: 'clip', invert, id, clip: [{ d: bezierPathToSvg([...rectPath(box), ...region], { precision }), clipRule: 'evenodd' }] };\n\t}\n\tif (!bounds) return null;\n\tif (!invert) return { type: group.mask.type, invert, id, bounds };\n\tconst filter = invertFilter(group.mask.type, filterId, bounds);\n\treturn { type: group.mask.type, invert, id, bounds, filter: `url(#${filterId})`, invertFilter: filter };\n}\n","/**\n * Warp geometry shared by the vector editor's envelopes and the image editor's Free Transform\n * warp: preset warp styles and editable Bézier meshes, both forward maps from a source box onto\n * the plane.\n *\n * - **Presets** (`WarpStyle`, Photoshop's fifteen with bend and horizontal / vertical distortion\n * in percent): each is one bicubic Bézier patch whose 4 × 4 control grid follows the bend\n * (`warpPresetGrid`). Every preset is the identity at bend 0 and continuous in it.\n * - **Meshes** (`WarpMesh`): a grid of bicubic patches. Splitting a mesh (`splitWarpMeshU` / `V`)\n * is an exact de Casteljau subdivision, so it never changes the shape, and a preset turns into\n * an editable mesh of any size exactly.\n *\n * Ported from ArtCraft (MIT OR Apache-2.0, © ArtCraft Team and contributors; see\n * THIRD_PARTY_NOTICES.md): photocraft `crates/geom/src/warp.rs` (`WarpStyle`, `StyleWarp`,\n * `rest_grid`, `edge_arc`, `arc_grid`, `blend_rows`, `preset_grid`, `bernstein`, `split_cubic`,\n * `BERN_INV`, and `BezierMesh`: `identity`, `fit`, `eval`, `split_u`, `split_v`, `remove_split_u`,\n * `transpose`, `map_points`, `param_at`, `pull`, `smooth_lines`, `drag_point`, `control_bounds`;\n * `Warp::map` and `Warp::to_mesh`).\n */\nimport type { Box, Vec2, WarpMesh, WarpStyle } from './types';\n\nexport type { WarpMesh, WarpStyle };\n\ntype P = [number, number];\n/** A single patch's control grid, `[row][column]`, in box units (0–1, y down). */\ntype Grid = P[][];\n\n/** The fifteen presets in Photoshop's menu order. */\nexport const WARP_STYLES: readonly WarpStyle[] = [\n 'arc',\n 'arcLower',\n 'arcUpper',\n 'arch',\n 'bulge',\n 'shellLower',\n 'shellUpper',\n 'flag',\n 'wave',\n 'fish',\n 'rise',\n 'fisheye',\n 'inflate',\n 'squeeze',\n 'twist'\n];\n\nexport const WARP_STYLE_LABELS: Readonly<Record<WarpStyle, string>> = {\n arc: 'Arc',\n arcLower: 'Arc Lower',\n arcUpper: 'Arc Upper',\n arch: 'Arch',\n bulge: 'Bulge',\n shellLower: 'Shell Lower',\n shellUpper: 'Shell Upper',\n flag: 'Flag',\n wave: 'Wave',\n fish: 'Fish',\n rise: 'Rise',\n fisheye: 'Fisheye',\n inflate: 'Inflate',\n squeeze: 'Squeeze',\n twist: 'Twist'\n};\n\n/** The rest grid (no warp). */\nfunction restGrid(): Grid {\n return [0, 1, 2, 3].map((j) => [0, 1, 2, 3].map((i): P => [i / 3, j / 3]));\n}\n\n/**\n * A horizontal edge at height `y` (box units, 0–1 across) bent into a circular arc of `|b|·π`\n * that keeps its chord, bowing up when `up === (b > 0)`. `h` is the box's height over its width,\n * so the arc is circular in pixels.\n */\nfunction edgeArc(y: number, b: number, up: boolean, h: number): P[] {\n if (Math.abs(b) < 1e-9) return [0, 1, 2, 3].map((i): P => [i / 3, y]);\n const th = Math.abs(b) * Math.PI;\n const k = (((4 / 3) * Math.tan(th / 4)) * 0.5) / Math.sin(th / 2);\n const s = b > 0 === up ? -1 : 1;\n const c = Math.cos(th / 2);\n const n = Math.sin(th / 2);\n const dy = (s * k * n) / h;\n return [\n [0, y],\n [k * c, y + dy],\n [1 - k * c, y + dy],\n [1, y]\n ];\n}\n\n/**\n * Arc: every row is a circular arc of `|b|·π` around one centre; the edge on the inside of the\n * bend keeps its chord and the rows' radii grow by the box height towards the other edge. Worked\n * in units of the box width (`h` = height / width) so the arcs are circular in pixels.\n */\nfunction arcGrid(b: number, h: number): Grid {\n if (Math.abs(b) < 1e-9) return restGrid();\n const up = b > 0;\n const th = Math.abs(b) * Math.PI;\n const r = 0.5 / Math.sin(th / 2);\n const k = (4 / 3) * Math.tan(th / 4);\n const s = up ? -1 : 1;\n const cy = up ? h + r * Math.cos(th / 2) : -r * Math.cos(th / 2);\n return [0, 1, 2, 3].map((j) => {\n const v = j / 3;\n const big = r + h * (up ? 1 - v : v);\n const at = (a: number): P => [0.5 + big * Math.sin(a), cy + s * big * Math.cos(a)];\n const tangent = (a: number): P => [Math.cos(a), -s * Math.sin(a)];\n const p0 = at(-th / 2);\n const p3 = at(th / 2);\n const t0 = tangent(-th / 2);\n const t1 = tangent(th / 2);\n const l = k * big;\n const pts: P[] = [p0, [p0[0] + l * t0[0], p0[1] + l * t0[1]], [p3[0] - l * t1[0], p3[1] - l * t1[1]], p3];\n return pts.map((p): P => [p[0], p[1] / h]);\n });\n}\n\n/** Rows blended from `top` to `bottom`. */\nfunction blendRows(top: P[], bottom: P[]): Grid {\n return [0, 1, 2, 3].map((j) => {\n const t = j / 3;\n return [0, 1, 2, 3].map((i): P => [top[i][0] + (bottom[i][0] - top[i][0]) * t, top[i][1] + (bottom[i][1] - top[i][1]) * t]);\n });\n}\n\nconst INNER: [number, number, number, number][] = [\n [1, 1, -1, -1],\n [1, 2, 1, -1],\n [2, 1, -1, 1],\n [2, 2, 1, 1]\n];\n\n/**\n * A preset as a Bézier control grid (rows of `[x, y]` in box units, y down). `b`, `hd`, `vd` are\n * the bend and the horizontal / vertical distortion as fractions (−1…1); `aspect` is the box's\n * height over its width. The arc family stays circular in pixels, the other offsets scale with the\n * box, and a vertical warp is the horizontal one with the axes (and distortions) swapped.\n */\nexport function warpPresetGrid(style: WarpStyle, b: number, hd: number, vd: number, vertical: boolean, aspect: number): [number, number][][] {\n // Height over width of the box the bend runs along (the transposed box when vertical); in that\n // frame the two distortions trade places too.\n const h = vertical ? 1 / aspect : aspect;\n if (vertical) [hd, vd] = [vd, hd];\n let g = restGrid();\n switch (style) {\n case 'arc':\n g = arcGrid(b, h);\n break;\n case 'arch':\n g = [0, 1, 2, 3].map((j) => edgeArc(j / 3, b, true, h));\n break;\n case 'bulge':\n g = blendRows(edgeArc(0, b, true, h), edgeArc(1, b, false, h));\n break;\n case 'arcLower':\n g = blendRows(g[0], edgeArc(1, b, false, h));\n break;\n case 'arcUpper':\n g = blendRows(edgeArc(0, b, true, h), g[3]);\n break;\n // The bulging edge and the outer points of the row next to it come from Arc (bent the other\n // way for Shell Lower); the rest stays put.\n case 'shellLower': {\n const a = arcGrid(-b, h);\n g[3] = a[3];\n g[2][0] = a[2][0];\n g[2][3] = a[2][3];\n break;\n }\n case 'shellUpper': {\n const a = arcGrid(b, h);\n g[0] = a[0];\n g[1][0] = a[1][0];\n g[1][3] = a[1][3];\n break;\n }\n case 'flag':\n for (const row of g) {\n row[1][1] -= 2 * b;\n row[2][1] += 2 * b;\n }\n break;\n case 'wave':\n for (const row of g.slice(1, 3)) {\n row[1][1] += (4 / 3) * b;\n row[2][1] -= (4 / 3) * b;\n }\n break;\n case 'fish':\n [-2, -2 / 3, 2 / 3, 2].forEach((f, j) => {\n g[j][1][1] += f * b;\n g[j][2][1] -= f * b;\n });\n break;\n case 'rise':\n for (const row of g) {\n row[0][1] += 2 * b;\n row[1][1] += 2 * b;\n }\n break;\n case 'fisheye':\n for (const [j, i, dx, dy] of INNER) {\n g[j][i][0] += (dx * 2 * b) / 3;\n g[j][i][1] += (dy * 2 * b) / 3;\n }\n break;\n // Edge midpoints move out (Inflate) or the sides in (Squeeze) by b/3, the inner points by b/9.\n case 'inflate':\n case 'squeeze': {\n const s = style === 'inflate' ? 1 : -1;\n for (const p of g[0].slice(1, 3)) p[1] -= b / 3;\n for (const p of g[3].slice(1, 3)) p[1] += b / 3;\n for (const row of g.slice(1, 3)) {\n row[0][0] -= (s * b) / 3;\n row[3][0] += (s * b) / 3;\n }\n for (const [j, i, dx, dy] of INNER) {\n g[j][i][0] += (s * dx * b) / 9;\n g[j][i][1] += (dy * b) / 9;\n }\n break;\n }\n // The inner points turn round the centre (the other way for a negative bend).\n case 'twist': {\n const a = Math.abs(b);\n if (b >= 0) {\n g[1][1][0] += a;\n g[1][2][1] += a;\n g[2][1][1] -= a;\n g[2][2][0] -= a;\n } else {\n g[1][1][1] += a;\n g[1][2][0] -= a;\n g[2][1][0] += a;\n g[2][2][1] -= a;\n }\n break;\n }\n }\n // Vertical distortion: the top and bottom rows scale about their end points' midpoint (by\n // 1 ∓ vd) and the middle rows follow by the blend of those two moves.\n if (vd !== 0) {\n const moved = (row: P[], s: number): P[] => {\n const m: P = [(row[0][0] + row[3][0]) / 2, (row[0][1] + row[3][1]) / 2];\n return row.map((p): P => [m[0] + (p[0] - m[0]) * s - p[0], m[1] + (p[1] - m[1]) * s - p[1]]);\n };\n const d0 = moved(g[0], 1 - vd);\n const d3 = moved(g[3], 1 + vd);\n g.forEach((row, j) => {\n const t = j / 3;\n row.forEach((p, i) => {\n p[0] += d0[i][0] + (d3[i][0] - d0[i][0]) * t;\n p[1] += d0[i][1] + (d3[i][1] - d0[i][1]) * t;\n });\n });\n }\n // Horizontal distortion: each column scales about its end points' midpoint by 1 + hd·(2i/3 − 1).\n if (hd !== 0) {\n for (let i = 0; i < 4; i++) {\n const s = 1 + hd * ((2 * i) / 3 - 1);\n const m: P = [(g[0][i][0] + g[3][i][0]) / 2, (g[0][i][1] + g[3][i][1]) / 2];\n for (const row of g) row[i] = [m[0] + (row[i][0] - m[0]) * s, m[1] + (row[i][1] - m[1]) * s];\n }\n }\n // Vertical orientation: the same grid with the axes swapped.\n if (vertical) g = [0, 1, 2, 3].map((j) => [0, 1, 2, 3].map((i): P => [g[i][j][1], g[i][j][0]]));\n return g;\n}\n\nfunction bernstein(t: number): [number, number, number, number] {\n const s = 1 - t;\n return [s * s * s, 3 * s * s * t, 3 * s * t * t, t * t * t];\n}\n\nexport const lerpVec2 = (a: Vec2, b: Vec2, t: number): Vec2 => ({ x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t });\n\n/** De Casteljau split of a cubic at `t`: 7 points (left 0..3, right 3..6). */\nfunction splitCubic(p: readonly Vec2[], t: number): Vec2[] {\n const a = lerpVec2(p[0], p[1], t);\n const b = lerpVec2(p[1], p[2], t);\n const c = lerpVec2(p[2], p[3], t);\n const d = lerpVec2(a, b, t);\n const e = lerpVec2(b, c, t);\n return [p[0], a, d, lerpVec2(d, e, t), e, c, p[3]];\n}\n\n/** Inverse of the Bernstein interpolation matrix at t = 0, ⅓, ⅔, 1 (rows: control point, columns: sample). */\nconst BERN_INV = [\n [1, 0, 0, 0],\n [-5 / 6, 3, -1.5, 1 / 3],\n [1 / 3, -1.5, 3, -5 / 6],\n [0, 0, 0, 1]\n];\n\n// ---------------------------------------------------------------------------\n// Presets\n// ---------------------------------------------------------------------------\n\n/** A preset warp's settings (bend and distortions in percent, −100…100). */\nexport interface WarpPreset {\n style: WarpStyle;\n bend: number;\n horizontal?: number;\n vertical?: number;\n /** Bend along the vertical axis. */\n orientation?: 'horizontal' | 'vertical';\n}\n\nconst pct = (v: number | undefined) => (typeof v === 'number' && Number.isFinite(v) ? Math.min(1, Math.max(-1, v / 100)) : 0);\n\n/**\n * A preset as one Bézier patch over `bounds` (points in the bounds' space), or null when it\n * changes nothing (an unknown style, all-zero amounts, or an empty box).\n */\nexport function warpPresetMesh(preset: WarpPreset, bounds: Box): WarpMesh | null {\n if (!WARP_STYLES.includes(preset.style)) return null;\n const { x, y, width: w, height: h } = bounds;\n if (!(w > 0 && h > 0)) return null;\n const b = pct(preset.bend);\n const hd = pct(preset.horizontal);\n const vd = pct(preset.vertical);\n if (b === 0 && hd === 0 && vd === 0) return null;\n const grid = warpPresetGrid(preset.style, b, hd, vd, preset.orientation === 'vertical', h / w);\n return { us: [0, 1], vs: [0, 1], points: grid.flat().map((p) => ({ x: x + p[0] * w, y: y + p[1] * h })) };\n}\n\n// ---------------------------------------------------------------------------\n// Meshes\n// ---------------------------------------------------------------------------\n\n/** Control points per row. */\nexport const warpMeshColumns = (m: WarpMesh) => 3 * (m.us.length - 1) + 1;\n/** Control point rows. */\nexport const warpMeshRows = (m: WarpMesh) => 3 * (m.vs.length - 1) + 1;\n\n/** Whether a mesh is well formed: knots from 0 to 1 increasing, the right number of finite points. */\nexport function isValidWarpMesh(m: unknown): m is WarpMesh {\n if (!m || typeof m !== 'object') return false;\n const { us, vs, points } = m as WarpMesh;\n const knots = (k: unknown): k is number[] =>\n Array.isArray(k) && k.length >= 2 && k.length <= 65 && k[0] === 0 && k[k.length - 1] === 1 && k.every((v, i) => typeof v === 'number' && (i === 0 || v > k[i - 1]));\n if (!knots(us) || !knots(vs) || !Array.isArray(points)) return false;\n return points.length === (3 * (us.length - 1) + 1) * (3 * (vs.length - 1) + 1) && points.every((p) => !!p && Number.isFinite(p.x) && Number.isFinite(p.y));\n}\n\n/** Fits a mesh with patch boundaries `us` / `vs` to the map `f` (box fractions → output) by interpolating it at each patch's thirds. Exact for bicubic maps (affine maps included). */\nexport function fitWarpMesh(f: (s: number, t: number) => Vec2, us: readonly number[], vs: readonly number[]): WarpMesh {\n const pc = us.length - 1;\n const pr = vs.length - 1;\n const nx = 3 * pc + 1;\n const points: Vec2[] = new Array((3 * pr + 1) * nx);\n for (let pj = 0; pj < pr; pj++) {\n for (let pi = 0; pi < pc; pi++) {\n const s: Vec2[][] = [0, 1, 2, 3].map((j) =>\n [0, 1, 2, 3].map((i) => f(us[pi] + ((us[pi + 1] - us[pi]) * i) / 3, vs[pj] + ((vs[pj + 1] - vs[pj]) * j) / 3))\n );\n for (let j = 0; j < 4; j++) {\n for (let i = 0; i < 4; i++) {\n let x = 0;\n let y = 0;\n for (let a = 0; a < 4; a++) {\n for (let b = 0; b < 4; b++) {\n const k = BERN_INV[j][a] * BERN_INV[i][b];\n x += k * s[a][b].x;\n y += k * s[a][b].y;\n }\n }\n points[(3 * pj + j) * nx + 3 * pi + i] = { x, y };\n }\n }\n }\n }\n return { us: us.slice(), vs: vs.slice(), points };\n}\n\n/** `n + 1` evenly spaced knots from 0 to 1. */\nexport const evenKnots = (n: number) => Array.from({ length: n + 1 }, (_, i) => i / n);\n/** A patch count rounded and clamped to 1–64. */\nexport const clampMeshCount = (n: number) => Math.min(64, Math.max(1, Math.round(Number.isFinite(n) ? n : 1)));\n\n/** The identity mesh over `bounds` with `columns × rows` patches. */\nexport function identityWarpMesh(bounds: Box, columns = 1, rows = 1): WarpMesh {\n return fitWarpMesh((s, t) => ({ x: bounds.x + s * bounds.width, y: bounds.y + t * bounds.height }), evenKnots(clampMeshCount(columns)), evenKnots(clampMeshCount(rows)));\n}\n\n/**\n * The patch holding box fraction `s` and the parameter inside it. Outside 0–1 the end patches\n * extrapolate (their polynomials continue), so handles past the box map smoothly.\n */\nfunction locate(knots: readonly number[], s: number): [number, number] {\n const n = knots.length - 1;\n let i = 0;\n while (i + 1 < n && s > knots[i + 1]) i++;\n const w = knots[i + 1] - knots[i];\n return [i, w > 0 ? (s - knots[i]) / w : 0];\n}\n\n/** The surface at box fractions `(s, t)`. */\nexport function evalWarpMesh(m: WarpMesh, s: number, t: number): Vec2 {\n const [pi, a] = locate(m.us, s);\n const [pj, b] = locate(m.vs, t);\n const ba = bernstein(a);\n const bb = bernstein(b);\n const nx = warpMeshColumns(m);\n let x = 0;\n let y = 0;\n for (let j = 0; j < 4; j++) {\n for (let i = 0; i < 4; i++) {\n const p = m.points[(3 * pj + j) * nx + 3 * pi + i];\n const k = ba[i] * bb[j];\n x += p.x * k;\n y += p.y * k;\n }\n }\n return { x, y };\n}\n\nfunction transposeMesh(m: WarpMesh): WarpMesh {\n const nx = warpMeshColumns(m);\n const ny = warpMeshRows(m);\n const points: Vec2[] = new Array(nx * ny);\n for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) points[i * ny + j] = m.points[j * nx + i];\n return { us: m.vs.slice(), vs: m.us.slice(), points };\n}\n\n/** The mesh with the patch column holding `s` split at `s` (exact). Null when `s` is on or too close to a boundary. */\nexport function splitWarpMeshU(m: WarpMesh, s: number): WarpMesh | null {\n const [pi, a] = locate(m.us, s);\n if (!(a >= 0.01 && a <= 0.99)) return null;\n const nx = warpMeshColumns(m);\n const ny = warpMeshRows(m);\n const points: Vec2[] = [];\n for (let j = 0; j < ny; j++) {\n const row = m.points.slice(j * nx, (j + 1) * nx);\n points.push(...row.slice(0, 3 * pi), ...splitCubic(row.slice(3 * pi, 3 * pi + 4), a), ...row.slice(3 * pi + 4));\n }\n const us = m.us.slice();\n us.splice(pi + 1, 0, Math.min(1, Math.max(0, s)));\n return { us, vs: m.vs.slice(), points };\n}\n\n/** The mesh with the patch row holding `t` split at `t` (exact). */\nexport function splitWarpMeshV(m: WarpMesh, t: number): WarpMesh | null {\n const out = splitWarpMeshU(transposeMesh(m), t);\n return out && transposeMesh(out);\n}\n\n/**\n * The mesh without interior vertical boundary `k` (1 … us.length − 2), its two patch columns\n * merged: exact when they came from an unedited split; otherwise the outer control points stay and\n * the inner handles are extrapolated.\n */\nexport function removeWarpMeshSplitU(m: WarpMesh, k: number): WarpMesh | null {\n if (k <= 0 || k + 1 >= m.us.length) return null;\n const a = (m.us[k] - m.us[k - 1]) / (m.us[k + 1] - m.us[k - 1]);\n const nx = warpMeshColumns(m);\n const ny = warpMeshRows(m);\n const c0 = 3 * (k - 1);\n const points: Vec2[] = [];\n for (let j = 0; j < ny; j++) {\n const row = m.points.slice(j * nx, (j + 1) * nx);\n const [p0, q1, r2, p3] = [row[c0], row[c0 + 1], row[c0 + 5], row[c0 + 6]];\n // De Casteljau inverse: q1 = lerpVec2(p0, p1, a), r2 = lerpVec2(p2, p3, a).\n const p1 = { x: (q1.x - (1 - a) * p0.x) / a, y: (q1.y - (1 - a) * p0.y) / a };\n const p2 = { x: (r2.x - a * p3.x) / (1 - a), y: (r2.y - a * p3.y) / (1 - a) };\n points.push(...row.slice(0, c0), p0, p1, p2, p3, ...row.slice(c0 + 7));\n }\n const us = m.us.slice();\n us.splice(k, 1);\n return { us, vs: m.vs.slice(), points };\n}\n\n/** Removes interior horizontal boundary `k`. */\nexport function removeWarpMeshSplitV(m: WarpMesh, k: number): WarpMesh | null {\n const out = removeWarpMeshSplitU(transposeMesh(m), k);\n return out && transposeMesh(out);\n}\n\n/** Every control point through `f` (exact for affine maps). */\nexport function mapWarpMeshPoints(m: WarpMesh, f: (p: Vec2) => Vec2): WarpMesh {\n return { us: m.us.slice(), vs: m.vs.slice(), points: m.points.map((p) => f(p)) };\n}\n\n/**\n * The mesh with `columns × rows` patches over the same surface: split exactly when its knots are\n * a subset of the new even ones (a one-patch mesh always is), otherwise refitted.\n */\nexport function resizeWarpMesh(m: WarpMesh, columns: number, rows: number): WarpMesh {\n const cols = clampMeshCount(columns);\n const rws = clampMeshCount(rows);\n if (m.us.length - 1 === cols && m.vs.length - 1 === rws) return m;\n const us = evenKnots(cols);\n const vs = evenKnots(rws);\n const has = (list: number[], v: number) => list.some((k) => Math.abs(k - v) < 1e-12);\n if (m.us.every((u) => has(us, u)) && m.vs.every((v) => has(vs, v))) {\n let out: WarpMesh | null = m;\n for (const u of us) if (!has(out.us, u)) out = splitWarpMeshU(out, u) ?? out;\n for (const v of vs) if (!has(out.vs, v)) out = splitWarpMeshV(out, v) ?? out;\n return out;\n }\n return fitWarpMesh((s, t) => evalWarpMesh(m, s, t), us, vs);\n}\n\n/** Bounding box of the control points (the surface lies inside it). */\nexport function warpMeshControlBounds(m: WarpMesh): Box {\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n for (const p of m.points) {\n minX = Math.min(minX, p.x);\n minY = Math.min(minY, p.y);\n maxX = Math.max(maxX, p.x);\n maxY = Math.max(maxY, p.y);\n }\n return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };\n}\n\n/** Box fractions `(s, t)` whose surface point is nearest `p` (a coarse search, then Newton steps). */\nexport function warpMeshParamAt(m: WarpMesh, p: Vec2): { s: number; t: number; distance: number } {\n const n = 48;\n let best = { s: 0.5, t: 0.5, d: Infinity };\n for (let j = 0; j <= n; j++) {\n for (let i = 0; i <= n; i++) {\n const q = evalWarpMesh(m, i / n, j / n);\n const d = (q.x - p.x) ** 2 + (q.y - p.y) ** 2;\n if (d < best.d) best = { s: i / n, t: j / n, d };\n }\n }\n let { s, t } = best;\n for (let k = 0; k < 12; k++) {\n const h = 1e-5;\n const q = evalWarpMesh(m, s, t);\n const qs = evalWarpMesh(m, s + h, t);\n const qt = evalWarpMesh(m, s, t + h);\n const a = (qs.x - q.x) / h;\n const b = (qt.x - q.x) / h;\n const c = (qs.y - q.y) / h;\n const d = (qt.y - q.y) / h;\n const det = a * d - b * c;\n if (Math.abs(det) < 1e-12) break;\n const ex = p.x - q.x;\n const ey = p.y - q.y;\n s = Math.min(1, Math.max(0, s + (d * ex - b * ey) / det));\n t = Math.min(1, Math.max(0, t + (a * ey - c * ex) / det));\n }\n const q = evalWarpMesh(m, s, t);\n return { s, t, distance: Math.hypot(q.x - p.x, q.y - p.y) };\n}\n\n/**\n * Makes the tangent equal on both sides of every interior grid line for the control points in\n * columns `i0..i1` and rows `j0..j1` (exclusive ends): each pair of handles takes the average of\n * the two tangents it had. In place.\n */\nfunction smoothLines(m: WarpMesh, i0: number, i1: number, j0: number, j1: number) {\n const nx = warpMeshColumns(m);\n i1 = Math.min(i1, nx);\n j1 = Math.min(j1, warpMeshRows(m));\n const triples: [number, number, number, number, number][] = [];\n for (let a = 1; a < m.us.length - 1; a++) {\n if (3 * a >= i0 && 3 * a < i1)\n for (let j = j0; j < j1; j++) triples.push([j * nx + 3 * a - 1, j * nx + 3 * a, j * nx + 3 * a + 1, m.us[a] - m.us[a - 1], m.us[a + 1] - m.us[a]]);\n }\n for (let b = 1; b < m.vs.length - 1; b++) {\n if (3 * b >= j0 && 3 * b < j1)\n for (let i = i0; i < i1; i++) triples.push([(3 * b - 1) * nx + i, 3 * b * nx + i, (3 * b + 1) * nx + i, m.vs[b] - m.vs[b - 1], m.vs[b + 1] - m.vs[b]]);\n }\n for (const [l, c, r, hl, hr] of triples) {\n const pl = m.points[l];\n const pc = m.points[c];\n const pr = m.points[r];\n const tx = ((pc.x - pl.x) / hl + (pr.x - pc.x) / hr) / 2;\n const ty = ((pc.y - pl.y) / hl + (pr.y - pc.y) / hr) / 2;\n m.points[l] = { x: pc.x - tx * hl, y: pc.y - ty * hl };\n m.points[r] = { x: pc.x + tx * hr, y: pc.y + ty * hr };\n }\n}\n\n/**\n * `base` with control point `index` dragged by `d`, keeping the surface smooth across the grid\n * lines: an anchor moves with the eight points around it as one block; a handle moves with the two\n * points beside it across its line, and the handle opposite it on the same anchor turns the other\n * way (with its two neighbours), so the line keeps passing straight through the anchor. An inner\n * point of a patch moves alone.\n */\nexport function dragWarpMeshPoint(base: WarpMesh, index: number, d: Vec2): WarpMesh {\n if (index < 0 || index >= base.points.length || !Number.isFinite(d.x) || !Number.isFinite(d.y)) return base;\n const out: WarpMesh = { us: base.us.slice(), vs: base.vs.slice(), points: base.points.slice() };\n const nx = warpMeshColumns(base);\n const ny = warpMeshRows(base);\n const i = index % nx;\n const j = Math.floor(index / nx);\n const shift = (ii: number, jj: number, v: Vec2) => {\n if (ii < 0 || jj < 0 || ii >= nx || jj >= ny) return;\n const p = out.points[jj * nx + ii];\n out.points[jj * nx + ii] = { x: p.x + v.x, y: p.y + v.y };\n };\n // Spans either side of interior knot `k`.\n const span = (knots: number[], k: number): [number, number] | null => (k > 0 && k + 1 < knots.length ? [knots[k] - knots[k - 1], knots[k + 1] - knots[k]] : null);\n const ri = i % 3;\n const rj = j % 3;\n if (ri === 0 && rj === 0) {\n for (let dj = -1; dj <= 1; dj++) for (let di = -1; di <= 1; di++) shift(i + di, j + dj, d);\n } else if (ri === 0) {\n // A handle along a vertical line: it takes the two points beside it across the line.\n for (let di = -1; di <= 1; di++) shift(i + di, j, d);\n // The opposite handle of the same anchor turns the other way.\n const sp = span(base.vs, Math.floor(j / 3) + (rj === 2 ? 1 : 0));\n if (sp) {\n const [other, k] = rj === 1 ? [j - 2, sp[0] / sp[1]] : [j + 2, sp[1] / sp[0]];\n for (let di = -1; di <= 1; di++) shift(i + di, other, { x: -d.x * k, y: -d.y * k });\n }\n } else if (rj === 0) {\n // A handle along a horizontal line, likewise.\n for (let dj = -1; dj <= 1; dj++) shift(i, j + dj, d);\n const sp = span(base.us, Math.floor(i / 3) + (ri === 2 ? 1 : 0));\n if (sp) {\n const [other, k] = ri === 1 ? [i - 2, sp[0] / sp[1]] : [i + 2, sp[1] / sp[0]];\n for (let dj = -1; dj <= 1; dj++) shift(other, j + dj, { x: -d.x * k, y: -d.y * k });\n }\n } else shift(i, j, d);\n return out;\n}\n\n/**\n * `base` with its surface point at box fractions `(s, t)` pulled by `d`, the way dragging inside a\n * patch works: interior anchors within about two cells follow by a share of `d` that fades with\n * distance (each with its block of handles, so grid lines stay smooth); the outer border stays\n * pinned unless the grab is near it, and then it bows; the four corners never move. The grabbed\n * patch's inner points (and, near the border, the border's handles) make up the rest, so the\n * grabbed point lands exactly at its start + `d`.\n */\nexport function pullWarpMesh(base: WarpMesh, s: number, t: number, d: Vec2): WarpMesh {\n /** Within this distance of the border (box fractions) a grab starts to drag the border with it. */\n const BORDER_ZONE = 0.12;\n /** Falloff radius, in the grabbed patch's size. */\n const REACH = 1.8;\n if (!Number.isFinite(d.x) || !Number.isFinite(d.y)) return base;\n const m: WarpMesh = { us: base.us.slice(), vs: base.vs.slice(), points: base.points.slice() };\n const cols = m.us.length - 1;\n const rows = m.vs.length - 1;\n const [pi, a] = locate(m.us, s);\n const [pj, b] = locate(m.vs, t);\n const ba = bernstein(a);\n const bb = bernstein(b);\n const nx = warpMeshColumns(m);\n const ny = warpMeshRows(m);\n const anchor = (ai: number, aj: number) => base.points[3 * aj * nx + 3 * ai] ?? { x: 0, y: 0 };\n const at0 = evalWarpMesh(base, s, t);\n const target = { x: at0.x + d.x, y: at0.y + d.y };\n // The grabbed patch's size and how far inside it the grab is (1 in the middle, 0 on its edges).\n let size = 1;\n for (const k of ['x', 'y'] as const) {\n const vals = [anchor(pi, pj)[k], anchor(pi + 1, pj)[k], anchor(pi, pj + 1)[k], anchor(pi + 1, pj + 1)[k]];\n size = Math.max(size, Math.max(...vals) - Math.min(...vals));\n }\n const radius = REACH * size;\n const innerW = (ba[1] + ba[2]) * (bb[1] + bb[2]);\n const interior = Math.min(1, Math.max(0, innerW / 0.5625));\n const toBorder = Math.min(s, 1 - s, t, 1 - t);\n const nearBorder = Math.min(1, Math.max(0, 1 - toBorder / BORDER_ZONE));\n const meshCorner = (ai: number, aj: number) => (ai === 0 || ai === cols) && (aj === 0 || aj === rows);\n const onBorder = (ai: number, aj: number) => ai === 0 || ai === cols || aj === 0 || aj === rows;\n const reach = (ai: number, aj: number, wa: number, wb: number) => (meshCorner(ai, aj) ? 0 : wa * wb * (onBorder(ai, aj) ? nearBorder : 1));\n const corner: [number, number, number][] = [\n [pi, pj, reach(pi, pj, ba[0] + ba[1], bb[0] + bb[1])],\n [pi + 1, pj, reach(pi + 1, pj, ba[2] + ba[3], bb[0] + bb[1])],\n [pi, pj + 1, reach(pi, pj + 1, ba[0] + ba[1], bb[2] + bb[3])],\n [pi + 1, pj + 1, reach(pi + 1, pj + 1, ba[2] + ba[3], bb[2] + bb[3])]\n ];\n // Share of `d` for each anchor.\n const share = new Array((cols + 1) * (rows + 1)).fill(0);\n for (let aj = 0; aj <= rows; aj++) {\n for (let ai = 0; ai <= cols; ai++) {\n const p = anchor(ai, aj);\n const x = Math.min(1, Math.max(0, Math.hypot(p.x - at0.x, p.y - at0.y) / radius));\n const fall = 0.5 * (1 + Math.cos(Math.PI * x));\n const edge = meshCorner(ai, aj) ? 0 : onBorder(ai, aj) ? nearBorder : 1;\n share[aj * (cols + 1) + ai] = fall * edge;\n }\n }\n // The grabbed patch's own corners: near one, that corner follows the pointer.\n for (const [ai, aj, w] of corner) share[aj * (cols + 1) + ai] = Math.max(share[aj * (cols + 1) + ai], (1 - interior) * w);\n const move = (idx: number, k: number, v: Vec2) => {\n const p = m.points[idx];\n m.points[idx] = { x: p.x + v.x * k, y: p.y + v.y * k };\n };\n // Every control point moves with the anchor it is closest to.\n for (let j = 0; j < ny; j++) {\n for (let i = 0; i < nx; i++) {\n const ai = Math.min(cols, Math.floor((i + 1) / 3));\n const aj = Math.min(rows, Math.floor((j + 1) / 3));\n move(j * nx + i, share[aj * (cols + 1) + ai], d);\n }\n }\n // Close the gap exactly with three groups that share the work: the grabbed patch's four inner\n // points, the corner blocks, and (near the border) the border's own handles. Closing nudges the\n // tangents across the grid lines, so they are evened out again and the gap re-closed.\n let norm = 0;\n for (const j of [1, 2]) for (const i of [1, 2]) norm += (ba[i] * bb[j]) ** 2;\n const cornerNorm = corner.reduce((acc, c) => acc + c[2] * c[2], 0);\n // With no free corner to help (a one-patch grid grabbed away from its border) the inner points do all of it.\n const innerPart = cornerNorm > 1e-12 ? Math.min(1, innerW / 0.15) : 1;\n const edgeHandles: [number, number][] = [];\n for (const k of [1, 2]) {\n if (pi === 0) edgeHandles.push([(3 * pj + k) * nx + 3 * pi, ba[0] * bb[k]]);\n if (pi + 1 === cols) edgeHandles.push([(3 * pj + k) * nx + 3 * pi + 3, ba[3] * bb[k]]);\n if (pj === 0) edgeHandles.push([3 * pj * nx + 3 * pi + k, ba[k] * bb[0]]);\n if (pj + 1 === rows) edgeHandles.push([(3 * pj + 3) * nx + 3 * pi + k, ba[k] * bb[3]]);\n }\n const edgeNorm = edgeHandles.reduce((acc, e) => acc + e[1] * e[1], 0);\n const edgePart = edgeNorm > 1e-12 ? nearBorder : 0;\n const innerShare = (1 - edgePart) * innerPart;\n const cornerShare = (1 - edgePart) * (1 - innerPart);\n for (let iter = 0; iter < 60; iter++) {\n const now = evalWarpMesh(m, s, t);\n const rem = { x: target.x - now.x, y: target.y - now.y };\n if (Math.hypot(rem.x, rem.y) < 1e-9) break;\n if (innerShare > 0 && norm > 0) for (const j of [1, 2]) for (const i of [1, 2]) move((3 * pj + j) * nx + 3 * pi + i, ((ba[i] * bb[j]) / norm) * innerShare, rem);\n if (edgePart > 0) for (const [idx, w] of edgeHandles) move(idx, (w / edgeNorm) * edgePart, rem);\n if (cornerShare > 0 && cornerNorm > 0) {\n for (const [ai, aj, w] of corner) {\n const k = (w / cornerNorm) * cornerShare;\n for (let dj = -1; dj <= 1; dj++) {\n for (let di = -1; di <= 1; di++) {\n const i = 3 * ai + di;\n const j = 3 * aj + dj;\n if (i >= 0 && j >= 0 && i < nx && j < ny) move(j * nx + i, k, rem);\n }\n }\n }\n }\n for (let k = 0; k < 3; k++) smoothLines(m, Math.max(0, 3 * pi - 3), 3 * pi + 7, Math.max(0, 3 * pj - 3), 3 * pj + 7);\n }\n return m;\n}\n\n/**\n * The control points an editor shows: the anchors (where grid lines cross) and the handles along\n * the grid lines, each with the anchor it belongs to. Points inside a patch are left out (drag\n * inside a patch to pull the surface instead).\n */\nexport function warpMeshEditPoints(m: WarpMesh): { anchors: number[]; handles: { index: number; anchor: number }[] } {\n const nx = warpMeshColumns(m);\n const ny = warpMeshRows(m);\n const anchors: number[] = [];\n const handles: { index: number; anchor: number }[] = [];\n for (let j = 0; j < ny; j++) {\n for (let i = 0; i < nx; i++) {\n const ri = i % 3;\n const rj = j % 3;\n if (ri === 0 && rj === 0) anchors.push(j * nx + i);\n else if (ri === 0) handles.push({ index: j * nx + i, anchor: (rj === 1 ? j - 1 : j + 1) * nx + i });\n else if (rj === 0) handles.push({ index: j * nx + i, anchor: j * nx + (ri === 1 ? i - 1 : i + 1) });\n }\n }\n return { anchors, handles };\n}\n\n/** The mesh's grid lines (patch borders) as cubics `[p0, p1, p2, p3]`. */\nexport function warpMeshGridCurves(m: WarpMesh): Vec2[][] {\n const nx = warpMeshColumns(m);\n const ny = warpMeshRows(m);\n const pt = (i: number, j: number) => m.points[j * nx + i];\n const out: Vec2[][] = [];\n for (let j = 0; j < ny; j += 3) for (let i = 0; i + 3 < nx; i += 3) out.push([pt(i, j), pt(i + 1, j), pt(i + 2, j), pt(i + 3, j)]);\n for (let i = 0; i < nx; i += 3) for (let j = 0; j + 3 < ny; j += 3) out.push([pt(i, j), pt(i, j + 1), pt(i, j + 2), pt(i, j + 3)]);\n return out;\n}\n","/**\n * Warp geometry for envelope distortion: preset warp styles and editable Bézier meshes, both\n * forward maps from a source box (the bounds of the paths an envelope bends) to the node's space.\n * The maths is shared with the image editor's Free Transform and lives in `src/geom/warp.ts`;\n * these are its vector-named exports, plus the envelope-from-outline helpers.\n *\n * The Coons patch of `vectorMeshFromOutline` is our own.\n */\nimport {\n\tclampMeshCount,\n\tevenKnots,\n\tfitWarpMesh,\n\tlerpVec2,\n\twarpMeshColumns,\n\twarpMeshRows\n} from '../geom/warp.js';\nimport type { Vec2, VectorSubpath, VectorWarpMesh } from './types.js';\n\nexport {\n\tWARP_STYLES as VECTOR_WARP_STYLES,\n\tWARP_STYLE_LABELS as VECTOR_WARP_STYLE_LABELS,\n\twarpPresetGrid as vectorWarpPresetGrid,\n\twarpPresetMesh as vectorWarpPresetMesh,\n\twarpMeshColumns as vectorMeshColumns,\n\twarpMeshRows as vectorMeshRows,\n\tisValidWarpMesh as isValidVectorMesh,\n\tfitWarpMesh as fitVectorMesh,\n\tidentityWarpMesh as vectorIdentityMesh,\n\tevalWarpMesh as evalVectorMesh,\n\tsplitWarpMeshU as splitVectorMeshU,\n\tsplitWarpMeshV as splitVectorMeshV,\n\tremoveWarpMeshSplitU as removeVectorMeshSplitU,\n\tremoveWarpMeshSplitV as removeVectorMeshSplitV,\n\tmapWarpMeshPoints as mapVectorMeshPoints,\n\tresizeWarpMesh as resizeVectorMesh,\n\twarpMeshControlBounds as vectorMeshControlBounds,\n\twarpMeshParamAt as vectorMeshParamAt,\n\tdragWarpMeshPoint as dragVectorMeshPoint,\n\tpullWarpMesh as pullVectorMesh,\n\twarpMeshEditPoints as vectorMeshEditPoints,\n\twarpMeshGridCurves as vectorMeshGridCurves\n} from '../geom/warp.js';\n\n/** A preset warp's settings (bend and distortions in percent, −100…100). */\nexport type { WarpPreset as VectorWarpPreset } from '../geom/warp.js';\n\n// ---------------------------------------------------------------------------\n// Envelope from an outline (Make with Top Object)\n// ---------------------------------------------------------------------------\n\n/** Points along a polyline by fraction of its length. */\nfunction polylineAt(pts: readonly Vec2[]): (u: number) => Vec2 {\n\tconst acc = [0];\n\tfor (let i = 1; i < pts.length; i++) acc.push(acc[i - 1] + Math.hypot(pts[i].x - pts[i - 1].x, pts[i].y - pts[i - 1].y));\n\tconst total = acc[acc.length - 1];\n\treturn (u) => {\n\t\tif (!(total > 0)) return pts[0];\n\t\tconst L = Math.min(1, Math.max(0, u)) * total;\n\t\tlet i = 1;\n\t\twhile (i < acc.length - 1 && acc[i] < L) i++;\n\t\tconst seg = acc[i] - acc[i - 1];\n\t\treturn lerpVec2(pts[i - 1], pts[i], seg > 0 ? (L - acc[i - 1]) / seg : 0);\n\t};\n}\n\nfunction sampleSubpath(sp: VectorSubpath, per = 24): Vec2[] {\n\tconst n = sp.anchors.length;\n\tconst out: Vec2[] = [];\n\tfor (let i = 0; i < n; i++) {\n\t\tconst a = sp.anchors[i];\n\t\tconst b = sp.anchors[(i + 1) % n];\n\t\tconst c = [{ x: a.x, y: a.y }, a.out ?? a, b.in ?? b, { x: b.x, y: b.y }];\n\t\tfor (let k = 0; k < per; k++) {\n\t\t\tconst t = k / per;\n\t\t\tconst ab = lerpVec2(c[0], c[1], t);\n\t\t\tconst bc = lerpVec2(c[1], c[2], t);\n\t\t\tconst cd = lerpVec2(c[2], c[3], t);\n\t\t\tout.push(lerpVec2(lerpVec2(ab, bc, t), lerpVec2(bc, cd, t), t));\n\t\t}\n\t}\n\treturn out;\n}\n\n/**\n * A mesh whose border follows a closed outline (Illustrator's Make with Top Object): the outline is\n * cut into four sides at the points nearest its bounding box's corners, and the interior is the\n * Coons patch of those sides, fitted with `columns × rows` patches. Null for an open or degenerate\n * outline.\n */\nexport function vectorMeshFromOutline(sp: VectorSubpath, columns = 4, rows = 4): VectorWarpMesh | null {\n\tif (!sp.closed || sp.anchors.length < 2) return null;\n\tlet ring = sampleSubpath(sp);\n\tconst xs = ring.map((p) => p.x);\n\tconst ys = ring.map((p) => p.y);\n\tconst box = { x0: Math.min(...xs), y0: Math.min(...ys), x1: Math.max(...xs), y1: Math.max(...ys) };\n\tif (!(box.x1 - box.x0 > 1e-9 && box.y1 - box.y0 > 1e-9)) return null;\n\tconst nearest = (c: Vec2) => {\n\t\tlet best = 0;\n\t\tfor (let i = 1; i < ring.length; i++) if (Math.hypot(ring[i].x - c.x, ring[i].y - c.y) < Math.hypot(ring[best].x - c.x, ring[best].y - c.y)) best = i;\n\t\treturn best;\n\t};\n\tconst cornersOf = () =>\n\t\t[\n\t\t\t{ x: box.x0, y: box.y0 },\n\t\t\t{ x: box.x1, y: box.y0 },\n\t\t\t{ x: box.x1, y: box.y1 },\n\t\t\t{ x: box.x0, y: box.y1 }\n\t\t].map(nearest);\n\tlet c = cornersOf();\n\tconst n = ring.length;\n\tconst fwd = (from: number, to: number) => (to - from + n) % n;\n\t// Clockwise on screen: top-left, top-right, bottom-right, bottom-left in walking order.\n\tif (!(fwd(c[0], c[1]) < fwd(c[0], c[2]) && fwd(c[0], c[2]) < fwd(c[0], c[3]))) {\n\t\tring = ring.slice().reverse();\n\t\tc = cornersOf();\n\t\tif (!(fwd(c[0], c[1]) < fwd(c[0], c[2]) && fwd(c[0], c[2]) < fwd(c[0], c[3]))) return null;\n\t}\n\tif (new Set(c).size < 4) return null;\n\tconst walk = (from: number, to: number) => {\n\t\tconst out: Vec2[] = [];\n\t\tfor (let i = from; ; i = (i + 1) % n) {\n\t\t\tout.push(ring[i]);\n\t\t\tif (i === to) break;\n\t\t}\n\t\treturn out;\n\t};\n\t// The ring runs clockwise, so the bottom (bottom-right → bottom-left) and left (bottom-left →\n\t// top-left) walks are reversed to run left to right and top to bottom.\n\tconst top = polylineAt(walk(c[0], c[1]));\n\tconst right = polylineAt(walk(c[1], c[2]));\n\tconst bottomLR = polylineAt(walk(c[2], c[3]).reverse());\n\tconst leftTB = polylineAt(walk(c[3], c[0]).reverse());\n\tconst p00 = top(0);\n\tconst p10 = top(1);\n\tconst p01 = bottomLR(0);\n\tconst p11 = bottomLR(1);\n\tconst coons = (s: number, t: number): Vec2 => {\n\t\tconst T = top(s);\n\t\tconst B = bottomLR(s);\n\t\tconst L = leftTB(t);\n\t\tconst R = right(t);\n\t\treturn {\n\t\t\tx: (1 - t) * T.x + t * B.x + (1 - s) * L.x + s * R.x - ((1 - s) * (1 - t) * p00.x + s * (1 - t) * p10.x + (1 - s) * t * p01.x + s * t * p11.x),\n\t\t\ty: (1 - t) * T.y + t * B.y + (1 - s) * L.y + s * R.y - ((1 - s) * (1 - t) * p00.y + s * (1 - t) * p10.y + (1 - s) * t * p01.y + s * t * p11.y)\n\t\t};\n\t};\n\treturn fitWarpMesh(coons, evenKnots(clampMeshCount(columns)), evenKnots(clampMeshCount(rows)));\n}\n\n/** The mesh's border as one closed subpath (clockwise from the top-left corner): what Release gives back as the envelope's shape. */\nexport function vectorMeshOutline(m: VectorWarpMesh): VectorSubpath {\n\tconst nx = warpMeshColumns(m);\n\tconst ny = warpMeshRows(m);\n\tconst pt = (i: number, j: number) => m.points[j * nx + i];\n\t// The border as a chain of cubics, each [p0, p1, p2, p3].\n\tconst runs: Vec2[][] = [];\n\tfor (let i = 0; i + 3 < nx; i += 3) runs.push([pt(i, 0), pt(i + 1, 0), pt(i + 2, 0), pt(i + 3, 0)]);\n\tfor (let j = 0; j + 3 < ny; j += 3) runs.push([pt(nx - 1, j), pt(nx - 1, j + 1), pt(nx - 1, j + 2), pt(nx - 1, j + 3)]);\n\tfor (let i = nx - 1; i - 3 >= 0; i -= 3) runs.push([pt(i, ny - 1), pt(i - 1, ny - 1), pt(i - 2, ny - 1), pt(i - 3, ny - 1)]);\n\tfor (let j = ny - 1; j - 3 >= 0; j -= 3) runs.push([pt(0, j), pt(0, j - 1), pt(0, j - 2), pt(0, j - 3)]);\n\tconst anchors = runs.map((r, k) => {\n\t\tconst prev = runs[(k + runs.length - 1) % runs.length];\n\t\treturn { x: r[0].x, y: r[0].y, in: { ...prev[2] }, out: { ...r[1] } };\n\t});\n\treturn { closed: true, anchors };\n}\n","/**\n * Live appearance: path effect stacks and live boolean groups, evaluated on demand while the\n * stored anchors and children stay editable.\n *\n * `expandVectorAppearance` is the one place the effected geometry is made (cached per node\n * object, so an edit recomputes only the nodes it replaced). Rendering, hit-testing, bounds,\n * snapping, booleans, the Pathfinder, the Shape Builder and SVG export all read it, the way they\n * read live corners through `subpathsToBezier`; Expand Appearance stores it.\n *\n * Stacking follows After Effects' shape layers (effectcraft `crates/render/src/shapes.rs`): an\n * effect acts on every path above it — the node's own outline, or for a group every path of its\n * children (nested groups included, as drawn by their own effects) — in the order of the stack,\n * and effects placed after a repeater act on its copies. The result paints with the style of the\n * path each shape came from; Merge Paths and live booleans paint with the bottom one's.\n *\n * Live booleans fold their operands bottom to top, each combined with the result below it by its\n * own operation or the group's, and every prefix of the fold is cached under a rolling hash of the\n * operands it covers, so editing one operand recombines only the operands from it up; the cache\n * drops its least recently used half when full. Live groups are hit by their result except while\n * they are being edited (`vectorEnteredGroups`).\n *\n * Ported from ArtCraft (MIT OR Apache-2.0, © ArtCraft Team and contributors; see\n * THIRD_PARTY_NOTICES.md): the stacking rule of effectcraft `crates/render/src/shapes.rs`\n * (`collect()`); figcraft `crates/render/src/boolean.rs` (`fold_cached`, `PathCache`) and\n * `crates/engine/src/booleans.rs` (`operand_op`, `result_outline`); and the live-object model of\n * vectorcraft `crates/doc/src/live.rs` (`expand_live`, `expanded_group`, `subtree_has_live`).\n */\nimport { bezierPathBounds, transformBezierPath, type AffineMatrix, type BezierPath } from '../canvas/pathops/bezier.js';\nimport { pathBoolean } from '../canvas/pathops/boolean.js';\nimport { bezierToSubpaths, isIdentityMatrix, subpathsToBezier } from './geometry.js';\nimport {\n\tmergePaths,\n\toffsetPaths,\n\tpathsCenter,\n\tpuckerBloatPaths,\n\trepeatPaths,\n\troundCornerPaths,\n\ttrimPaths,\n\ttrimPathsIndividually,\n\ttwistPaths,\n\twigglePaths,\n\tzigzagPaths\n} from './pathEffects.js';\nimport { mapBezierPath } from './pathMap.js';\nimport { isVectorMaskGroup, vectorMaskedShapes } from './mask.js';\nimport {\n\tVECTOR_WARP_STYLES,\n\tVECTOR_WARP_STYLE_LABELS,\n\tevalVectorMesh,\n\tisValidVectorMesh,\n\tmapVectorMeshPoints,\n\tresizeVectorMesh,\n\tvectorIdentityMesh,\n\tvectorWarpPresetMesh\n} from './warp.js';\nimport type {\n\tVectorBounds,\n\tVec2,\n\tVectorBooleanOperation,\n\tVectorEffect,\n\tVectorEffectParamsMap,\n\tVectorEffectType,\n\tVectorFillRule,\n\tVectorGroupNode,\n\tVectorNode,\n\tVectorPathNode,\n\tVectorWarpMesh\n} from './types.js';\n\n/** One shape of a node's appearance: a path in the node's own space, painted in `source`'s style. */\nexport interface VectorAppearanceShape {\n\t/** The path whose style paints it. */\n\tsource: VectorPathNode;\n\tpath: BezierPath;\n\t/** Opacity factor relative to the node (its own opacity not included). */\n\topacity: number;\n\t/** Draw-order key (compared element by element). */\n\torder: number[];\n}\n\n// ---------------------------------------------------------------------------\n// Effect definitions\n// ---------------------------------------------------------------------------\n\n/** Default parameters of each effect type. */\nexport const VECTOR_EFFECT_DEFAULTS: { readonly [K in VectorEffectType]: VectorEffectParamsMap[K] } = {\n\ttrim: { start: 0, end: 50, offset: 0, mode: 'simultaneous' },\n\troundCorners: { radius: 10 },\n\tpuckerBloat: { amount: 30 },\n\ttwist: { angle: 45, center: { x: 0, y: 0 } },\n\tzigzag: { size: 5, ridges: 4, smooth: false },\n\twiggle: { size: 5, detail: 6, smooth: true, speed: 2, correlation: 50, phase: 0, seed: 1, time: 0 },\n\toffset: { amount: 5, join: 'miter', miterLimit: 4, copies: 1, copyOffset: 0 },\n\tmerge: { mode: 'add' },\n\trepeater: {\n\t\tcopies: 3,\n\t\toffset: 0,\n\t\tposition: { x: 100, y: 0 },\n\t\tanchor: { x: 0, y: 0 },\n\t\trotation: 0,\n\t\tscale: { x: 100, y: 100 },\n\t\tstartOpacity: 100,\n\t\tendOpacity: 100,\n\t\tcomposite: 'below'\n\t},\n\tenvelope: { style: 'arc', bend: 50, horizontal: 0, vertical: 0, orientation: 'horizontal', rows: 2, columns: 2, mesh: null }\n};\n\nexport const VECTOR_EFFECT_LABELS: Record<VectorEffectType, string> = {\n\ttrim: 'Trim Paths',\n\troundCorners: 'Round Corners',\n\tpuckerBloat: 'Pucker & Bloat',\n\ttwist: 'Twist',\n\tzigzag: 'Zig Zag',\n\twiggle: 'Wiggle Paths',\n\toffset: 'Offset Paths',\n\tmerge: 'Merge Paths',\n\trepeater: 'Repeater',\n\tenvelope: 'Envelope'\n};\n\n/** How a panel edits one effect parameter. */\nexport type VectorEffectParamSpec =\n\t| { key: string; label: string; kind: 'number'; min?: number; max?: number; step: number; slider?: boolean }\n\t| { key: string; label: string; kind: 'vec2'; step: number }\n\t| { key: string; label: string; kind: 'boolean' }\n\t| { key: string; label: string; kind: 'select'; options: { value: string; label: string }[] };\n\n/** The editable parameters of each effect type, in panel order. */\nexport const VECTOR_EFFECT_PARAM_SPECS: Record<VectorEffectType, VectorEffectParamSpec[]> = {\n\ttrim: [\n\t\t{ key: 'start', label: 'Start %', kind: 'number', min: 0, max: 100, step: 1, slider: true },\n\t\t{ key: 'end', label: 'End %', kind: 'number', min: 0, max: 100, step: 1, slider: true },\n\t\t{ key: 'offset', label: 'Offset °', kind: 'number', min: -360, max: 360, step: 1, slider: true },\n\t\t{\n\t\t\tkey: 'mode',\n\t\t\tlabel: 'Paths',\n\t\t\tkind: 'select',\n\t\t\toptions: [\n\t\t\t\t{ value: 'simultaneous', label: 'Simultaneously' },\n\t\t\t\t{ value: 'individual', label: 'Individually' }\n\t\t\t]\n\t\t}\n\t],\n\troundCorners: [{ key: 'radius', label: 'Radius', kind: 'number', min: 0, max: 200, step: 1, slider: true }],\n\tpuckerBloat: [{ key: 'amount', label: 'Amount %', kind: 'number', min: -100, max: 100, step: 1, slider: true }],\n\ttwist: [\n\t\t{ key: 'angle', label: 'Angle °', kind: 'number', min: -720, max: 720, step: 1, slider: true },\n\t\t{ key: 'center', label: 'Centre', kind: 'vec2', step: 1 }\n\t],\n\tzigzag: [\n\t\t{ key: 'size', label: 'Size', kind: 'number', min: 0, max: 100, step: 0.5, slider: true },\n\t\t{ key: 'ridges', label: 'Ridges', kind: 'number', min: 0, max: 50, step: 1, slider: true },\n\t\t{ key: 'smooth', label: 'Smooth', kind: 'boolean' }\n\t],\n\twiggle: [\n\t\t{ key: 'size', label: 'Size', kind: 'number', min: 0, max: 100, step: 0.5, slider: true },\n\t\t{ key: 'detail', label: 'Detail', kind: 'number', min: 0, max: 50, step: 1, slider: true },\n\t\t{ key: 'smooth', label: 'Smooth', kind: 'boolean' },\n\t\t{ key: 'correlation', label: 'Correlation %', kind: 'number', min: 0, max: 100, step: 1, slider: true },\n\t\t{ key: 'speed', label: 'Speed', kind: 'number', min: 0, step: 0.1 },\n\t\t{ key: 'phase', label: 'Phase °', kind: 'number', step: 1 },\n\t\t{ key: 'time', label: 'Time (s)', kind: 'number', min: 0, max: 10, step: 0.05, slider: true },\n\t\t{ key: 'seed', label: 'Seed', kind: 'number', step: 1 }\n\t],\n\toffset: [\n\t\t{ key: 'amount', label: 'Amount', kind: 'number', min: -100, max: 100, step: 0.5, slider: true },\n\t\t{\n\t\t\tkey: 'join',\n\t\t\tlabel: 'Join',\n\t\t\tkind: 'select',\n\t\t\toptions: [\n\t\t\t\t{ value: 'miter', label: 'Miter' },\n\t\t\t\t{ value: 'round', label: 'Round' },\n\t\t\t\t{ value: 'bevel', label: 'Bevel' }\n\t\t\t]\n\t\t},\n\t\t{ key: 'miterLimit', label: 'Miter limit', kind: 'number', min: 1, step: 0.5 },\n\t\t{ key: 'copies', label: 'Copies', kind: 'number', min: 1, max: 20, step: 1 },\n\t\t{ key: 'copyOffset', label: 'Copy offset', kind: 'number', step: 0.5 }\n\t],\n\tmerge: [\n\t\t{\n\t\t\tkey: 'mode',\n\t\t\tlabel: 'Mode',\n\t\t\tkind: 'select',\n\t\t\toptions: [\n\t\t\t\t{ value: 'merge', label: 'Merge' },\n\t\t\t\t{ value: 'add', label: 'Add' },\n\t\t\t\t{ value: 'subtract', label: 'Subtract' },\n\t\t\t\t{ value: 'intersect', label: 'Intersect' },\n\t\t\t\t{ value: 'exclude', label: 'Exclude' }\n\t\t\t]\n\t\t}\n\t],\n\trepeater: [\n\t\t{ key: 'copies', label: 'Copies', kind: 'number', min: 0, max: 50, step: 0.1, slider: true },\n\t\t{ key: 'offset', label: 'Offset', kind: 'number', min: -10, max: 10, step: 0.1, slider: true },\n\t\t{ key: 'position', label: 'Position', kind: 'vec2', step: 1 },\n\t\t{ key: 'anchor', label: 'Anchor', kind: 'vec2', step: 1 },\n\t\t{ key: 'rotation', label: 'Rotation °', kind: 'number', min: -360, max: 360, step: 1, slider: true },\n\t\t{ key: 'scale', label: 'Scale %', kind: 'vec2', step: 1 },\n\t\t{ key: 'startOpacity', label: 'Start opacity %', kind: 'number', min: 0, max: 100, step: 1, slider: true },\n\t\t{ key: 'endOpacity', label: 'End opacity %', kind: 'number', min: 0, max: 100, step: 1, slider: true },\n\t\t{\n\t\t\tkey: 'composite',\n\t\t\tlabel: 'Copies',\n\t\t\tkind: 'select',\n\t\t\toptions: [\n\t\t\t\t{ value: 'below', label: 'Below' },\n\t\t\t\t{ value: 'above', label: 'Above' }\n\t\t\t]\n\t\t}\n\t],\n\tenvelope: [\n\t\t{\n\t\t\tkey: 'style',\n\t\t\tlabel: 'Warp',\n\t\t\tkind: 'select',\n\t\t\toptions: [...VECTOR_WARP_STYLES.map((value) => ({ value, label: VECTOR_WARP_STYLE_LABELS[value] })), { value: 'mesh', label: 'Mesh' }]\n\t\t},\n\t\t{ key: 'bend', label: 'Bend %', kind: 'number', min: -100, max: 100, step: 1, slider: true },\n\t\t{ key: 'horizontal', label: 'Horizontal distortion %', kind: 'number', min: -100, max: 100, step: 1, slider: true },\n\t\t{ key: 'vertical', label: 'Vertical distortion %', kind: 'number', min: -100, max: 100, step: 1, slider: true },\n\t\t{\n\t\t\tkey: 'orientation',\n\t\t\tlabel: 'Orientation',\n\t\t\tkind: 'select',\n\t\t\toptions: [\n\t\t\t\t{ value: 'horizontal', label: 'Horizontal' },\n\t\t\t\t{ value: 'vertical', label: 'Vertical' }\n\t\t\t]\n\t\t},\n\t\t{ key: 'rows', label: 'Mesh rows', kind: 'number', min: 1, max: 16, step: 1 },\n\t\t{ key: 'columns', label: 'Mesh columns', kind: 'number', min: 1, max: 16, step: 1 }\n\t]\n};\n\n/** Envelope parameters. */\nexport type VectorEnvelopeParams = VectorEffectParamsMap['envelope'];\n\nconst cloneMesh = (m: VectorWarpMesh): VectorWarpMesh => ({ us: m.us.slice(), vs: m.vs.slice(), points: m.points.map((p) => ({ x: p.x, y: p.y })) });\n\n/**\n * The envelope's mesh over `bounds` (the paths' combined bounds), in the node's space: its own\n * mesh, the flat mesh of `columns × rows` patches, or a preset split exactly into that many patches.\n */\nexport function vectorEnvelopeMesh(params: VectorEnvelopeParams, bounds: VectorBounds): VectorWarpMesh {\n\tif (params.style === 'mesh') return params.mesh ?? vectorIdentityMesh(bounds, params.columns, params.rows);\n\tconst preset = vectorWarpPresetMesh({ style: params.style, bend: params.bend, horizontal: params.horizontal, vertical: params.vertical, orientation: params.orientation }, bounds);\n\treturn preset ? resizeVectorMesh(preset, params.columns, params.rows) : vectorIdentityMesh(bounds, params.columns, params.rows);\n}\n\n/** The envelope as a map of the node's space over `bounds`, or null when it changes nothing (or the box is empty). */\nexport function vectorEnvelopeMap(params: VectorEnvelopeParams, bounds: VectorBounds | null): ((p: { x: number; y: number }) => { x: number; y: number }) | null {\n\tif (!bounds || !(bounds.width > 0 && bounds.height > 0)) return null;\n\tconst mesh =\n\t\tparams.style === 'mesh'\n\t\t\t? params.mesh\n\t\t\t: vectorWarpPresetMesh({ style: params.style, bend: params.bend, horizontal: params.horizontal, vertical: params.vertical, orientation: params.orientation }, bounds);\n\tif (!mesh) return null;\n\tconst { x, y, width, height } = bounds;\n\treturn (p) => evalVectorMesh(mesh, (p.x - x) / width, (p.y - y) / height);\n}\n\n/** Combined bounds of paths. */\nfunction pathsBounds(paths: readonly BezierPath[]): VectorBounds | null {\n\tlet minX = Infinity;\n\tlet minY = Infinity;\n\tlet maxX = -Infinity;\n\tlet maxY = -Infinity;\n\tfor (const p of paths) {\n\t\tconst b = bezierPathBounds(p);\n\t\tif (!b) continue;\n\t\tminX = Math.min(minX, b.minX);\n\t\tminY = Math.min(minY, b.minY);\n\t\tmaxX = Math.max(maxX, b.maxX);\n\t\tmaxY = Math.max(maxY, b.maxY);\n\t}\n\treturn minX <= maxX ? { x: minX, y: minY, width: maxX - minX, height: maxY - minY } : null;\n}\n\n/** The paths through an envelope (each mapped adaptively, within a tolerance relative to their size). */\nfunction envelopePaths(paths: BezierPath[], params: VectorEnvelopeParams): BezierPath[] {\n\tconst bounds = pathsBounds(paths);\n\tconst f = vectorEnvelopeMap(params, bounds);\n\tif (!f || !bounds) return paths;\n\tconst tol = Math.min(0.25, Math.max(0.01, Math.hypot(bounds.width, bounds.height) / 2000));\n\treturn paths.map((p) => (p.length ? mapBezierPath(p, f, tol) : p));\n}\n\nconst isVec2 = (v: unknown): v is Vec2 => !!v && typeof v === 'object' && Number.isFinite((v as Vec2).x) && Number.isFinite((v as Vec2).y);\n\n/**\n * Effect parameters with defaults filled in and invalid values dropped (unknown keys go too).\n * Returns null for an unknown type.\n */\nexport function normalizeVectorEffectParams<K extends VectorEffectType>(type: K, params: Record<string, unknown> | null | undefined, base?: VectorEffectParamsMap[K]): VectorEffectParamsMap[K] | null {\n\tconst defaults = VECTOR_EFFECT_DEFAULTS[type] as Record<string, unknown> | undefined;\n\tif (!defaults) return null;\n\tconst out: Record<string, unknown> = { ...defaults, ...((base as Record<string, unknown> | undefined) ?? {}) };\n\tfor (const spec of VECTOR_EFFECT_PARAM_SPECS[type]) {\n\t\tconst v = params?.[spec.key];\n\t\tif (v === undefined) continue;\n\t\tif (spec.kind === 'number' && typeof v === 'number' && Number.isFinite(v)) out[spec.key] = Math.min(spec.max ?? Infinity, Math.max(spec.min ?? -Infinity, v));\n\t\telse if (spec.kind === 'boolean' && typeof v === 'boolean') out[spec.key] = v;\n\t\telse if (spec.kind === 'vec2' && isVec2(v)) out[spec.key] = { x: v.x, y: v.y };\n\t\telse if (spec.kind === 'select' && spec.options.some((o) => o.value === v)) out[spec.key] = v;\n\t}\n\tif (type === 'envelope') {\n\t\tconst o = out as unknown as VectorEnvelopeParams;\n\t\to.rows = Math.round(o.rows);\n\t\to.columns = Math.round(o.columns);\n\t\tconst given = params?.mesh;\n\t\tlet mesh: VectorWarpMesh | null = given !== undefined ? (isValidVectorMesh(given) ? cloneMesh(given) : null) : o.mesh;\n\t\tif (o.style !== 'mesh') mesh = null;\n\t\tif (mesh && given !== undefined) {\n\t\t\to.columns = mesh.us.length - 1;\n\t\t\to.rows = mesh.vs.length - 1;\n\t\t} else if (mesh) mesh = resizeVectorMesh(mesh, o.columns, o.rows);\n\t\to.mesh = mesh;\n\t}\n\treturn out as VectorEffectParamsMap[K];\n}\n\n/** A new effect of `type` (defaults merged with `params`), or null for an unknown type. */\nexport function createVectorEffect<K extends VectorEffectType>(type: K, id: string, params?: Partial<VectorEffectParamsMap[K]> | Record<string, unknown>): Extract<VectorEffect, { type: K }> | null {\n\tconst p = normalizeVectorEffectParams(type, params as Record<string, unknown>);\n\treturn p ? ({ id, type, params: p } as unknown as Extract<VectorEffect, { type: K }>) : null;\n}\n\nconst isEnabled = (e: VectorEffect) => e.enabled !== false && !!VECTOR_EFFECT_DEFAULTS[e.type];\n\n/** The node's effects that take part (enabled, of a known type). */\nexport function activeVectorEffects(node: VectorNode): VectorEffect[] {\n\treturn node.effects?.filter(isEnabled) ?? [];\n}\n\n/** Whether the node itself draws differently from its stored geometry (effects or a live boolean). */\nexport function hasOwnVectorAppearance(node: VectorNode): boolean {\n\treturn (node.type === 'group' && !!node.liveBoolean) || !!node.effects?.some(isEnabled);\n}\n\nconst liveCache = new WeakMap<VectorNode, boolean>();\n\n/** Whether the node or anything inside it has a live appearance. */\nexport function hasVectorAppearance(node: VectorNode): boolean {\n\tlet v = liveCache.get(node);\n\tif (v === undefined) {\n\t\tv = hasOwnVectorAppearance(node) || (node.type === 'group' && node.children.some(hasVectorAppearance));\n\t\tliveCache.set(node, v);\n\t}\n\treturn v;\n}\n\n/** A live boolean group (its children are operands). */\nexport function isVectorLiveBoolean(node: VectorNode | null | undefined): node is VectorGroupNode & { liveBoolean: VectorBooleanOperation } {\n\treturn node?.type === 'group' && !!node.liveBoolean;\n}\n\n/** How operand `child` of a live boolean group combines with the operands below it. */\nexport function vectorOperandOperation(group: VectorGroupNode, child: VectorNode): VectorBooleanOperation {\n\treturn child.booleanOperation ?? group.liveBoolean ?? 'union';\n}\n\n// ---------------------------------------------------------------------------\n// Live boolean fold\n// ---------------------------------------------------------------------------\n\nconst PATH_OPS = { union: 'union', subtract: 'difference', intersect: 'intersection', exclude: 'xor' } as const;\n\n/** A bounded map of fold prefixes; the least recently used half goes when it is full. */\nclass FoldCache {\n\tprivate map = new Map<string, BezierPath>();\n\tconstructor(private readonly cap: number) {}\n\tget(key: string): BezierPath | undefined {\n\t\tconst hit = this.map.get(key);\n\t\tif (hit) {\n\t\t\tthis.map.delete(key);\n\t\t\tthis.map.set(key, hit);\n\t\t}\n\t\treturn hit;\n\t}\n\tset(key: string, path: BezierPath) {\n\t\tif (this.map.size >= this.cap) {\n\t\t\tlet drop = Math.floor(this.map.size / 2);\n\t\t\tfor (const k of this.map.keys()) {\n\t\t\t\tif (drop-- <= 0) break;\n\t\t\t\tthis.map.delete(k);\n\t\t\t}\n\t\t}\n\t\tthis.map.set(key, path);\n\t}\n\tclear() {\n\t\tthis.map.clear();\n\t}\n}\n\nconst foldCache = new FoldCache(4096);\nlet foldSteps = 0;\n\n/** How many boolean steps (one operand combined with the result below it) live booleans have computed: what a cache miss costs. */\nexport function vectorLiveBooleanSteps(): number {\n\treturn foldSteps;\n}\n\n/** Empties the live boolean prefix cache. */\nexport function clearVectorLiveBooleanCache(): void {\n\tfoldCache.clear();\n}\n\n/** A rolling hash of operands: two 32-bit FNV-1a lanes over every number's bits. */\nclass RollingHash {\n\tprivate a = 0x811c9dc5;\n\tprivate b = 0x01000193 ^ 0x5bd1e995;\n\tprivate static view = new DataView(new ArrayBuffer(8));\n\tbyte(v: number) {\n\t\tthis.a = Math.imul(this.a ^ (v & 0xff), 0x01000193);\n\t\tthis.b = Math.imul(this.b ^ (v & 0xff), 0x5bd1e995) ^ (this.b >>> 15);\n\t}\n\tnum(n: number) {\n\t\tRollingHash.view.setFloat64(0, n);\n\t\tfor (let i = 0; i < 8; i++) this.byte(RollingHash.view.getUint8(i));\n\t}\n\tpath(p: BezierPath) {\n\t\tfor (const c of p) {\n\t\t\tthis.byte(c.type.charCodeAt(0));\n\t\t\tif (c.type === 'Z') continue;\n\t\t\tif (c.type === 'C') {\n\t\t\t\tthis.num(c.x1);\n\t\t\t\tthis.num(c.y1);\n\t\t\t\tthis.num(c.x2);\n\t\t\t\tthis.num(c.y2);\n\t\t\t} else if (c.type === 'Q') {\n\t\t\t\tthis.num(c.x1);\n\t\t\t\tthis.num(c.y1);\n\t\t\t}\n\t\t\tthis.num(c.x);\n\t\t\tthis.num(c.y);\n\t\t}\n\t}\n\tkey(): string {\n\t\treturn `${(this.a >>> 0).toString(36)}.${(this.b >>> 0).toString(36)}`;\n\t}\n}\n\n/** One operand of a live boolean: its outline (group space), fill rule and operation (unused for the bottom one). */\nexport interface VectorBooleanOperand {\n\tpath: BezierPath;\n\tfillRule: VectorFillRule;\n\toperation: VectorBooleanOperation;\n}\n\n/**\n * The result of folding `operands` bottom to top, reusing the longest cached prefix: only the\n * operands above it are combined. Invalid geometry gives an empty path.\n */\nexport function foldVectorBooleanOperands(operands: readonly VectorBooleanOperand[]): BezierPath {\n\tif (!operands.length) return [];\n\tif (operands.length === 1) return operands[0].path;\n\tconst h = new RollingHash();\n\tconst keys = operands.map((o, i) => {\n\t\tif (i > 0) h.byte(o.operation.charCodeAt(0) + o.operation.length);\n\t\th.byte(o.fillRule === 'evenodd' ? 1 : 0);\n\t\th.path(o.path);\n\t\th.byte(9);\n\t\treturn h.key();\n\t});\n\tlet start = 0;\n\tlet acc: BezierPath = operands[0].path;\n\tfor (let i = keys.length - 1; i >= 1; i--) {\n\t\tconst hit = foldCache.get(keys[i]);\n\t\tif (hit) {\n\t\t\tif (i === keys.length - 1) return hit;\n\t\t\tstart = i;\n\t\t\tacc = hit;\n\t\t\tbreak;\n\t\t}\n\t}\n\tlet accRule: VectorFillRule = start === 0 ? operands[0].fillRule : 'nonzero';\n\tfor (let i = start + 1; i < operands.length; i++) {\n\t\tconst o = operands[i];\n\t\tfoldSteps++;\n\t\tconst r = pathBoolean(PATH_OPS[o.operation] ?? 'union', [\n\t\t\t{ path: acc, fillRule: accRule },\n\t\t\t{ path: o.path, fillRule: o.fillRule }\n\t\t]);\n\t\tif (r.error) return [];\n\t\tacc = r.path;\n\t\taccRule = 'nonzero';\n\t\tfoldCache.set(keys[i], acc);\n\t}\n\treturn acc;\n}\n\n// ---------------------------------------------------------------------------\n// The effect stack\n// ---------------------------------------------------------------------------\n\nconst compareOrder = (a: readonly number[], b: readonly number[]) => {\n\tconst n = Math.min(a.length, b.length);\n\tfor (let i = 0; i < n; i++) if (a[i] !== b[i]) return a[i] - b[i];\n\treturn a.length - b.length;\n};\n\nconst add = (a: Vec2, b: Vec2 | undefined): Vec2 => ({ x: a.x + (b?.x ?? 0), y: a.y + (b?.y ?? 0) });\n\n/** Every path operator maps the shapes' paths one to one. */\nconst mapPaths = (shapes: VectorAppearanceShape[], fn: (paths: BezierPath[]) => BezierPath[]): VectorAppearanceShape[] => {\n\tconst out = fn(shapes.map((s) => s.path));\n\treturn shapes.map((s, i) => ({ ...s, path: out[i] ?? [] }));\n};\n\n/** Applies an effect stack to shapes, top to bottom (disabled effects skipped). */\nexport function applyVectorEffects(shapes: readonly VectorAppearanceShape[], effects: readonly VectorEffect[] | null | undefined): VectorAppearanceShape[] {\n\tlet list = shapes.slice();\n\tfor (const e of effects ?? []) {\n\t\tif (!isEnabled(e) || !list.length) continue;\n\t\tswitch (e.type) {\n\t\t\tcase 'trim': {\n\t\t\t\tconst { start, end, offset, mode } = e.params;\n\t\t\t\tlist = mapPaths(list, (p) => (mode === 'individual' ? trimPathsIndividually(p, start, end, offset) : trimPaths(p, start, end, offset)));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'roundCorners':\n\t\t\t\tlist = mapPaths(list, (p) => roundCornerPaths(p, e.params.radius));\n\t\t\t\tbreak;\n\t\t\tcase 'puckerBloat':\n\t\t\t\tlist = mapPaths(list, (p) => puckerBloatPaths(p, e.params.amount));\n\t\t\t\tbreak;\n\t\t\tcase 'twist':\n\t\t\t\tlist = mapPaths(list, (p) => twistPaths(p, e.params.angle, add(pathsCenter(p), e.params.center)));\n\t\t\t\tbreak;\n\t\t\tcase 'zigzag':\n\t\t\t\tlist = mapPaths(list, (p) => zigzagPaths(p, e.params.size, e.params.ridges, e.params.smooth));\n\t\t\t\tbreak;\n\t\t\tcase 'wiggle':\n\t\t\t\tlist = mapPaths(list, (p) => wigglePaths(p, e.params));\n\t\t\t\tbreak;\n\t\t\tcase 'offset': {\n\t\t\t\tconst o = e.params;\n\t\t\t\tlist = mapPaths(list, (p) => offsetPaths(p, o.amount, o.join, o.miterLimit, o.copies, o.copyOffset));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'merge': {\n\t\t\t\tconst first = list[0];\n\t\t\t\tlist = [{ ...first, path: mergePaths(list.map((s) => s.path), e.params.mode) }];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'envelope': {\n\t\t\t\tconst params = e.params;\n\t\t\t\tlist = mapPaths(list, (p) => envelopePaths(p, params));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'repeater': {\n\t\t\t\tconst r = e.params;\n\t\t\t\tconst copies = repeatPaths(\n\t\t\t\t\tlist.map((s) => s.path),\n\t\t\t\t\tr,\n\t\t\t\t\tadd(pathsCenter(list.map((s) => s.path)), r.anchor)\n\t\t\t\t);\n\t\t\t\tconst n = copies.length;\n\t\t\t\tconst next: VectorAppearanceShape[] = [];\n\t\t\t\tfor (const { copy, paths } of copies) {\n\t\t\t\t\t// Below: each copy draws under the one before it (the original on top).\n\t\t\t\t\tconst rank = r.composite === 'above' ? copy.index : n - 1 - copy.index;\n\t\t\t\t\tlist.forEach((s, i) => next.push({ source: s.source, path: paths[i], opacity: s.opacity * copy.opacity, order: [rank, ...s.order] }));\n\t\t\t\t}\n\t\t\t\tlist = next;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn list;\n}\n\n/** The shapes of a child in its parent's space (hidden children have none), ordered by its index. */\nexport function vectorChildAppearanceShapes(child: VectorNode, index: number): VectorAppearanceShape[] {\n\tif (child.visible === false) return [];\n\tconst m = child.transform;\n\tconst k = child.opacity ?? 1;\n\treturn vectorAppearanceShapes(child).map((s) => ({\n\t\tsource: s.source,\n\t\tpath: m && !isIdentityMatrix(m) ? transformBezierPath(s.path, m) : s.path,\n\t\topacity: s.opacity * k,\n\t\torder: [index, ...s.order]\n\t}));\n}\n\n/** A live boolean group's result: its operands folded, in the bottom operand's style. */\nfunction liveBooleanShapes(group: VectorGroupNode): VectorAppearanceShape[] {\n\tconst operands: VectorBooleanOperand[] = [];\n\tlet source: VectorPathNode | null = null;\n\tgroup.children.forEach((child, i) => {\n\t\tconst shapes = vectorChildAppearanceShapes(child, i);\n\t\tif (!shapes.length) return;\n\t\tsource ??= shapes[0].source;\n\t\tconst path =\n\t\t\tshapes.length === 1 ? shapes[0].path : pathBoolean('union', shapes.map((s) => ({ path: s.path, fillRule: s.source.fillRule ?? 'nonzero' }))).path;\n\t\tconst fillRule: VectorFillRule = shapes.length === 1 ? (shapes[0].source.fillRule ?? 'nonzero') : 'nonzero';\n\t\toperands.push({ path, fillRule, operation: vectorOperandOperation(group, child) });\n\t});\n\tif (!source) return [];\n\treturn [{ source, path: foldVectorBooleanOperands(operands), opacity: 1, order: [0] }];\n}\n\nconst shapeCache = new WeakMap<VectorNode, VectorAppearanceShape[]>();\n\n/** What a node's effect stack starts from: its own outline, its live boolean result or its children's shapes. */\nfunction baseShapes(node: VectorNode): VectorAppearanceShape[] {\n\tif (node.type === 'path') return [{ source: node, path: subpathsToBezier(node.subpaths), opacity: 1, order: [] }];\n\tif (node.liveBoolean) return liveBooleanShapes(node);\n\t// A mask group's effects act on its contents (the mask stays as it is).\n\tif (isVectorMaskGroup(node)) return node.children.flatMap((c, i) => (i === 0 ? [] : vectorChildAppearanceShapes(c, i)));\n\treturn node.children.flatMap((c, i) => vectorChildAppearanceShapes(c, i));\n}\n\n/** The paths entering effect `effectId` of the node's stack (those above it applied), in the node's own space. */\nexport function vectorEffectInputPaths(node: VectorNode, effectId: string): BezierPath[] | null {\n\tconst list = node.effects ?? [];\n\tconst i = list.findIndex((e) => e.id === effectId);\n\tif (i < 0) return null;\n\treturn applyVectorEffects(baseShapes(node), list.slice(0, i)).map((s) => s.path);\n}\n\n/** The box effect `effectId` (an envelope) bends: the combined bounds of the paths entering it, in the node's own space. */\nexport function vectorEffectInputBounds(node: VectorNode, effectId: string): VectorBounds | null {\n\tconst paths = vectorEffectInputPaths(node, effectId);\n\treturn paths ? pathsBounds(paths) : null;\n}\n\n/** The node's first enabled envelope effect, or null. */\nexport function vectorNodeEnvelope(node: VectorNode | null | undefined): Extract<VectorEffect, { type: 'envelope' }> | null {\n\treturn (node?.effects?.find((e) => e.type === 'envelope' && e.enabled !== false) as Extract<VectorEffect, { type: 'envelope' }> | undefined) ?? null;\n}\n\n/**\n * The editable mesh of a node's envelope (its own mesh, or the preset or flat mesh it stands for)\n * with the box it bends, in the node's own space; null without an envelope or contents.\n */\nexport function vectorEnvelopeFrame(node: VectorNode, effectId?: string): { effectId: string; bounds: VectorBounds; mesh: VectorWarpMesh } | null {\n\tconst e = effectId ? node.effects?.find((x) => x.id === effectId) : vectorNodeEnvelope(node);\n\tif (!e || e.type !== 'envelope') return null;\n\tconst bounds = vectorEffectInputBounds(node, e.id);\n\tif (!bounds || !(bounds.width > 0 && bounds.height > 0)) return null;\n\treturn { effectId: e.id, bounds, mesh: vectorEnvelopeMesh(e.params, bounds) };\n}\n\n/**\n * What a node draws as: shapes in its own space (its `transform` and opacity not applied),\n * bottom to top, with its effects and those of everything inside it applied. Cached per node\n * object.\n */\nexport function vectorAppearanceShapes(node: VectorNode): VectorAppearanceShape[] {\n\tconst hit = shapeCache.get(node);\n\tif (hit) return hit;\n\t// A mask group draws its contents (effects applied) clipped by its mask.\n\tconst out = (isVectorMaskGroup(node) ? vectorMaskedShapes(node) : applyVectorEffects(baseShapes(node), node.effects)).sort((a, b) => compareOrder(a.order, b.order));\n\tshapeCache.set(node, out);\n\treturn out;\n}\n\nconst outlineCache = new WeakMap<VectorNode, BezierPath>();\n\n/** Everything a node draws as one path in its own space (live corners cut, effects applied). */\nexport function vectorAppearanceOutline(node: VectorNode): BezierPath {\n\tlet hit = outlineCache.get(node);\n\tif (!hit) {\n\t\thit = node.type === 'path' && !hasOwnVectorAppearance(node) ? subpathsToBezier(node.subpaths) : vectorAppearanceShapes(node).flatMap((s) => s.path);\n\t\toutlineCache.set(node, hit);\n\t}\n\treturn hit;\n}\n\n// ---------------------------------------------------------------------------\n// Expanded nodes\n// ---------------------------------------------------------------------------\n\n/** A shape as a plain path node in `source`'s style. */\nfunction shapeNode(shape: VectorAppearanceShape, id: string): VectorPathNode {\n\tconst {\n\t\tid: _id,\n\t\ttype: _type,\n\t\tsubpaths: _s,\n\t\ttransform: _t,\n\t\teffects: _e,\n\t\tbooleanOperation: _b,\n\t\tblendStep: _bs,\n\t\tlocked: _l,\n\t\tvisible: _v,\n\t\topacity: _o,\n\t\t// The node's own blend mode and filters stay on the node, not on each shape it draws.\n\t\tblendMode: _bm,\n\t\tfilters: _fl,\n\t\t...style\n\t} = shape.source;\n\treturn { ...style, id, type: 'path', subpaths: bezierToSubpaths(shape.path), ...(shape.opacity < 1 ? { opacity: shape.opacity } : {}) };\n}\n\n/** The node's own placement and state, kept by its expanded form. */\nfunction placement(node: VectorNode) {\n\treturn {\n\t\t...(node.name !== undefined ? { name: node.name } : {}),\n\t\t...(node.transform ? { transform: node.transform } : {}),\n\t\t...(node.visible === false ? { visible: false } : {}),\n\t\t...(node.locked ? { locked: true } : {}),\n\t\t...(node.blendStep ? { blendStep: true } : {}),\n\t\t...(node.booleanOperation ? { booleanOperation: node.booleanOperation } : {}),\n\t\t...(node.blendMode ? { blendMode: node.blendMode } : {}),\n\t\t...(node.filters?.length ? { filters: node.filters } : {})\n\t};\n}\n\n/** What a node draws as, one plain path per shape (ids `<id>~fx<n>`, opacity relative to the node). */\nexport function vectorAppearanceNodes(node: VectorNode): VectorPathNode[] {\n\treturn vectorAppearanceShapes(node).map((s, k) => shapeNode(s, `${node.id}~fx${k}`));\n}\n\nconst expandCache = new WeakMap<VectorNode, VectorNode>();\n\n/**\n * The node as plain geometry: path effects and live booleans evaluated into paths (the node\n * itself when nothing inside it is live). A path keeps its id when it draws as one shape;\n * otherwise, like any live group, it becomes a group with that id holding one path per shape\n * (ids `<id>~fx<n>`). Groups without effects of their own keep their structure. Cached per node.\n */\nexport function expandVectorAppearance(node: VectorNode): VectorNode {\n\tif (!hasVectorAppearance(node)) return node;\n\tconst hit = expandCache.get(node);\n\tif (hit) return hit;\n\tlet out: VectorNode;\n\tif (!hasOwnVectorAppearance(node)) {\n\t\tconst group = node as VectorGroupNode;\n\t\tout = { ...group, children: group.children.map(expandVectorAppearance) };\n\t} else if (isVectorMaskGroup(node)) {\n\t\t// A mask group keeps its mask; its effects act on the contents, wrapped in a group of their own.\n\t\tconst { effects, ...group } = node;\n\t\tconst [mask, ...contents] = node.children;\n\t\tconst wrapper: VectorGroupNode = { id: `${node.id}~content`, type: 'group', effects, children: contents };\n\t\tout = { ...group, children: [expandVectorAppearance(mask), ...(contents.length ? [expandVectorAppearance(wrapper)] : [])] };\n\t} else {\n\t\tconst shapes = vectorAppearanceShapes(node);\n\t\tif (node.type === 'path' && shapes.length === 1) {\n\t\t\tconst one = shapes[0];\n\t\t\tconst { effects: _e, opacity: _o, ...rest } = node;\n\t\t\tconst opacity = (node.opacity ?? 1) * one.opacity;\n\t\t\tout = { ...rest, subpaths: bezierToSubpaths(one.path), ...(opacity < 1 ? { opacity } : {}) };\n\t\t} else {\n\t\t\tout = {\n\t\t\t\tid: node.id,\n\t\t\t\ttype: 'group',\n\t\t\t\t...placement(node),\n\t\t\t\t...(node.opacity !== undefined ? { opacity: node.opacity } : {}),\n\t\t\t\tchildren: vectorAppearanceNodes(node)\n\t\t\t};\n\t\t}\n\t}\n\texpandCache.set(node, out);\n\treturn out;\n}\n\n/** Every node of a list expanded (the same array when nothing in it is live). */\nexport function expandVectorAppearances(nodes: readonly VectorNode[]): VectorNode[] {\n\tlet changed = false;\n\tconst out = nodes.map((n) => {\n\t\tconst e = expandVectorAppearance(n);\n\t\tif (e !== n) changed = true;\n\t\treturn e;\n\t});\n\treturn changed ? out : (nodes as VectorNode[]);\n}\n\n/**\n * Reads effects from untrusted data (JSON, agent input): unknown types and malformed entries are\n * dropped, parameters normalized, ids made unique.\n */\nexport function sanitizeVectorEffects(value: unknown): VectorEffect[] {\n\tif (!Array.isArray(value)) return [];\n\tconst out: VectorEffect[] = [];\n\tconst used = new Set<string>();\n\tfor (const raw of value) {\n\t\tif (!raw || typeof raw !== 'object') continue;\n\t\tconst r = raw as Record<string, unknown>;\n\t\tconst type = r.type as VectorEffectType;\n\t\tif (typeof type !== 'string' || !VECTOR_EFFECT_DEFAULTS[type]) continue;\n\t\tlet id = typeof r.id === 'string' && r.id && !used.has(r.id) ? r.id : '';\n\t\tfor (let k = out.length + 1; !id; k++) if (!used.has(`fx${k}`)) id = `fx${k}`;\n\t\tused.add(id);\n\t\tconst effect = createVectorEffect(type, id, (r.params as Record<string, unknown>) ?? {})!;\n\t\tout.push(r.enabled === false ? { ...effect, enabled: false } : effect);\n\t}\n\treturn out;\n}\n\n/**\n * Effect parameters carried through a linear map baked into a node's geometry (scaling or\n * flipping it): offsets and positions move with it, angles turn the other way when it mirrors.\n * Lengths such as sizes and radii are kept, like stroke widths.\n */\nexport function transformVectorEffects(effects: readonly VectorEffect[], m: AffineMatrix, node?: VectorNode): VectorEffect[] {\n\tconst lin = (v: Vec2): Vec2 => ({ x: m[0] * v.x + m[2] * v.y, y: m[1] * v.x + m[3] * v.y });\n\tconst full = (v: Vec2): Vec2 => ({ x: m[0] * v.x + m[2] * v.y + m[4], y: m[1] * v.x + m[3] * v.y + m[5] });\n\tconst mirror = m[0] * m[3] - m[1] * m[2] < 0 ? -1 : 1;\n\t// A preset is laid over the box of what it bends, so it follows a move or a scale by itself; a\n\t// skew or a mirror turns it into a mesh, which maps like the geometry.\n\tconst axisScale = Math.abs(m[1]) < 1e-12 && Math.abs(m[2]) < 1e-12 && m[0] > 0 && m[3] > 0;\n\treturn effects.map((e) => {\n\t\tif (e.type === 'envelope') {\n\t\t\tif (e.params.style === 'mesh') return e.params.mesh ? { ...e, params: { ...e.params, mesh: mapVectorMeshPoints(e.params.mesh, full) } } : e;\n\t\t\tif (axisScale || !node) return e;\n\t\t\tconst bounds = vectorEffectInputBounds(node, e.id);\n\t\t\tif (!bounds || !vectorEnvelopeMap(e.params, bounds)) return e;\n\t\t\treturn { ...e, params: { ...e.params, style: 'mesh', mesh: mapVectorMeshPoints(vectorEnvelopeMesh(e.params, bounds), full) } };\n\t\t}\n\t\tif (e.type === 'twist') return { ...e, params: { ...e.params, center: lin(e.params.center), angle: e.params.angle * mirror } };\n\t\tif (e.type === 'repeater')\n\t\t\treturn { ...e, params: { ...e.params, position: lin(e.params.position), anchor: lin(e.params.anchor), rotation: e.params.rotation * mirror } };\n\t\treturn e;\n\t});\n}\n\n/**\n * The live groups (live booleans and groups with effects) being edited: those in `ids` and those\n * holding a node in `ids`; mask groups only when they hold one. Their children are hit and outlined as stored instead of as drawn, so\n * each operand can be picked (figcraft `crates/engine/src/booleans.rs`, `result_outline`).\n */\nexport function vectorEnteredGroups(nodes: readonly VectorNode[], ids: readonly string[]): Set<string> {\n\tconst out = new Set<string>();\n\tif (!ids.length) return out;\n\tconst want = new Set(ids);\n\tconst visit = (list: readonly VectorNode[], live: readonly string[]) => {\n\t\tfor (const n of list) {\n\t\t\tconst own = n.type === 'group' && (hasOwnVectorAppearance(n) || isVectorMaskGroup(n));\n\t\t\tif (want.has(n.id)) {\n\t\t\t\tfor (const id of live) out.add(id);\n\t\t\t\t// A selected mask group stays clipped; selecting inside it opens it.\n\t\t\t\tif (own && hasOwnVectorAppearance(n)) out.add(n.id);\n\t\t\t}\n\t\t\tif (n.type === 'group') visit(n.children, own ? [...live, n.id] : live);\n\t\t}\n\t};\n\tvisit(nodes, []);\n\treturn out;\n}\n","/**\n * Vector path geometry: anchors and handles to Bézier paths and back, bounds, hit-testing,\n * affine transforms, segment splitting, anchor-type conversion and shape factories.\n */\nimport { isVectorGradient, transformVectorPaint } from './gradient.js';\nimport type { Point } from '../canvas/types.js';\nimport {\n\tbezierPathBounds,\n\tbezierPathToSvg,\n\ttransformBezierPath,\n\tdistanceToBezierPath,\n\tpointInBezierPath,\n\tsegmentNearest,\n\tsegmentPoint,\n\tsplitSegment,\n\ttoBezierPath,\n\ttype AffineMatrix,\n\ttype BezierPath,\n\ttype BezierPathInput\n} from '../canvas/pathops/bezier.js';\nimport {\n\tIDENTITY_MATRIX,\n\tapplyMatrix,\n\tapplyMatrixLinear,\n\tdecomposeRigid,\n\tinvertMatrix,\n\tisIdentityMatrix,\n\tmatrixRotation,\n\tmultiplyMatrices,\n\trotateMatrix,\n\tscaleMatrix,\n\ttranslateMatrix\n} from '../geom/affine.js';\nimport { expandVectorCorners, setSubpathCorners } from './corners.js';\nimport { hitTestVectorStroke, vectorStrokeOutlinePath } from './stroke.js';\nimport { mirrorWidthProfile } from './width.js';\nimport { hitTestVectorPaintStack } from './paintLayers.js';\nimport { expandVectorAppearance, hasOwnVectorAppearance, transformVectorEffects, vectorAppearanceOutline, vectorAppearanceShapes } from './appearance.js';\nimport { isVectorMaskActive, isVectorMaskGroup, vectorMaskContains } from './mask.js';\nimport type {\n\tVectorAnchor,\n\tVectorAnchorType,\n\tVectorCornerKind,\n\tVectorBounds,\n\tVectorDocument,\n\tVectorGroupNode,\n\tVectorNode,\n\tVectorPaint,\n\tVectorPathNode,\n\tVectorSubpath,\n\tVectorWidthPoint,\n\tVec2\n} from './types.js';\n\nexport type { AffineMatrix };\n\nconst EPS = 1e-9;\n\n// ---------------------------------------------------------------------------\n// Small helpers\n// ---------------------------------------------------------------------------\n\nexport const cloneAnchor = (a: VectorAnchor): VectorAnchor => ({\n\tx: a.x,\n\ty: a.y,\n\t...(a.in ? { in: { x: a.in.x, y: a.in.y } } : {}),\n\t...(a.out ? { out: { x: a.out.x, y: a.out.y } } : {}),\n\t...(a.type && a.type !== 'corner' ? { type: a.type } : {}),\n\t...(a.corner ? { corner: { ...a.corner } } : {})\n});\n\nexport const cloneSubpath = (s: VectorSubpath): VectorSubpath => ({ anchors: s.anchors.map(cloneAnchor), closed: s.closed });\n\n/** A deep copy of a node (ids kept). */\nexport function cloneVectorNode<T extends VectorNode>(node: T): T {\n\treturn JSON.parse(JSON.stringify(node)) as T;\n}\n\nexport function cloneVectorDocument(doc: VectorDocument): VectorDocument {\n\treturn JSON.parse(JSON.stringify(doc)) as VectorDocument;\n}\n\n/** True when the paint draws something (not `null`, `'none'`, `'transparent'` or empty). */\nexport function hasPaint(paint: VectorPaint | undefined): boolean {\n\tif (paint === undefined || paint === null) return false;\n\tif (typeof paint === 'string') {\n\t\tconst p = paint.trim().toLowerCase();\n\t\treturn p !== '' && p !== 'none' && p !== 'transparent';\n\t}\n\treturn true;\n}\n\nconst handleOf = (a: VectorAnchor, side: 'in' | 'out'): Vec2 => a[side] ?? { x: a.x, y: a.y };\nconst isOnAnchor = (a: VectorAnchor, h: Vec2 | null | undefined) => !h || (Math.abs(h.x - a.x) < EPS && Math.abs(h.y - a.y) < EPS);\n\n// ---------------------------------------------------------------------------\n// Anchors ↔ Bézier\n// ---------------------------------------------------------------------------\n\n/** Number of segments of a subpath (a closed one has a segment from the last anchor back to the first). */\nexport function subpathSegmentCount(sp: VectorSubpath): number {\n\tconst n = sp.anchors.length;\n\tif (n < 2) return 0;\n\treturn sp.closed ? n : n - 1;\n}\n\n/** Control points of segment `i` of a subpath: 2 for a line, 4 for a cubic. */\nexport function subpathSegment(sp: VectorSubpath, i: number): Point[] {\n\tconst a = sp.anchors[i];\n\tconst b = sp.anchors[(i + 1) % sp.anchors.length];\n\tif (isOnAnchor(a, a.out) && isOnAnchor(b, b.in)) return [[a.x, a.y], [b.x, b.y]];\n\tconst c1 = handleOf(a, 'out');\n\tconst c2 = handleOf(b, 'in');\n\treturn [[a.x, a.y], [c1.x, c1.y], [c2.x, c2.y], [b.x, b.y]];\n}\n\n/**\n * Absolute `M` / `L` / `C` / `Z` commands of subpaths, with live corners cut\n * (`expandVectorCorners`). Pass `{ corners: false }` for the stored anchors as they are.\n */\nexport function subpathsToBezier(subpaths: readonly VectorSubpath[], options: { corners?: boolean } = {}): BezierPath {\n\tconst out: BezierPath = [];\n\tfor (const sp of options.corners === false ? subpaths : expandVectorCorners(subpaths)) {\n\t\tif (sp.anchors.length === 0) continue;\n\t\tconst first = sp.anchors[0];\n\t\tout.push({ type: 'M', x: first.x, y: first.y });\n\t\tconst count = subpathSegmentCount(sp);\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tconst seg = subpathSegment(sp, i);\n\t\t\tif (sp.closed && i === count - 1 && seg.length === 2) break; // `Z` draws the closing line.\n\t\t\tif (seg.length === 2) out.push({ type: 'L', x: seg[1][0], y: seg[1][1] });\n\t\t\telse out.push({ type: 'C', x1: seg[1][0], y1: seg[1][1], x2: seg[2][0], y2: seg[2][1], x: seg[3][0], y: seg[3][1] });\n\t\t}\n\t\tif (sp.closed) out.push({ type: 'Z' });\n\t}\n\treturn out;\n}\n\n/** The node's outline as Bézier commands, as drawn (path effects applied). Groups have none. */\nexport function vectorNodeToBezier(node: VectorNode): BezierPath {\n\treturn node.type === 'path' ? vectorAppearanceOutline(node) : [];\n}\n\n/** SVG path data (`d`) of a path node or subpaths. */\nexport function vectorPathData(input: VectorPathNode | readonly VectorSubpath[], precision = 3): string {\n\tconst subpaths = Array.isArray(input) ? (input as readonly VectorSubpath[]) : (input as VectorPathNode).subpaths;\n\treturn bezierPathToSvg(subpathsToBezier(subpaths), { precision });\n}\n\n/** Infers the anchor type from its handles. */\nexport function inferAnchorType(a: VectorAnchor): VectorAnchorType {\n\tif (isOnAnchor(a, a.in) || isOnAnchor(a, a.out)) return 'corner';\n\tconst ix = a.in!.x - a.x;\n\tconst iy = a.in!.y - a.y;\n\tconst ox = a.out!.x - a.x;\n\tconst oy = a.out!.y - a.y;\n\tconst li = Math.hypot(ix, iy);\n\tconst lo = Math.hypot(ox, oy);\n\tconst cross = (ix * oy - iy * ox) / (li * lo);\n\tconst dot = (ix * ox + iy * oy) / (li * lo);\n\tif (Math.abs(cross) > 1e-3 || dot > 0) return 'corner';\n\treturn Math.abs(li - lo) <= 1e-3 * Math.max(li, lo) ? 'symmetric' : 'smooth';\n}\n\n/**\n * Converts SVG path data or Bézier commands to editable subpaths. Quadratics become cubics,\n * arcs become cubics, a closing anchor that repeats the first one is merged into it, and\n * each anchor's type is inferred from its handles.\n */\nexport function bezierToSubpaths(input: BezierPathInput): VectorSubpath[] {\n\tconst path = toBezierPath(input);\n\tconst out: VectorSubpath[] = [];\n\tlet current: VectorSubpath | null = null;\n\tconst last = () => current!.anchors[current!.anchors.length - 1];\n\tfor (const cmd of path) {\n\t\tswitch (cmd.type) {\n\t\t\tcase 'M':\n\t\t\t\tcurrent = { anchors: [{ x: cmd.x, y: cmd.y }], closed: false };\n\t\t\t\tout.push(current);\n\t\t\t\tbreak;\n\t\t\tcase 'L':\n\t\t\t\tcurrent!.anchors.push({ x: cmd.x, y: cmd.y });\n\t\t\t\tbreak;\n\t\t\tcase 'Q': {\n\t\t\t\tconst p0 = last();\n\t\t\t\tp0.out = { x: p0.x + (2 / 3) * (cmd.x1 - p0.x), y: p0.y + (2 / 3) * (cmd.y1 - p0.y) };\n\t\t\t\tcurrent!.anchors.push({ x: cmd.x, y: cmd.y, in: { x: cmd.x + (2 / 3) * (cmd.x1 - cmd.x), y: cmd.y + (2 / 3) * (cmd.y1 - cmd.y) } });\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'C':\n\t\t\t\tlast().out = { x: cmd.x1, y: cmd.y1 };\n\t\t\t\tcurrent!.anchors.push({ x: cmd.x, y: cmd.y, in: { x: cmd.x2, y: cmd.y2 } });\n\t\t\t\tbreak;\n\t\t\tcase 'Z': {\n\t\t\t\tif (!current) break;\n\t\t\t\tcurrent.closed = true;\n\t\t\t\tconst anchors = current.anchors;\n\t\t\t\tif (anchors.length > 1) {\n\t\t\t\t\tconst first = anchors[0];\n\t\t\t\t\tconst end = anchors[anchors.length - 1];\n\t\t\t\t\tif (Math.abs(end.x - first.x) < 1e-7 && Math.abs(end.y - first.y) < 1e-7) {\n\t\t\t\t\t\tif (end.in) first.in = end.in;\n\t\t\t\t\t\tanchors.pop();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcurrent = null;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tfor (const sp of out) {\n\t\tfor (const a of sp.anchors) {\n\t\t\tif (isOnAnchor(a, a.in)) delete a.in;\n\t\t\tif (isOnAnchor(a, a.out)) delete a.out;\n\t\t\tconst type = inferAnchorType(a);\n\t\t\tif (type !== 'corner') a.type = type;\n\t\t}\n\t}\n\treturn out.filter((sp) => sp.anchors.length > 0);\n}\n\n// ---------------------------------------------------------------------------\n// Tree helpers\n// ---------------------------------------------------------------------------\n\n/** Calls `fn` for every node, depth first, parents before children. */\nexport function walkVectorNodes(nodes: readonly VectorNode[], fn: (node: VectorNode, parent: VectorGroupNode | null, depth: number) => void): void {\n\tconst visit = (list: readonly VectorNode[], parent: VectorGroupNode | null, depth: number) => {\n\t\tfor (const node of list) {\n\t\t\tfn(node, parent, depth);\n\t\t\tif (node.type === 'group') visit(node.children, node, depth + 1);\n\t\t}\n\t};\n\tvisit(nodes, null, 0);\n}\n\n/** Finds a node by id anywhere in the tree. */\nexport function findVectorNode(nodes: readonly VectorNode[], id: string): VectorNode | undefined {\n\tfor (const node of nodes) {\n\t\tif (node.id === id) return node;\n\t\tif (node.type === 'group') {\n\t\t\tconst found = findVectorNode(node.children, id);\n\t\t\tif (found) return found;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/** The list that contains node `id` (the root list or a group's children) and its index there. */\nexport function locateVectorNode(nodes: VectorNode[], id: string): { list: VectorNode[]; index: number; parent: VectorGroupNode | null } | null {\n\tconst search = (list: VectorNode[], parent: VectorGroupNode | null): ReturnType<typeof locateVectorNode> => {\n\t\tfor (let i = 0; i < list.length; i++) {\n\t\t\tconst node = list[i];\n\t\t\tif (node.id === id) return { list, index: i, parent };\n\t\t\tif (node.type === 'group') {\n\t\t\t\tconst found = search(node.children, node);\n\t\t\t\tif (found) return found;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t};\n\treturn search(nodes, null);\n}\n\n/** Every path node in the subtree (a path node itself, or a group's descendants). */\nexport function collectPathNodes(node: VectorNode): VectorPathNode[] {\n\tif (node.type === 'path') return [node];\n\tconst out: VectorPathNode[] = [];\n\twalkVectorNodes(node.children, (n) => {\n\t\tif (n.type === 'path') out.push(n);\n\t});\n\treturn out;\n}\n\n// ---------------------------------------------------------------------------\n// Bounds\n// ---------------------------------------------------------------------------\n\n/** The node's local → parent matrix (identity when it has no `transform`). */\nexport function nodeMatrix(node: VectorNode): AffineMatrix {\n\treturn node.transform ?? IDENTITY_MATRIX;\n}\n\n/**\n * A path node's outline in the space `parent` maps to (default: its parent's space), as drawn:\n * live corners cut and path effects applied (`{ effects: false }`: the stored path only).\n */\nexport function vectorPathWorldBezier(node: VectorPathNode, parent: AffineMatrix = IDENTITY_MATRIX, options: { effects?: boolean } = {}): BezierPath {\n\tconst m = multiplyMatrices(nodeMatrix(node), parent);\n\tconst path = options.effects === false || !hasOwnVectorAppearance(node) ? subpathsToBezier(node.subpaths) : vectorAppearanceOutline(node);\n\treturn isIdentityMatrix(m) ? path : transformBezierPath(path, m);\n}\n\n/**\n * Geometric bounds of a node (stroke width not included) in the space `parent` maps to —\n * by default the node's parent space, which for top-level nodes is the document. Null when\n * the node has no points. A mask group is bounded by its masked result.\n */\nexport function vectorNodeBounds(node: VectorNode, parent: AffineMatrix = IDENTITY_MATRIX): VectorBounds | null {\n\tif (isVectorMaskActive(node)) {\n\t\tconst m = multiplyMatrices(nodeMatrix(node), parent);\n\t\tconst b = bezierPathBounds(vectorAppearanceShapes(node).flatMap((s) => (isIdentityMatrix(m) ? s.path : transformBezierPath(s.path, m))));\n\t\treturn b ? { x: b.minX, y: b.minY, width: b.maxX - b.minX, height: b.maxY - b.minY } : null;\n\t}\n\tnode = expandVectorAppearance(node);\n\tif (node.type === 'group') {\n\t\tconst m = multiplyMatrices(nodeMatrix(node), parent);\n\t\treturn unionBounds(node.children.map((c) => vectorNodeBounds(c, m)));\n\t}\n\tconst b = bezierPathBounds(vectorPathWorldBezier(node, parent));\n\tif (!b) return null;\n\treturn { x: b.minX, y: b.minY, width: b.maxX - b.minX, height: b.maxY - b.minY };\n}\n\n/** The smallest box around all non-null boxes, or null. */\nexport function unionBounds(list: readonly (VectorBounds | null | undefined)[]): VectorBounds | null {\n\tlet minX = Infinity;\n\tlet minY = Infinity;\n\tlet maxX = -Infinity;\n\tlet maxY = -Infinity;\n\tfor (const b of list) {\n\t\tif (!b) continue;\n\t\tminX = Math.min(minX, b.x);\n\t\tminY = Math.min(minY, b.y);\n\t\tmaxX = Math.max(maxX, b.x + b.width);\n\t\tmaxY = Math.max(maxY, b.y + b.height);\n\t}\n\tif (minX === Infinity) return null;\n\treturn { x: minX, y: minY, width: maxX - minX, height: maxY - minY };\n}\n\n/** True when two boxes overlap (touching counts). */\nexport function boundsIntersect(a: VectorBounds, b: VectorBounds): boolean {\n\treturn a.x <= b.x + b.width && b.x <= a.x + a.width && a.y <= b.y + b.height && b.y <= a.y + a.height;\n}\n\n/** A box from two corners in any order. */\nexport function boundsFromPoints(a: Vec2, b: Vec2): VectorBounds {\n\treturn { x: Math.min(a.x, b.x), y: Math.min(a.y, b.y), width: Math.abs(b.x - a.x), height: Math.abs(b.y - a.y) };\n}\n\n// ---------------------------------------------------------------------------\n// Hit-testing\n// ---------------------------------------------------------------------------\n\n/** Options of `hitTestVectorNode`. */\nexport interface VectorHitTestOptions {\n\t/**\n\t * Live groups (live booleans or groups with effects) hit by their children as stored rather\n\t * than by what they draw: the groups being edited.\n\t */\n\tentered?: ReadonlySet<string>;\n}\n\n/**\n * Whether `p` hits a node as drawn (path effects and live booleans applied): inside its fill\n * (when it has one), on its stroke (its alignment and arrowheads respected) or within\n * `tolerance` of either. A group is hit when any visible child is; a mask group when a child\n * above the mask is, where the mask lets it through. An entered mask group is hit by its children\n * as stored, the mask by its outline when it clips.\n */\nexport function hitTestVectorNode(node: VectorNode, p: Vec2, tolerance = 0, parent: AffineMatrix = IDENTITY_MATRIX, options: VectorHitTestOptions = {}): boolean {\n\tif (node.visible === false) return false;\n\tif (isVectorMaskGroup(node)) {\n\t\tconst m = multiplyMatrices(nodeMatrix(node), parent);\n\t\tconst entered = !!options.entered?.has(node.id);\n\t\tif (!entered && isVectorMaskActive(node) && !vectorMaskContains(node, applyMatrix(invertMatrix(m), p), tolerance)) return false;\n\t\t// With effects, the contents hit as drawn (unless entered).\n\t\tconst shown = !entered && hasOwnVectorAppearance(node) ? (expandVectorAppearance(node) as VectorGroupNode).children : node.children;\n\t\tfor (let i = shown.length - 1; i >= 1; i--) if (hitTestVectorNode(shown[i], p, tolerance, m, options)) return true;\n\t\treturn entered && hitTestVectorMaskSource(node, p, tolerance, m, options);\n\t}\n\t// Plain groups recurse as stored, so an entered live group deeper down still hits by its children.\n\tif (!(node.type === 'group' && (!hasOwnVectorAppearance(node) || options.entered?.has(node.id)))) node = expandVectorAppearance(node);\n\tif (node.type === 'group') {\n\t\tconst m = multiplyMatrices(nodeMatrix(node), parent);\n\t\treturn node.children.some((c) => hitTestVectorNode(c, p, tolerance, m, options));\n\t}\n\tconst path = vectorPathWorldBezier(node, parent);\n\tif (path.length === 0) return false;\n\t// Every drawn fill and stroke layer counts (hidden layers don't).\n\treturn hitTestVectorPaintStack(node, path, p, tolerance);\n}\n\n/** Whether `p` hits an entered mask group's mask: as drawn for an opacity mask, by its outline (any paint) for a clip. */\nfunction hitTestVectorMaskSource(group: VectorGroupNode, p: Vec2, tolerance: number, m: AffineMatrix, options: VectorHitTestOptions): boolean {\n\tconst source = group.children[0];\n\tif (source.visible === false) return false;\n\tif (group.mask?.type !== 'clip') return hitTestVectorNode(source, p, tolerance, m, options);\n\tconst paths = collectPathNodes(source).filter((n) => n.visible !== false);\n\tconst pt: [number, number] = [p.x, p.y];\n\treturn paths.some((n) => {\n\t\tconst world = vectorParentMatrix([source], n.id);\n\t\tconst path = vectorPathWorldBezier(n, multiplyMatrices(world ?? IDENTITY_MATRIX, m));\n\t\treturn pointInBezierPath(path, pt, n.fillRule ?? 'nonzero') || distanceToBezierPath(path, pt) <= tolerance;\n\t});\n}\n\n/**\n * The area a path node's stroke paints (alignment, caps, joins, dashes and arrowheads\n * included), as a filled path in the space `parent` maps to. Empty without a stroke.\n */\nexport function vectorStrokeOutline(node: VectorPathNode, parent: AffineMatrix = IDENTITY_MATRIX): BezierPath {\n\tif (!hasPaint(node.stroke) || !((node.strokeWidth ?? 1) > 0)) return [];\n\treturn vectorStrokeOutlinePath(vectorPathWorldBezier(node, parent), node);\n}\n\n/** The topmost node hit by `p` (skipping hidden and locked ones), or null. */\nexport function hitTestVectorNodes(nodes: readonly VectorNode[], p: Vec2, tolerance = 0, options: VectorHitTestOptions = {}): VectorNode | null {\n\tfor (let i = nodes.length - 1; i >= 0; i--) {\n\t\tconst node = nodes[i];\n\t\tif (node.visible === false || node.locked) continue;\n\t\tif (hitTestVectorNode(node, p, tolerance, IDENTITY_MATRIX, options)) return node;\n\t}\n\treturn null;\n}\n\nexport interface NearestSegment {\n\tsubpath: number;\n\tsegment: number;\n\t/** Curve parameter 0–1 on the segment. */\n\tt: number;\n\tpoint: Vec2;\n\tdistance: number;\n}\n\n/** The closest point on any segment of a path node (`p` and the result are in the node's own space). */\nexport function nearestSegment(node: VectorPathNode, p: Vec2): NearestSegment | null {\n\tlet best: NearestSegment | null = null;\n\tnode.subpaths.forEach((sp, s) => {\n\t\tconst count = subpathSegmentCount(sp);\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tconst seg = subpathSegment(sp, i);\n\t\t\tconst hit = segmentNearest(seg, [p.x, p.y]);\n\t\t\tif (!best || hit.distance < best.distance) {\n\t\t\t\tconst pt = segmentPoint(seg, hit.t);\n\t\t\t\tbest = { subpath: s, segment: i, t: hit.t, point: { x: pt[0], y: pt[1] }, distance: hit.distance };\n\t\t\t}\n\t\t}\n\t});\n\treturn best;\n}\n\n// ---------------------------------------------------------------------------\n// Affine transforms\n// ---------------------------------------------------------------------------\n\n// The matrix maths is shared with the image editor (`src/geom/affine.ts`).\nexport {\n\tIDENTITY_MATRIX,\n\tmultiplyMatrices,\n\ttranslateMatrix,\n\tscaleMatrix,\n\trotateMatrix,\n\tapplyMatrix,\n\tisIdentityMatrix,\n\tinvertMatrix,\n\tapplyMatrixLinear,\n\tmatrixRotation,\n\tdecomposeRigid\n};\n\nfunction mapAnchor(a: VectorAnchor, m: AffineMatrix): VectorAnchor {\n\tconst p = applyMatrix(m, a);\n\tconst next: VectorAnchor = { x: p.x, y: p.y };\n\tif (a.in) next.in = applyMatrix(m, a.in);\n\tif (a.out) next.out = applyMatrix(m, a.out);\n\tif (a.type) next.type = a.type;\n\tif (a.corner) next.corner = { ...a.corner };\n\treturn next;\n}\n\n/** Every anchor and handle mapped through `m` (the node's own `transform` is untouched). */\nfunction bakeIntoGeometry<T extends VectorNode>(node: T, m: AffineMatrix): T {\n\tif (isIdentityMatrix(m)) return node;\n\tif (node.effects?.length) node = { ...node, effects: transformVectorEffects(node.effects, m, node) } as T;\n\tif (node.type === 'group') {\n\t\tconst group = node as VectorGroupNode;\n\t\tconst children = group.children.map((c) => transformVectorNode(c, m));\n\t\t// A blend's replaced spine lives in the group's space too.\n\t\tconst spine = group.blend?.spine;\n\t\tif (!spine) return { ...group, children } as T;\n\t\tconst moved = { closed: spine.closed, anchors: spine.anchors.map((a) => mapAnchor(a, m)) };\n\t\treturn { ...group, children, blend: { ...group.blend, spine: moved } } as T;\n\t}\n\tconst path = node as VectorPathNode;\n\t// A mirror swaps the sides of a variable-width stroke (the path still runs the same way).\n\tconst flips = m[0] * m[3] - m[1] * m[2] < 0;\n\tconst mirrored = flips && path.strokeWidthProfile?.length;\n\t// Each layer of a stack: its gradient moves with the geometry, its profile mirrors.\n\tconst layer = <L extends { paint: VectorPaint; strokeWidthProfile?: VectorWidthPoint[] | null }>(l: L): L => ({\n\t\t...l,\n\t\t...(isVectorGradient(l.paint) ? { paint: transformVectorPaint(l.paint, m) } : {}),\n\t\t...(flips && l.strokeWidthProfile?.length ? { strokeWidthProfile: mirrorWidthProfile(l.strokeWidthProfile) } : {})\n\t});\n\treturn {\n\t\t...path,\n\t\t...(mirrored ? { strokeWidthProfile: mirrorWidthProfile(path.strokeWidthProfile!) } : {}),\n\t\t// Gradients in the node's own space move with its geometry.\n\t\t...(isVectorGradient(path.fill) ? { fill: transformVectorPaint(path.fill, m) } : {}),\n\t\t...(isVectorGradient(path.stroke) ? { stroke: transformVectorPaint(path.stroke, m) } : {}),\n\t\t...(Array.isArray(path.fills) ? { fills: path.fills.map(layer) } : {}),\n\t\t...(Array.isArray(path.strokes) ? { strokes: path.strokes.map(layer) } : {}),\n\t\tsubpaths: path.subpaths.map((sp) => ({\n\t\t\tclosed: sp.closed,\n\t\t\tanchors: sp.anchors.map((a) => mapAnchor(a, m))\n\t\t}))\n\t} as T;\n}\n\n/**\n * A copy of the node moved by `m`, given in its parent's space. The node's rotation and\n * translation go to its rigid `transform`; scale and skew are baked into its anchors (or its\n * children), so the result draws exactly as `m` says. Stroke widths are kept.\n */\nexport function transformVectorNode<T extends VectorNode>(node: T, m: AffineMatrix): T {\n\tconst total = multiplyMatrices(nodeMatrix(node), m);\n\tconst { rigid, residual } = decomposeRigid(total);\n\tconst { transform: _old, ...rest } = node as VectorNode;\n\tconst baked = bakeIntoGeometry(rest as T, residual);\n\treturn isIdentityMatrix(rigid) ? baked : ({ ...baked, transform: rigid } as T);\n}\n\n/** The node's rotation in degrees (from its `transform` and its ancestors' when `parent` is given). */\nexport function vectorNodeRotation(node: VectorNode, parent: AffineMatrix = IDENTITY_MATRIX): number {\n\treturn matrixRotation(multiplyMatrices(nodeMatrix(node), parent));\n}\n\n/** The local → document matrix of node `id` (ancestors' transforms included), or null. */\nexport function vectorWorldMatrix(nodes: readonly VectorNode[], id: string): AffineMatrix | null {\n\tconst search = (list: readonly VectorNode[], parent: AffineMatrix): AffineMatrix | null => {\n\t\tfor (const n of list) {\n\t\t\tconst m = multiplyMatrices(nodeMatrix(n), parent);\n\t\t\tif (n.id === id) return m;\n\t\t\tif (n.type === 'group') {\n\t\t\t\tconst found = search(n.children, m);\n\t\t\t\tif (found) return found;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t};\n\treturn search(nodes, IDENTITY_MATRIX);\n}\n\n/** The parent space → document matrix of node `id` (identity for top-level nodes), or null. */\nexport function vectorParentMatrix(nodes: readonly VectorNode[], id: string): AffineMatrix | null {\n\tconst node = findVectorNode(nodes, id);\n\tconst world = vectorWorldMatrix(nodes, id);\n\tif (!node || !world) return null;\n\treturn multiplyMatrices(invertMatrix(nodeMatrix(node)), world);\n}\n\n// ---------------------------------------------------------------------------\n// Anchor editing\n// ---------------------------------------------------------------------------\n\n/** Moves an anchor and its handles by (dx, dy). */\nexport function translateAnchor(a: VectorAnchor, dx: number, dy: number): VectorAnchor {\n\tconst next = cloneAnchor(a);\n\tnext.x += dx;\n\tnext.y += dy;\n\tif (next.in) next.in = { x: next.in.x + dx, y: next.in.y + dy };\n\tif (next.out) next.out = { x: next.out.x + dx, y: next.out.y + dy };\n\treturn next;\n}\n\n/**\n * Moves one handle to `pos`, keeping the other in line for `smooth` anchors and mirrored for\n * `symmetric` ones. With `breakHandles` the anchor becomes a `corner` and only this handle moves.\n */\nexport function moveAnchorHandle(a: VectorAnchor, side: 'in' | 'out', pos: Vec2, breakHandles = false): VectorAnchor {\n\tconst next = cloneAnchor(a);\n\tnext[side] = { x: pos.x, y: pos.y };\n\tconst other = side === 'in' ? 'out' : 'in';\n\tconst type = breakHandles ? 'corner' : (a.type ?? 'corner');\n\tif (breakHandles) delete next.type;\n\tconst dx = pos.x - a.x;\n\tconst dy = pos.y - a.y;\n\tconst len = Math.hypot(dx, dy);\n\tif (type === 'symmetric') next[other] = { x: a.x - dx, y: a.y - dy };\n\telse if (type === 'smooth' && len > EPS) {\n\t\tconst o = a[other];\n\t\tconst olen = o ? Math.hypot(o.x - a.x, o.y - a.y) : len;\n\t\tnext[other] = { x: a.x - (dx / len) * olen, y: a.y - (dy / len) * olen };\n\t}\n\tif (isOnAnchor(next, next.in)) delete next.in;\n\tif (isOnAnchor(next, next.out)) delete next.out;\n\treturn next;\n}\n\n/**\n * Converts anchor `index` of a subpath. `corner` removes both handles; `smooth` and\n * `symmetric` keep existing handles in line, or add handles a third of the way to the\n * neighbours along the line between them.\n */\nexport function convertAnchor(sp: VectorSubpath, index: number, type: VectorAnchorType): VectorSubpath {\n\tconst anchors = sp.anchors.map(cloneAnchor);\n\tconst a = anchors[index];\n\tif (!a) return { anchors, closed: sp.closed };\n\tif (type === 'corner') {\n\t\tdelete a.in;\n\t\tdelete a.out;\n\t\tdelete a.type;\n\t\treturn { anchors, closed: sp.closed };\n\t}\n\tconst n = anchors.length;\n\tconst prev = index > 0 ? anchors[index - 1] : sp.closed ? anchors[n - 1] : null;\n\tconst next = index < n - 1 ? anchors[index + 1] : sp.closed ? anchors[0] : null;\n\tlet dir: Vec2 | null = null;\n\tlet lenIn = 0;\n\tlet lenOut = 0;\n\tif (!isOnAnchor(a, a.out)) dir = { x: a.out!.x - a.x, y: a.out!.y - a.y };\n\telse if (!isOnAnchor(a, a.in)) dir = { x: a.x - a.in!.x, y: a.y - a.in!.y };\n\telse if (prev && next) dir = { x: next.x - prev.x, y: next.y - prev.y };\n\telse if (next) dir = { x: next.x - a.x, y: next.y - a.y };\n\telse if (prev) dir = { x: a.x - prev.x, y: a.y - prev.y };\n\tif (!dir || Math.hypot(dir.x, dir.y) < EPS) return { anchors, closed: sp.closed };\n\tconst dl = Math.hypot(dir.x, dir.y);\n\tconst ux = dir.x / dl;\n\tconst uy = dir.y / dl;\n\tlenIn = a.in && !isOnAnchor(a, a.in) ? Math.hypot(a.in.x - a.x, a.in.y - a.y) : prev ? Math.hypot(prev.x - a.x, prev.y - a.y) / 3 : 0;\n\tlenOut = a.out && !isOnAnchor(a, a.out) ? Math.hypot(a.out.x - a.x, a.out.y - a.y) : next ? Math.hypot(next.x - a.x, next.y - a.y) / 3 : 0;\n\tif (type === 'symmetric') lenIn = lenOut = (lenIn + lenOut) / 2 || Math.max(lenIn, lenOut);\n\tif (lenIn > EPS) a.in = { x: a.x - ux * lenIn, y: a.y - uy * lenIn };\n\tif (lenOut > EPS) a.out = { x: a.x + ux * lenOut, y: a.y + uy * lenOut };\n\ta.type = type;\n\treturn { anchors, closed: sp.closed };\n}\n\n/**\n * Inserts an anchor on segment `segment` at parameter `t` without changing the curve's\n * shape (de Casteljau split). Returns the new subpath and the new anchor's index.\n */\nexport function insertAnchor(sp: VectorSubpath, segment: number, t: number): { subpath: VectorSubpath; index: number } {\n\tconst anchors = sp.anchors.map(cloneAnchor);\n\tconst n = anchors.length;\n\tconst ia = segment;\n\tconst ib = (segment + 1) % n;\n\tconst seg = subpathSegment(sp, segment);\n\tconst [left, right] = splitSegment(seg, t);\n\tconst mid = left[left.length - 1];\n\tconst anchor: VectorAnchor = { x: mid[0], y: mid[1] };\n\tif (seg.length === 4) {\n\t\tanchors[ia].out = { x: left[1][0], y: left[1][1] };\n\t\tanchor.in = { x: left[2][0], y: left[2][1] };\n\t\tanchor.out = { x: right[1][0], y: right[1][1] };\n\t\tanchor.type = 'smooth';\n\t\tanchors[ib].in = { x: right[2][0], y: right[2][1] };\n\t\tfor (const k of [ia, ib]) if (isOnAnchor(anchors[k], anchors[k].in)) delete anchors[k].in;\n\t\tfor (const k of [ia, ib]) if (isOnAnchor(anchors[k], anchors[k].out)) delete anchors[k].out;\n\t}\n\tconst index = segment + 1;\n\tanchors.splice(index, 0, anchor);\n\treturn { subpath: { anchors, closed: sp.closed }, index };\n}\n\n/**\n * Removes anchors from a subpath. An open subpath with fewer than 2 anchors left, or a\n * closed one with fewer than 2, is returned with whatever remains (callers drop empty ones).\n */\nexport function removeAnchors(sp: VectorSubpath, indices: readonly number[]): VectorSubpath {\n\tconst drop = new Set(indices);\n\treturn { anchors: sp.anchors.filter((_, i) => !drop.has(i)).map(cloneAnchor), closed: sp.closed };\n}\n\n/** Reverses a subpath's direction (handles swap sides). */\nexport function reverseSubpath(sp: VectorSubpath): VectorSubpath {\n\tconst anchors = sp.anchors\n\t\t.slice()\n\t\t.reverse()\n\t\t.map((a) => {\n\t\t\tconst next: VectorAnchor = { x: a.x, y: a.y };\n\t\t\tif (a.out) next.in = { ...a.out };\n\t\t\tif (a.in) next.out = { ...a.in };\n\t\t\tif (a.type) next.type = a.type;\n\t\t\tif (a.corner) next.corner = { ...a.corner };\n\t\t\treturn next;\n\t\t});\n\treturn { anchors, closed: sp.closed };\n}\n\n// ---------------------------------------------------------------------------\n// Shape factories\n// ---------------------------------------------------------------------------\n\n/** Handle length that makes a cubic approximate a quarter circle. */\nexport const KAPPA = 0.5522847498307936;\n\n/**\n * A rectangle. A `radius` becomes a live corner on each of its four anchors (drawn round, and\n * clamped to half the shorter side, when the path is turned into curves).\n */\nexport function rectSubpath(b: VectorBounds, radius = 0, kind?: VectorCornerKind): VectorSubpath {\n\tconst { x, y, width: w, height: h } = b;\n\tconst sp: VectorSubpath = { anchors: [{ x, y }, { x: x + w, y }, { x: x + w, y: y + h }, { x, y: y + h }], closed: true };\n\treturn radius > 0 ? setSubpathCorners(sp, radius, kind) : sp;\n}\n\n/** An ellipse inscribed in a box (four smooth anchors). */\nexport function ellipseSubpath(b: VectorBounds): VectorSubpath {\n\tconst rx = b.width / 2;\n\tconst ry = b.height / 2;\n\tconst cx = b.x + rx;\n\tconst cy = b.y + ry;\n\tconst kx = rx * KAPPA;\n\tconst ky = ry * KAPPA;\n\treturn {\n\t\tclosed: true,\n\t\tanchors: [\n\t\t\t{ x: cx, y: cy - ry, in: { x: cx - kx, y: cy - ry }, out: { x: cx + kx, y: cy - ry }, type: 'symmetric' },\n\t\t\t{ x: cx + rx, y: cy, in: { x: cx + rx, y: cy - ky }, out: { x: cx + rx, y: cy + ky }, type: 'symmetric' },\n\t\t\t{ x: cx, y: cy + ry, in: { x: cx + kx, y: cy + ry }, out: { x: cx - kx, y: cy + ry }, type: 'symmetric' },\n\t\t\t{ x: cx - rx, y: cy, in: { x: cx - rx, y: cy + ky }, out: { x: cx - rx, y: cy - ky }, type: 'symmetric' }\n\t\t]\n\t};\n}\n\n/** A regular polygon inscribed in a box, first vertex at the top. */\nexport function polygonSubpath(b: VectorBounds, sides = 6): VectorSubpath {\n\tconst n = Math.max(3, Math.round(sides));\n\tconst cx = b.x + b.width / 2;\n\tconst cy = b.y + b.height / 2;\n\tconst anchors: VectorAnchor[] = [];\n\tfor (let i = 0; i < n; i++) {\n\t\tconst t = -Math.PI / 2 + (i * 2 * Math.PI) / n;\n\t\tanchors.push({ x: cx + (Math.cos(t) * b.width) / 2, y: cy + (Math.sin(t) * b.height) / 2 });\n\t}\n\treturn { anchors, closed: true };\n}\n\n/** A star inscribed in a box, first point at the top. `innerRatio` is inner / outer radius. */\nexport function starSubpath(b: VectorBounds, points = 5, innerRatio = 0.5): VectorSubpath {\n\tconst n = Math.max(3, Math.round(points));\n\tconst cx = b.x + b.width / 2;\n\tconst cy = b.y + b.height / 2;\n\tconst anchors: VectorAnchor[] = [];\n\tfor (let i = 0; i < n * 2; i++) {\n\t\tconst t = -Math.PI / 2 + (i * Math.PI) / n;\n\t\tconst r = i % 2 === 0 ? 1 : innerRatio;\n\t\tanchors.push({ x: cx + (Math.cos(t) * r * b.width) / 2, y: cy + (Math.sin(t) * r * b.height) / 2 });\n\t}\n\treturn { anchors, closed: true };\n}\n\n/** A straight open line. */\nexport function lineSubpath(a: Vec2, b: Vec2): VectorSubpath {\n\treturn { anchors: [{ x: a.x, y: a.y }, { x: b.x, y: b.y }], closed: false };\n}\n\n/** Rounds every coordinate to `precision` decimals (stable JSON and SVG output). */\nexport function roundSubpaths(subpaths: readonly VectorSubpath[], precision = 3): VectorSubpath[] {\n\tconst f = 10 ** precision;\n\tconst r = (n: number) => Math.round(n * f) / f;\n\tconst rp = (p: Vec2) => ({ x: r(p.x), y: r(p.y) });\n\treturn subpaths.map((sp) => ({\n\t\tclosed: sp.closed,\n\t\tanchors: sp.anchors.map((a) => ({ ...cloneAnchor(a), x: r(a.x), y: r(a.y), ...(a.in ? { in: rp(a.in) } : {}), ...(a.out ? { out: rp(a.out) } : {}) }))\n\t}));\n}\n","/**\n * Path operators of live path effects (After Effects' \"Add ▸\" path operations). Each maps a list\n * of paths to a list of the same length (one per shape above the operator), except `mergePaths`,\n * which combines them into one, and `repeatPaths`, which makes copies. Paths are in the space of\n * the node the effect belongs to.\n *\n * Ported from ArtCraft (MIT OR Apache-2.0, © ArtCraft Team and contributors; see\n * THIRD_PARTY_NOTICES.md): effectcraft `crates/path/src/ops.rs` — `trim`, `trim_individually`,\n * `trim_intervals`, `Measured::append`, `pucker_bloat`, `round_corners`, `offset`, `twist`,\n * `resample`, `emit`, `zigzag`, `WiggleParams`, `splitmix`, `hash`, `noise`, `wiggle`, `MergeMode`\n * and `merge`; and the `\"repeater\"` branch of `collect()` in `crates/render/src/shapes.rs` (copy\n * transforms, opacity ramp, fractional last copy, offset and composite order). Arc lengths come\n * from our own `segmentLength` / `segmentParamAtLength` / `trimSegments`, offsets from\n * `offsetPath`, booleans from `pathBoolean`, and Round Corners uses the live-corner maths in\n * `corners.ts` (a true radius, exact at any angle, where a curve meets a corner too).\n */\nimport type { Point } from '../canvas/types.js';\nimport {\n\tbezierPathBounds,\n\tcloseContour,\n\tcontoursToPath,\n\tpathToContours,\n\tsegmentDerivative,\n\tsegmentLength,\n\tsegmentParamAtLength,\n\tsegmentPoint,\n\tsubSegment,\n\ttransformBezierPath,\n\ttrimSegments,\n\ttype AffineMatrix,\n\ttype BezierPath,\n\ttype BezierSegment\n} from '../canvas/pathops/bezier.js';\nimport { pathBoolean } from '../canvas/pathops/boolean.js';\nimport { offsetPath } from '../canvas/pathops/stroke.js';\nimport { setSubpathCorners } from './corners.js';\nimport { bezierToSubpaths, multiplyMatrices, rotateMatrix, scaleMatrix, subpathsToBezier, translateMatrix } from './geometry.js';\nimport type { Vec2, VectorEffectParamsMap, VectorLineJoin, VectorMergeMode } from './types.js';\n\nconst EPS = 1e-9;\n\n// ---------------------------------------------------------------------------\n// Subpath helpers\n// ---------------------------------------------------------------------------\n\n/** One subpath as cubic or line segments (quadratics raised), the closing line included. */\ninterface Sub {\n\tsegs: Point[][];\n\tclosed: boolean;\n}\n\nconst degenerate = (s: BezierSegment) => s.every((p) => Math.abs(p[0] - s[0][0]) < EPS && Math.abs(p[1] - s[0][1]) < EPS);\n\nfunction raise(seg: BezierSegment): Point[] {\n\tif (seg.length !== 3) return seg.map((p) => [p[0], p[1]] as Point);\n\tconst [p0, p1, p2] = seg;\n\treturn [p0, [p0[0] + (2 / 3) * (p1[0] - p0[0]), p0[1] + (2 / 3) * (p1[1] - p0[1])], [p2[0] + (2 / 3) * (p1[0] - p2[0]), p2[1] + (2 / 3) * (p1[1] - p2[1])], p2];\n}\n\n/** The path's subpaths with at least one segment (a closed one's closing line included). */\nfunction subsOf(path: BezierPath): Sub[] {\n\treturn pathToContours(path)\n\t\t.map((c) => ({ segs: closeContour(c).filter((s) => !degenerate(s)).map(raise), closed: c.closed }))\n\t\t.filter((s) => s.segs.length > 0);\n}\n\nconst subsToPath = (subs: readonly Sub[]): BezierPath => contoursToPath(subs.map((s) => ({ segments: s.segs, closed: s.closed })));\n\nconst unit = (x: number, y: number): Point | null => {\n\tconst l = Math.hypot(x, y);\n\treturn l > 1e-12 && Number.isFinite(l) ? [x / l, y / l] : null;\n};\n\n/** Direction a segment leaves its start in (robust at a handle on its anchor). */\nfunction startTangent(s: BezierSegment): Point {\n\tfor (let i = 1; i < s.length; i++) {\n\t\tconst u = unit(s[i][0] - s[0][0], s[i][1] - s[0][1]);\n\t\tif (u) return u;\n\t}\n\treturn [1, 0];\n}\n\n/** Direction a segment arrives at its end in. */\nfunction endTangent(s: BezierSegment): Point {\n\tconst end = s[s.length - 1];\n\tfor (let i = s.length - 2; i >= 0; i--) {\n\t\tconst u = unit(end[0] - s[i][0], end[1] - s[i][1]);\n\t\tif (u) return u;\n\t}\n\treturn [1, 0];\n}\n\nfunction tangentAt(s: BezierSegment, t: number): Point {\n\tif (t <= 1e-9) return startTangent(s);\n\tif (t >= 1 - 1e-9) return endTangent(s);\n\tconst d = segmentDerivative(s, t);\n\treturn unit(d[0], d[1]) ?? startTangent(s);\n}\n\nconst perp = (v: Point): Point => [-v[1], v[0]];\n\n/** Total arc length of a path (closing lines included). */\nexport function effectPathLength(path: BezierPath): number {\n\tlet total = 0;\n\tfor (const s of subsOf(path)) for (const seg of s.segs) total += segmentLength(seg);\n\treturn total;\n}\n\n/** Number of on-curve points of a path (a closed subpath's start counted once). */\nexport function effectPathVertexCount(path: BezierPath): number {\n\treturn subsOf(path).reduce((n, s) => n + s.segs.length + (s.closed ? 0 : 1), 0);\n}\n\n// ---------------------------------------------------------------------------\n// Trim Paths\n// ---------------------------------------------------------------------------\n\n/** A path measured for trimming: its segments end to end and their lengths. */\nclass Measured {\n\treadonly segs: Point[][];\n\treadonly lens: number[];\n\treadonly total: number;\n\tconstructor(path: BezierPath) {\n\t\tthis.segs = subsOf(path).flatMap((s) => s.segs);\n\t\tthis.lens = this.segs.map((s) => segmentLength(s));\n\t\tthis.total = this.lens.reduce((a, b) => a + b, 0);\n\t}\n\n\t/**\n\t * Appends the part between lengths `sa` and `sb`, continuing the last piece when this one\n\t * starts where it ends (across the start of a closed path).\n\t */\n\tappend(sa: number, sb: number, out: Sub[]) {\n\t\tfor (const piece of trimSegments(this.segs, sa, sb, this.lens)) {\n\t\t\tif (degenerate(piece)) continue;\n\t\t\tconst last = out[out.length - 1]?.segs;\n\t\t\tconst end = last?.[last.length - 1]?.at(-1);\n\t\t\tif (!end || Math.hypot(end[0] - piece[0][0], end[1] - piece[0][1]) > 1e-6) out.push({ segs: [piece], closed: false });\n\t\t\telse last!.push(piece);\n\t\t}\n\t}\n}\n\n/** The fractions of the length a trim keeps, or null when it keeps everything. */\nexport function trimIntervals(start: number, end: number, offsetDegrees: number): [number, number][] | null {\n\tlet s = start / 100;\n\tlet e = end / 100;\n\tif (!Number.isFinite(s) || !Number.isFinite(e)) return null;\n\tif (s > e) [s, e] = [e, s];\n\ts = Math.min(1, Math.max(0, s));\n\te = Math.min(1, Math.max(0, e));\n\tif (e - s >= 1 - 1e-9) return null;\n\tif (e - s <= 1e-9) return [];\n\tconst off = Number.isFinite(offsetDegrees) ? (((offsetDegrees / 360) % 1) + 1) % 1 : 0;\n\ts += off;\n\te += off;\n\tif (e <= 1) return [[s, e]];\n\tif (s >= 1) return [[s - 1, e - 1]];\n\treturn [\n\t\t[s, 1],\n\t\t[0, e - 1]\n\t];\n}\n\n/**\n * Trim Paths, simultaneously: every path is trimmed by the same fractions of its own length.\n * `start` / `end` in percent, `offset` in degrees. Paths trimmed away entirely come back empty.\n */\nexport function trimPaths(paths: readonly BezierPath[], start: number, end: number, offsetDegrees = 0): BezierPath[] {\n\tconst iv = trimIntervals(start, end, offsetDegrees);\n\tif (!iv) return paths.slice();\n\treturn paths.map((p) => {\n\t\tconst m = new Measured(p);\n\t\tconst out: Sub[] = [];\n\t\tif (m.total > 0) for (const [a, b] of iv) m.append(a * m.total, b * m.total, out);\n\t\treturn subsToPath(out);\n\t});\n}\n\n/**\n * Trim Paths, individually: the paths are laid end to end in stacking order and trimmed as one\n * length, so they draw on one after another.\n */\nexport function trimPathsIndividually(paths: readonly BezierPath[], start: number, end: number, offsetDegrees = 0): BezierPath[] {\n\tconst iv = trimIntervals(start, end, offsetDegrees);\n\tif (!iv) return paths.slice();\n\tconst ms = paths.map((p) => new Measured(p));\n\tconst total = ms.reduce((n, m) => n + m.total, 0);\n\tlet base = 0;\n\treturn ms.map((m) => {\n\t\tconst out: Sub[] = [];\n\t\tfor (const [a, b] of iv) {\n\t\t\tconst la = Math.max(0, a * total - base);\n\t\t\tconst lb = Math.min(m.total, b * total - base);\n\t\t\tif (lb > la) m.append(la, lb, out);\n\t\t}\n\t\tbase += m.total;\n\t\treturn subsToPath(out);\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Pucker & Bloat\n// ---------------------------------------------------------------------------\n\n/**\n * Pucker & Bloat (`amount` in percent, −100 to 100). Positive (bloat) moves the points towards\n * the mean of a path's points and pushes the handles away from it, so the segments bulge\n * outwards; negative (pucker) does the opposite, giving spiky shapes.\n */\nexport function puckerBloatPaths(paths: readonly BezierPath[], amount: number): BezierPath[] {\n\tconst a = amount / 100;\n\tif (!a || !Number.isFinite(a)) return paths.slice();\n\treturn paths.map((p) => {\n\t\tconst verts = p.filter((c) => c.type !== 'Z') as Exclude<BezierPath[number], { type: 'Z' }>[];\n\t\tif (!verts.length) return p;\n\t\tconst cx = verts.reduce((s, c) => s + c.x, 0) / verts.length;\n\t\tconst cy = verts.reduce((s, c) => s + c.y, 0) / verts.length;\n\t\tconst mv = (x: number, y: number) => ({ x: x + (cx - x) * a, y: y + (cy - y) * a });\n\t\tconst mvh = (x: number, y: number) => ({ x: x + (x - cx) * a, y: y + (y - cy) * a });\n\t\tconst out: BezierPath = [];\n\t\tlet prev = { x: 0, y: 0 };\n\t\tlet start = { x: 0, y: 0 };\n\t\tconst curve = (c1: Vec2, c2: Vec2, q: Vec2) => {\n\t\t\tconst h1 = mvh(c1.x, c1.y);\n\t\t\tconst h2 = mvh(c2.x, c2.y);\n\t\t\tconst e = mv(q.x, q.y);\n\t\t\tout.push({ type: 'C', x1: h1.x, y1: h1.y, x2: h2.x, y2: h2.y, x: e.x, y: e.y });\n\t\t};\n\t\tfor (const c of p) {\n\t\t\tswitch (c.type) {\n\t\t\t\tcase 'M': {\n\t\t\t\t\tconst e = mv(c.x, c.y);\n\t\t\t\t\tout.push({ type: 'M', x: e.x, y: e.y });\n\t\t\t\t\tprev = start = { x: c.x, y: c.y };\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 'L':\n\t\t\t\t\tcurve(prev, c, c);\n\t\t\t\t\tprev = { x: c.x, y: c.y };\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'Q': {\n\t\t\t\t\tconst c1 = { x: prev.x + (2 / 3) * (c.x1 - prev.x), y: prev.y + (2 / 3) * (c.y1 - prev.y) };\n\t\t\t\t\tconst c2 = { x: c.x + (2 / 3) * (c.x1 - c.x), y: c.y + (2 / 3) * (c.y1 - c.y) };\n\t\t\t\t\tcurve(c1, c2, c);\n\t\t\t\t\tprev = { x: c.x, y: c.y };\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 'C':\n\t\t\t\t\tcurve({ x: c.x1, y: c.y1 }, { x: c.x2, y: c.y2 }, c);\n\t\t\t\t\tprev = { x: c.x, y: c.y };\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'Z':\n\t\t\t\t\t// The implicit closing line becomes a curve too.\n\t\t\t\t\tif (Math.hypot(prev.x - start.x, prev.y - start.y) > EPS) curve(prev, start, start);\n\t\t\t\t\tout.push({ type: 'Z' });\n\t\t\t\t\tprev = start;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn out;\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Round Corners\n// ---------------------------------------------------------------------------\n\n/**\n * Round Corners: every corner (where the direction jumps) gets a circular arc of `radius`,\n * shrunk to fit where the sides are short. Smooth points and the ends of open paths are kept.\n */\nexport function roundCornerPaths(paths: readonly BezierPath[], radius: number): BezierPath[] {\n\tif (!(radius > 0) || !Number.isFinite(radius)) return paths.slice();\n\treturn paths.map((p) => subpathsToBezier(bezierToSubpaths(p).map((sp) => setSubpathCorners(sp, radius))));\n}\n\n// ---------------------------------------------------------------------------\n// Offset Paths\n// ---------------------------------------------------------------------------\n\n/**\n * Offset Paths: grows (positive `amount`) or shrinks (negative) every path with the given join.\n * `copies` copies are made, copy i offset by `amount · (i + 1 + copyOffset)`, all in one path.\n */\nexport function offsetPaths(paths: readonly BezierPath[], amount: number, join: VectorLineJoin = 'miter', miterLimit = 4, copies = 1, copyOffset = 0): BezierPath[] {\n\tconst n = Math.min(1000, Math.max(1, Math.round(Number.isFinite(copies) ? copies : 1)));\n\treturn paths.map((p) => {\n\t\tconst out: BezierPath = [];\n\t\tfor (let i = 0; i < n; i++) out.push(...offsetPath(p, amount * (i + 1 + copyOffset), { join, miterLimit }));\n\t\treturn out;\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Twist\n// ---------------------------------------------------------------------------\n\n/**\n * Twist: turns the paths about `center` by an angle growing with the distance from it, from 0\n * at the centre to `angle` degrees at the farthest point. Segments are subdivided and their\n * handles mapped through the warp's derivative, which keeps the result smooth.\n */\nexport function twistPaths(paths: readonly BezierPath[], angle: number, center: Vec2): BezierPath[] {\n\tlet rmax = 0;\n\tfor (const p of paths) for (const c of p) if (c.type !== 'Z') rmax = Math.max(rmax, Math.hypot(c.x - center.x, c.y - center.y));\n\tconst a = (angle * Math.PI) / 180;\n\tif (!a || rmax <= 1e-9 || !Number.isFinite(a)) return paths.slice();\n\tconst k = a / rmax;\n\tconst rot = (v: Point, th: number): Point => {\n\t\tconst s = Math.sin(th);\n\t\tconst co = Math.cos(th);\n\t\treturn [v[0] * co - v[1] * s, v[0] * s + v[1] * co];\n\t};\n\tconst map = (p: Point): Point => {\n\t\tconst v: Point = [p[0] - center.x, p[1] - center.y];\n\t\tconst r = rot(v, k * Math.hypot(v[0], v[1]));\n\t\treturn [center.x + r[0], center.y + r[1]];\n\t};\n\t// The warp's derivative at `p` applied to `dv`.\n\tconst jac = (p: Point, dv: Point): Point => {\n\t\tconst v: Point = [p[0] - center.x, p[1] - center.y];\n\t\tconst r = Math.hypot(v[0], v[1]);\n\t\tlet w = dv;\n\t\tif (r > 1e-12) {\n\t\t\tconst f = (k * (v[0] * dv[0] + v[1] * dv[1])) / r;\n\t\t\tw = [dv[0] - v[1] * f, dv[1] + v[0] * f];\n\t\t}\n\t\treturn rot(w, k * r);\n\t};\n\treturn paths.map((p) => {\n\t\tconst out: Sub[] = [];\n\t\tfor (const sub of subsOf(p)) {\n\t\t\tconst segs: Point[][] = [];\n\t\t\tfor (const seg of sub.segs) {\n\t\t\t\tconst cubic = seg.length === 2 ? [seg[0], seg[0], seg[1], seg[1]] : seg;\n\t\t\t\tconst len = segmentLength(seg);\n\t\t\t\tconst m = Math.min(64, Math.max(1, Math.ceil((Math.abs(a) * len) / rmax / 0.15 + len / 50)));\n\t\t\t\tfor (let i = 0; i < m; i++) {\n\t\t\t\t\tconst q = subSegment(cubic, i / m, (i + 1) / m);\n\t\t\t\t\tconst p0 = map(q[0]);\n\t\t\t\t\tconst p3 = map(q[3]);\n\t\t\t\t\tconst h1 = jac(q[0], [q[1][0] - q[0][0], q[1][1] - q[0][1]]);\n\t\t\t\t\tconst h2 = jac(q[3], [q[2][0] - q[3][0], q[2][1] - q[3][1]]);\n\t\t\t\t\tsegs.push([p0, [p0[0] + h1[0], p0[1] + h1[1]], [p3[0] + h2[0], p3[1] + h2[1]], p3]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tout.push({ segs, closed: sub.closed });\n\t\t}\n\t\treturn subsToPath(out);\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Resampling (Zig Zag, Wiggle Paths)\n// ---------------------------------------------------------------------------\n\ninterface Sample {\n\tp: Point;\n\ttan: Point;\n\t/** Length of the piece before / after this sample. */\n\tlenPrev: number;\n\tlenNext: number;\n}\n\n/**\n * Splits every segment into `m` pieces of equal arc length. Original points get the average\n * of their incoming and outgoing directions (so a corner's normal is its bisector).\n */\nfunction resample(sub: Sub, m: number): Sample[] {\n\tconst segs = sub.segs;\n\tconst n = segs.length;\n\tconst lens = segs.map((s) => segmentLength(s));\n\tconst out: Sample[] = [];\n\tfor (let j = 0; j < n; j++) {\n\t\tconst piece = lens[j] / m;\n\t\tfor (let k = 0; k < m; k++) {\n\t\t\tif (k === 0) {\n\t\t\t\tconst tout = startTangent(segs[j]);\n\t\t\t\tconst prev = sub.closed || j > 0 ? (j + n - 1) % n : null;\n\t\t\t\tlet tan = tout;\n\t\t\t\tif (prev !== null) {\n\t\t\t\t\tconst tin = endTangent(segs[prev]);\n\t\t\t\t\ttan = unit(tin[0] + tout[0], tin[1] + tout[1]) ?? tout;\n\t\t\t\t}\n\t\t\t\tout.push({ p: segs[j][0], tan, lenPrev: prev === null ? 0 : lens[prev] / m, lenNext: piece });\n\t\t\t} else {\n\t\t\t\tconst t = segmentParamAtLength(segs[j], piece * k, lens[j]);\n\t\t\t\tout.push({ p: segmentPoint(segs[j], t), tan: tangentAt(segs[j], t), lenPrev: piece, lenNext: piece });\n\t\t\t}\n\t\t}\n\t}\n\tif (!sub.closed) {\n\t\tconst last = segs[n - 1];\n\t\tout.push({ p: last[last.length - 1], tan: endTangent(last), lenPrev: lens[n - 1] / m, lenNext: 0 });\n\t}\n\treturn out;\n}\n\n/** Displaced samples as corner (polyline) or smooth (tangent-aligned cubic) points; `handle` is a fraction of the pieces. */\nfunction emit(samples: readonly Sample[], disp: readonly Point[], closed: boolean, smooth: boolean, handle: number): Sub | null {\n\tconst n = samples.length;\n\tif (!n) return null;\n\tconst pt = (i: number): Point => [samples[i].p[0] + disp[i][0], samples[i].p[1] + disp[i][1]];\n\tconst segs: Point[][] = [];\n\tconst count = closed ? n : n - 1;\n\tfor (let i = 0; i < count; i++) {\n\t\tconst j = (i + 1) % n;\n\t\tconst a = samples[i];\n\t\tconst b = samples[j];\n\t\tconst p = pt(i);\n\t\tconst q = pt(j);\n\t\tif (smooth) segs.push([p, [p[0] + a.tan[0] * a.lenNext * handle, p[1] + a.tan[1] * a.lenNext * handle], [q[0] - b.tan[0] * b.lenPrev * handle, q[1] - b.tan[1] * b.lenPrev * handle], q]);\n\t\telse segs.push([p, q]);\n\t}\n\tif (!segs.length) return null;\n\treturn { segs, closed };\n}\n\n/**\n * Zig Zag: every segment gets `ridges` ridges: it is split into `ridges + 1` equal pieces and the\n * points (original ones included) are pushed alternately `size` to either side of the path.\n * `smooth` makes rounded waves. A closed path of n segments ends up with `n · (ridges + 1)` points\n * (an open one, one more).\n */\nexport function zigzagPaths(paths: readonly BezierPath[], size: number, ridges: number, smooth = false): BezierPath[] {\n\tconst m = Math.min(1000, Math.max(0, Math.round(Number.isFinite(ridges) ? ridges : 0))) + 1;\n\treturn paths.map((p) => {\n\t\tconst out: Sub[] = [];\n\t\tfor (const sub of subsOf(p)) {\n\t\t\tconst s = resample(sub, m);\n\t\t\tconst disp = s.map((x, i) => {\n\t\t\t\tconst n = perp(x.tan);\n\t\t\t\tconst d = i % 2 === 0 ? size : -size;\n\t\t\t\treturn [n[0] * d, n[1] * d] as Point;\n\t\t\t});\n\t\t\tconst e = emit(s, disp, sub.closed, smooth, 0.36);\n\t\t\tif (e) out.push(e);\n\t\t}\n\t\treturn subsToPath(out);\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Wiggle Paths\n// ---------------------------------------------------------------------------\n\nconst MASK64 = (1n << 64n) - 1n;\n\nfunction splitmix(x: bigint): bigint {\n\tx = (x + 0x9e3779b97f4a7c15n) & MASK64;\n\tlet z = x;\n\tz = ((z ^ (z >> 30n)) * 0xbf58476d1ce4e5b9n) & MASK64;\n\tz = ((z ^ (z >> 27n)) * 0x94d049bb133111ebn) & MASK64;\n\treturn z ^ (z >> 31n);\n}\n\n/** Deterministic hash → [−1, 1]. */\nfunction hash(seed: bigint, idx: bigint, t: number): number {\n\tconst h = splitmix(splitmix(splitmix(seed) ^ idx) ^ BigInt.asUintN(64, BigInt(t)));\n\treturn (Number(h >> 11n) / 2 ** 53) * 2 - 1;\n}\n\n/** Smooth 1D value noise in [−1, 1]: Catmull-Rom through hashed lattice values (C1 in time). */\nfunction noise(seed: bigint, idx: bigint, t: number): number {\n\tconst i = Math.floor(t);\n\tconst f = t - i;\n\tconst p0 = hash(seed, idx, i - 1);\n\tconst p1 = hash(seed, idx, i);\n\tconst p2 = hash(seed, idx, i + 1);\n\tconst p3 = hash(seed, idx, i + 2);\n\tconst v = 0.5 * (2 * p1 + (-p0 + p2) * f + (2 * p0 - 5 * p1 + 4 * p2 - p3) * f * f + (-p0 + 3 * p1 - 3 * p2 + p3) * f * f * f);\n\treturn Math.min(1, Math.max(-1, v));\n}\n\n/**\n * Wiggle Paths: subdivides the paths (`detail` points per segment) and moves every point by\n * smooth noise of up to `size` that evolves over `time` seconds at `speed` wiggles per second.\n * The same parameters always give the same result.\n */\nexport function wigglePaths(paths: readonly BezierPath[], w: VectorEffectParamsMap['wiggle']): BezierPath[] {\n\tif (!w.size || !Number.isFinite(w.size)) return paths.slice();\n\tconst m = Math.min(1000, Math.max(0, Math.round(Number.isFinite(w.detail) ? w.detail : 0))) + 1;\n\tconst seed = BigInt.asUintN(64, BigInt(Math.round(Number.isFinite(w.seed) ? w.seed : 0)));\n\tconst t = (Number.isFinite(w.time) ? w.time : 0) * (Number.isFinite(w.speed) ? w.speed : 0) + (Number.isFinite(w.phase) ? w.phase : 0) / 360;\n\tconst corr = Math.min(1, Math.max(0, (Number.isFinite(w.correlation) ? w.correlation : 0) / 100));\n\tconst sx = noise(seed, MASK64, t);\n\tconst sy = noise(seed, MASK64 - 1n, t);\n\tlet idx = 0;\n\treturn paths.map((p) => {\n\t\tconst out: Sub[] = [];\n\t\tfor (const sub of subsOf(p)) {\n\t\t\tconst s = resample(sub, m);\n\t\t\tconst disp = s.map(() => {\n\t\t\t\tconst i = BigInt(idx);\n\t\t\t\tconst ox = noise(seed, i * 2n, t + idx * 0.37);\n\t\t\t\tconst oy = noise(seed, i * 2n + 1n, t + idx * 0.61);\n\t\t\t\tidx++;\n\t\t\t\treturn [(sx * corr + ox * (1 - corr)) * w.size, (sy * corr + oy * (1 - corr)) * w.size] as Point;\n\t\t\t});\n\t\t\tconst e = emit(s, disp, sub.closed, w.smooth, 1 / 3);\n\t\t\tif (e) out.push(e);\n\t\t}\n\t\treturn subsToPath(out);\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Merge Paths\n// ---------------------------------------------------------------------------\n\nconst MERGE_OPS = { add: 'union', subtract: 'difference', intersect: 'intersection', exclude: 'xor' } as const;\n\n/** Merge Paths: the paths (in stacking order, each filled non-zero) combined into one path. */\nexport function mergePaths(paths: readonly BezierPath[], mode: VectorMergeMode = 'merge'): BezierPath {\n\tif (mode === 'merge' || !(mode in MERGE_OPS)) return paths.flat();\n\tconst inputs = paths.filter((p) => p.length > 0).map((path) => ({ path, fillRule: 'nonzero' as const }));\n\tif (!inputs.length) return [];\n\treturn pathBoolean(MERGE_OPS[mode as keyof typeof MERGE_OPS], inputs).path;\n}\n\n// ---------------------------------------------------------------------------\n// Repeater\n// ---------------------------------------------------------------------------\n\n/** One copy a repeater makes: its transform (node space) and opacity factor. */\nexport interface VectorRepeaterCopy {\n\t/** Copy number (0 is the original). */\n\tindex: number;\n\tmatrix: AffineMatrix;\n\topacity: number;\n}\n\n/**\n * The copies of a repeater around `pivot` (the anchor point in node space), in copy order.\n * Copy i is moved by `translate(position·k) · rotate(rotation·k) · scale^k` about the pivot with\n * `k = i + offset`; opacity runs from the start to the end opacity across the copies, and a\n * fractional copy count fades the last copy by its fraction.\n */\nexport function vectorRepeaterCopies(r: VectorEffectParamsMap['repeater'], pivot: Vec2): VectorRepeaterCopy[] {\n\tconst copies = Math.max(0, Number.isFinite(r.copies) ? Math.min(r.copies, 1000) : 0);\n\tconst n = Math.ceil(copies);\n\tconst offset = Number.isFinite(r.offset) ? r.offset : 0;\n\tconst so = (r.startOpacity ?? 100) / 100;\n\tconst eo = (r.endOpacity ?? 100) / 100;\n\tconst fract = copies - Math.floor(copies);\n\tconst out: VectorRepeaterCopy[] = [];\n\tfor (let i = 0; i < n; i++) {\n\t\tconst k = i + offset;\n\t\tlet m = translateMatrix(-pivot.x, -pivot.y);\n\t\tm = multiplyMatrices(m, scaleMatrix(Math.pow((r.scale?.x ?? 100) / 100, k), Math.pow((r.scale?.y ?? 100) / 100, k)));\n\t\tm = multiplyMatrices(m, rotateMatrix((r.rotation ?? 0) * k));\n\t\tm = multiplyMatrices(m, translateMatrix(pivot.x + (r.position?.x ?? 0) * k, pivot.y + (r.position?.y ?? 0) * k));\n\t\tconst t = n > 1 ? i / (n - 1) : 0;\n\t\tconst partial = i + 1 === n && fract > 0 ? fract : 1;\n\t\tout.push({ index: i, matrix: m, opacity: Math.min(1, Math.max(0, (so + (eo - so) * t) * partial)) });\n\t}\n\treturn out;\n}\n\n/** Each path repeated by `vectorRepeaterCopies` (copy order, the original first). */\nexport function repeatPaths(paths: readonly BezierPath[], r: VectorEffectParamsMap['repeater'], pivot: Vec2): { copy: VectorRepeaterCopy; paths: BezierPath[] }[] {\n\treturn vectorRepeaterCopies(r, pivot).map((copy) => ({ copy, paths: paths.map((p) => transformBezierPath(p, copy.matrix)) }));\n}\n\n/** The middle of the paths' bounds (the origin when they are empty). */\nexport function pathsCenter(paths: readonly BezierPath[]): Vec2 {\n\tconst b = bezierPathBounds(paths.flat());\n\treturn b ? { x: (b.minX + b.maxX) / 2, y: (b.minY + b.maxY) / 2 } : { x: 0, y: 0 };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BO,IAAM,sBAAmD,CAAC,SAAS,YAAY,SAAS;AA6CxF,IAAM,wBAAuD,CAAC,UAAU,UAAU,SAAS,aAAa,SAAS;AAIjH,IAAM,0BAA2D,CAAC,OAAO,WAAW,QAAQ;AAI5F,IAAM,iCAAyE,CAAC,QAAQ,UAAU,OAAO;AAczG,IAAM,+BAAoE,CAAC,UAAU,SAAS,QAAQ;AA2EtG,IAAM,oBAAgD,CAAC,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G,gBAAgB,MAAM,KAAK,EAAE,UAAU,KAAK,KAAK,GAAG,MAAM,KAAK,EAAE,UAAU,KAAK,KAAK,CAAC,CAAC;AAC/G,UAAM,IAAI,IAAI,IAAI,KAAK,IAAI,KAAK;AAChC,UAAM,UAAU,IAAI,MAAM,KAAK,QAAQ,IAAI,QAAQ;AACnD,QAAI,KAAK,EAAE,OAAO,GAAG,QAAQ,GAAG,SAAS,KAAK,IAAI,GAAG,KAAK,IAAI,IAAI,MAAM,KAAK,MAAM,KAAK,OAAO,CAAC,EAAE,CAAC;AAAA,EACpG;AACA,SAAO;AACR;AAGO,SAAS,YAAY,OAA8B,GAAsC,OAAkE;AACjK,SAAO,qBAAqB,GAAG,KAAK,EAAE,IAAI,CAAC,UAAU,EAAE,MAAM,OAAO,MAAM,IAAI,CAAC,MAAM,oBAAoB,GAAG,KAAK,MAAM,CAAC,EAAE,EAAE;AAC7H;AAGO,SAAS,YAAY,OAAoC;AAC/D,QAAM,IAAI,iBAAiB,MAAM,KAAK,CAAC;AACvC,SAAO,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,GAAG,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,GAAG,GAAG,GAAG,EAAE;AAClF;","names":["v","at","tangent","plain","s","start","along","mirrored","capped","clean","v","sub","add","mul","dot","t","v","v","same","p","round","sub","v","len","w","cross","dot","polygon","near","pt","scale","at","s","t","dist","place","near","v","next","same","num","plain","lerp","dist","toVec","out","scale","pt","face","fi","from","to","len","v","pt","invert","fe","v","at","tangent","q","pt","c","pt","v","add","EPS","cross","dot","b","pt","len","EPS","KAPPA","EPS","degenerate","unit","perp","v","sub","len","pt"]}
|