@pixerate/editor 0.125.0 → 0.127.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.
Files changed (124) hide show
  1. package/dist/animation/index.d.cts +2 -3
  2. package/dist/animation/index.d.ts +2 -3
  3. package/dist/animation-editor/index.cjs +71 -73
  4. package/dist/animation-editor/index.cjs.map +1 -1
  5. package/dist/animation-editor/index.d.cts +6 -8
  6. package/dist/animation-editor/index.d.ts +6 -8
  7. package/dist/animation-editor/index.js +11 -13
  8. package/dist/animation-editor/index.js.map +1 -1
  9. package/dist/{bezier-CBzKKDjl.d.cts → bezier-DBz0IgEt.d.cts} +22 -2
  10. package/dist/{bezier-CWv6LQal.d.ts → bezier-DWI5MEkI.d.ts} +22 -2
  11. package/dist/{brushstrokeRender-LRV7GXGD.js → brushstrokeRender-7RUITO42.js} +3 -3
  12. package/dist/{brushstrokeRender-EELTV7U4.cjs → brushstrokeRender-OW6ENCZG.cjs} +7 -7
  13. package/dist/{brushstrokeRender-EELTV7U4.cjs.map → brushstrokeRender-OW6ENCZG.cjs.map} +1 -1
  14. package/dist/canvas/index.cjs +423 -37
  15. package/dist/canvas/index.cjs.map +1 -1
  16. package/dist/canvas/index.d.cts +189 -11
  17. package/dist/canvas/index.d.ts +189 -11
  18. package/dist/canvas/index.js +395 -9
  19. package/dist/canvas/index.js.map +1 -1
  20. package/dist/{chunk-7LQO6OHH.cjs → chunk-33SO3QWP.cjs} +4 -4
  21. package/dist/{chunk-7LQO6OHH.cjs.map → chunk-33SO3QWP.cjs.map} +1 -1
  22. package/dist/{chunk-MPQAO33O.js → chunk-A6KHMKI4.js} +3 -3
  23. package/dist/{chunk-V5YGPRCZ.cjs → chunk-BEGEWQHD.cjs} +41 -41
  24. package/dist/{chunk-V5YGPRCZ.cjs.map → chunk-BEGEWQHD.cjs.map} +1 -1
  25. package/dist/{chunk-N3FVUOZD.cjs → chunk-BJTCSLF6.cjs} +7 -7
  26. package/dist/{chunk-N3FVUOZD.cjs.map → chunk-BJTCSLF6.cjs.map} +1 -1
  27. package/dist/{chunk-WUDPFWAN.js → chunk-F7Q2NE2Y.js} +3 -3
  28. package/dist/{chunk-G6WXWS4Y.js → chunk-FICSDDDF.js} +2 -2
  29. package/dist/{chunk-GUZ47CJM.cjs → chunk-IZ4WRXZA.cjs} +1 -1
  30. package/dist/{chunk-GUZ47CJM.cjs.map → chunk-IZ4WRXZA.cjs.map} +1 -1
  31. package/dist/{chunk-QDJKUBWE.cjs → chunk-JODTP4DP.cjs} +176 -5
  32. package/dist/chunk-JODTP4DP.cjs.map +1 -0
  33. package/dist/{chunk-GLWZXQ4Q.js → chunk-KHNZ6MOU.js} +1 -1
  34. package/dist/chunk-KHNZ6MOU.js.map +1 -0
  35. package/dist/{chunk-GCJWMEYW.cjs → chunk-KSJLDRHK.cjs} +46 -46
  36. package/dist/{chunk-GCJWMEYW.cjs.map → chunk-KSJLDRHK.cjs.map} +1 -1
  37. package/dist/{chunk-QQKTOA4U.cjs → chunk-ORE334I6.cjs} +132 -132
  38. package/dist/{chunk-QQKTOA4U.cjs.map → chunk-ORE334I6.cjs.map} +1 -1
  39. package/dist/{chunk-X6KTSFAE.js → chunk-Q4NBEVV5.js} +2 -2
  40. package/dist/{chunk-XZWOLXWA.js → chunk-QFSTQHZY.js} +174 -3
  41. package/dist/chunk-QFSTQHZY.js.map +1 -0
  42. package/dist/{chunk-FPRIUR4T.js → chunk-ROZFX4QI.js} +3 -3
  43. package/dist/{chunk-UXFI3CDZ.cjs → chunk-SFCPGMCT.cjs} +8 -8
  44. package/dist/{chunk-UXFI3CDZ.cjs.map → chunk-SFCPGMCT.cjs.map} +1 -1
  45. package/dist/{chunk-J67OLQUQ.js → chunk-UABQTYQF.js} +3 -3
  46. package/dist/{chunk-O5RVCDEC.cjs → chunk-XLUYXUBD.cjs} +88 -88
  47. package/dist/{chunk-O5RVCDEC.cjs.map → chunk-XLUYXUBD.cjs.map} +1 -1
  48. package/dist/{chunk-FG274FYT.js → chunk-YGJIER2R.js} +2 -2
  49. package/dist/effects/index.cjs +32 -34
  50. package/dist/effects/index.cjs.map +1 -1
  51. package/dist/effects/index.d.cts +6 -38
  52. package/dist/effects/index.d.ts +6 -38
  53. package/dist/effects/index.js +3 -5
  54. package/dist/effects/index.js.map +1 -1
  55. package/dist/evaluate-BbCeF6pt.d.ts +114 -0
  56. package/dist/evaluate-BsxYieLN.d.cts +114 -0
  57. package/dist/{export-DVl4fWy5.d.cts → export-Cbr9IqpJ.d.cts} +1 -1
  58. package/dist/{export-Bp7ji2r4.d.cts → export-CcldobdN.d.cts} +3 -3
  59. package/dist/{export-C1s4eolZ.d.ts → export-ClPKUB-v.d.ts} +1 -1
  60. package/dist/{export-DAyPY94f.d.ts → export-PGhOpDmz.d.ts} +3 -3
  61. package/dist/{helpers-i95Ob6Vi.d.cts → helpers-C5aAd44p.d.cts} +67 -4
  62. package/dist/{helpers-BBLlekuM.d.ts → helpers-CPWcK504.d.ts} +67 -4
  63. package/dist/image-editor/index.cjs +619 -621
  64. package/dist/image-editor/index.cjs.map +1 -1
  65. package/dist/image-editor/index.d.cts +9 -11
  66. package/dist/image-editor/index.d.ts +9 -11
  67. package/dist/image-editor/index.js +6 -8
  68. package/dist/image-editor/index.js.map +1 -1
  69. package/dist/{opentype-14PDI5D2.d.ts → opentype-01rMIuQR.d.ts} +1 -1
  70. package/dist/{opentype-D80AVmMu.d.cts → opentype-BgqvmGT-.d.cts} +1 -1
  71. package/dist/paint-editor/index.cjs +737 -117
  72. package/dist/paint-editor/index.cjs.map +1 -1
  73. package/dist/paint-editor/index.d.cts +248 -13
  74. package/dist/paint-editor/index.d.ts +248 -13
  75. package/dist/paint-editor/index.js +635 -15
  76. package/dist/paint-editor/index.js.map +1 -1
  77. package/dist/{pathfinder-DjISxkUv.d.ts → pathfinder-D-h0Imus.d.ts} +1 -1
  78. package/dist/{pathfinder-C0UoFypx.d.cts → pathfinder-DgG0Z9Lr.d.cts} +1 -1
  79. package/dist/{player-cGLrngL_.d.ts → player-BK2kKbfd.d.ts} +1 -1
  80. package/dist/{player-CBtEoU2x.d.cts → player-CmbY3218.d.cts} +1 -1
  81. package/dist/pool-C7GtrL34.d.cts +34 -0
  82. package/dist/pool-CTrtciaN.d.ts +34 -0
  83. package/dist/{svg-DJKriJ4A.d.ts → svg-BRLwcibA.d.ts} +2 -3
  84. package/dist/{svg-BkRL-fZJ.d.cts → svg-DLBBPQP9.d.cts} +2 -3
  85. package/dist/{tools-CM8Oe8F3.d.ts → tools-AugT22z3.d.ts} +1 -1
  86. package/dist/{tools-DZCv2kX1.d.cts → tools-BpCmUNxb.d.cts} +1 -1
  87. package/dist/vector/index.cjs +923 -925
  88. package/dist/vector/index.cjs.map +1 -1
  89. package/dist/vector/index.d.cts +10 -12
  90. package/dist/vector/index.d.ts +10 -12
  91. package/dist/vector/index.js +11 -13
  92. package/dist/vector/index.js.map +1 -1
  93. package/dist/video-editor/index.cjs +269 -271
  94. package/dist/video-editor/index.cjs.map +1 -1
  95. package/dist/video-editor/index.d.cts +6 -8
  96. package/dist/video-editor/index.d.ts +6 -8
  97. package/dist/video-editor/index.js +3 -5
  98. package/dist/video-editor/index.js.map +1 -1
  99. package/dist/{warp-CH9MM435.d.cts → warp-C13L_GRn.d.cts} +1 -1
  100. package/dist/{warp-k_PdtXOG.d.ts → warp-q8FK5HHi.d.ts} +1 -1
  101. package/package.json +1 -1
  102. package/skills/pixerate-canvas/SKILL.md +19 -0
  103. package/skills/pixerate-paint-editor/SKILL.md +40 -1
  104. package/dist/behavior-Ymbld6jL.d.cts +0 -60
  105. package/dist/behavior-Ymbld6jL.d.ts +0 -60
  106. package/dist/chunk-GLWZXQ4Q.js.map +0 -1
  107. package/dist/chunk-IOXKXQNW.cjs +0 -178
  108. package/dist/chunk-IOXKXQNW.cjs.map +0 -1
  109. package/dist/chunk-QDJKUBWE.cjs.map +0 -1
  110. package/dist/chunk-TGKT5QAB.js +0 -178
  111. package/dist/chunk-TGKT5QAB.js.map +0 -1
  112. package/dist/chunk-XZWOLXWA.js.map +0 -1
  113. package/dist/evaluate-2S3vSPLy.d.cts +0 -55
  114. package/dist/evaluate-CfmT6xA3.d.ts +0 -55
  115. package/dist/gradient-KDfCvhuj.d.cts +0 -66
  116. package/dist/gradient-KDfCvhuj.d.ts +0 -66
  117. /package/dist/{brushstrokeRender-LRV7GXGD.js.map → brushstrokeRender-7RUITO42.js.map} +0 -0
  118. /package/dist/{chunk-MPQAO33O.js.map → chunk-A6KHMKI4.js.map} +0 -0
  119. /package/dist/{chunk-WUDPFWAN.js.map → chunk-F7Q2NE2Y.js.map} +0 -0
  120. /package/dist/{chunk-G6WXWS4Y.js.map → chunk-FICSDDDF.js.map} +0 -0
  121. /package/dist/{chunk-X6KTSFAE.js.map → chunk-Q4NBEVV5.js.map} +0 -0
  122. /package/dist/{chunk-FPRIUR4T.js.map → chunk-ROZFX4QI.js.map} +0 -0
  123. /package/dist/{chunk-J67OLQUQ.js.map → chunk-UABQTYQF.js.map} +0 -0
  124. /package/dist/{chunk-FG274FYT.js.map → chunk-YGJIER2R.js.map} +0 -0
@@ -1,6 +1,159 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;
2
2
 
3
- var _chunkIOXKXQNWcjs = require('./chunk-IOXKXQNW.cjs');
3
+ var _chunkRIWPYSKUcjs = require('./chunk-RIWPYSKU.cjs');
4
+
5
+ // src/effects/errors.ts
6
+ var EFFECT_ERROR_CODES = ["unknown_effect", "invalid_values", "unsupported", "disposed", "no_provider"];
7
+ var EffectError = class extends Error {
8
+
9
+
10
+ constructor(code, message, effectId) {
11
+ super(message);
12
+ this.name = "EffectError";
13
+ this.code = code;
14
+ this.effectId = effectId;
15
+ }
16
+ };
17
+ var UnknownEffectError = class extends EffectError {
18
+ constructor(effectId, providerName) {
19
+ super(
20
+ "unknown_effect",
21
+ `Unknown effect "${effectId}"${providerName ? ` in ${providerName}` : ""}. Call search_effects or list() for valid ids.`,
22
+ effectId
23
+ );
24
+ this.name = "UnknownEffectError";
25
+ }
26
+ };
27
+ var EffectControlError = class extends EffectError {
28
+
29
+ constructor(effectId, details) {
30
+ const lines = details.map((d) => `- ${d.path || "/"}: ${d.message}`).join("\n");
31
+ super("invalid_values", `Invalid values for effect "${effectId}":
32
+ ${lines}`, effectId);
33
+ this.name = "EffectControlError";
34
+ this.details = details;
35
+ }
36
+ };
37
+ var EffectUnsupportedError = class extends EffectError {
38
+ constructor(message, effectId) {
39
+ super("unsupported", message, effectId);
40
+ this.name = "EffectUnsupportedError";
41
+ }
42
+ };
43
+ var EffectDisposedError = class extends EffectError {
44
+ constructor(effectId) {
45
+ super("disposed", `The renderer for "${effectId}" was disposed. Create a new renderer.`, effectId);
46
+ this.name = "EffectDisposedError";
47
+ }
48
+ };
49
+ var NoEffectsProviderError = class extends EffectError {
50
+ constructor() {
51
+ super("no_provider", "No effects provider is registered with this editor. The host must call setEffectsProvider(provider) first.");
52
+ this.name = "NoEffectsProviderError";
53
+ }
54
+ };
55
+ function isEffectError(error) {
56
+ if (error instanceof EffectError) return true;
57
+ const code = error instanceof Error ? error.code : void 0;
58
+ return typeof code === "string" && EFFECT_ERROR_CODES.includes(code);
59
+ }
60
+
61
+ // src/effects/helpers.ts
62
+ function effectValueErrors(description, values) {
63
+ if (values === void 0) return [];
64
+ return _chunkRIWPYSKUcjs.validateJsonSchema.call(void 0, values, { ...description.controls, required: [] });
65
+ }
66
+ function resolveEffectValues(description, values) {
67
+ const errors = effectValueErrors(description, values);
68
+ if (errors.length) throw new EffectControlError(description.id, errors);
69
+ return { ...description.defaults, ..._nullishCoalesce(values, () => ( {})) };
70
+ }
71
+ var matchesFilters = (e, o) => (!o.kind || e.kind === o.kind) && (!o.category || e.category === o.category) && (!o.use || e.uses.includes(o.use));
72
+ function searchEffectSummaries(catalog, query = "", options = {}) {
73
+ const words = query.toLowerCase().split(/\s+/).filter(Boolean);
74
+ const scored = [];
75
+ catalog.forEach((e, i) => {
76
+ if (!matchesFilters(e, options)) return;
77
+ const name = e.name.toLowerCase();
78
+ const hay = [e.id, e.name, e.category, ..._nullishCoalesce(e.tags, () => ( [])), _nullishCoalesce(e.description, () => ( ""))].join(" ").toLowerCase();
79
+ let score = 0;
80
+ for (const w of words) {
81
+ if (!hay.includes(w)) return;
82
+ score += name.startsWith(w) ? 3 : name.includes(w) ? 2 : 1;
83
+ }
84
+ scored.push({ e, score, i });
85
+ });
86
+ scored.sort((a, b) => b.score - a.score || a.i - b.i);
87
+ const out = scored.map((s) => s.e);
88
+ return options.limit !== void 0 ? out.slice(0, Math.max(0, options.limit)) : out;
89
+ }
90
+ function createEffectPixels(width, height, float = false) {
91
+ const n = Math.max(0, width * height * 4);
92
+ return { width, height, data: new Uint8ClampedArray(n), ...float ? { float: new Float32Array(n) } : {} };
93
+ }
94
+ function isEffectPixels(source) {
95
+ return !!source && typeof source === "object" && source.data instanceof Uint8ClampedArray && typeof source.width === "number" && typeof source.height === "number";
96
+ }
97
+ var srgbToLinear = (v) => v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
98
+ var linearToSrgb = (v) => v > 0 ? v <= 31308e-7 ? v * 12.92 : 1.055 * Math.pow(v, 1 / 2.4) - 0.055 : 0;
99
+ function encodeEffectFloat(pixels) {
100
+ const f = pixels.float;
101
+ if (!f) return pixels;
102
+ const d = pixels.data;
103
+ for (let i = 0; i < d.length; i += 4) {
104
+ d[i] = Math.round(linearToSrgb(f[i]) * 255);
105
+ d[i + 1] = Math.round(linearToSrgb(f[i + 1]) * 255);
106
+ d[i + 2] = Math.round(linearToSrgb(f[i + 2]) * 255);
107
+ d[i + 3] = Math.round(Math.min(1, Math.max(0, f[i + 3])) * 255);
108
+ }
109
+ return pixels;
110
+ }
111
+ function applyEffectMask(result, mask, source) {
112
+ const { data } = result;
113
+ const m = mask.data;
114
+ for (let i = 0; i < data.length; i += 4) {
115
+ const k = m[i + 3] / 255;
116
+ if (k >= 1) continue;
117
+ if (source) {
118
+ for (let c = 0; c < 4; c++) data[i + c] = source.data[i + c] + (data[i + c] - source.data[i + c]) * k;
119
+ if (result.float && source.float) {
120
+ for (let c = 0; c < 4; c++) result.float[i + c] = source.float[i + c] + (result.float[i + c] - source.float[i + c]) * k;
121
+ }
122
+ } else {
123
+ data[i + 3] = data[i + 3] * k;
124
+ if (result.float) result.float[i + 3] *= k;
125
+ }
126
+ }
127
+ return result;
128
+ }
129
+ var EffectsSlot = (_class = class {constructor() { _class.prototype.__init.call(this);_class.prototype.__init2.call(this); }
130
+ __init() {this.current = null}
131
+ __init2() {this.listeners = /* @__PURE__ */ new Set()}
132
+ get provider() {
133
+ return this.current;
134
+ }
135
+ set(provider) {
136
+ if (provider === this.current) return;
137
+ this.current = provider;
138
+ for (const l of [...this.listeners]) l(provider);
139
+ }
140
+ /** Sets `provider` and returns a function that clears it again (if it is still the one set). */
141
+ use(provider) {
142
+ this.set(provider);
143
+ return () => {
144
+ if (this.current === provider) this.set(null);
145
+ };
146
+ }
147
+ /** The provider, or a `NoEffectsProviderError`. */
148
+ require() {
149
+ if (!this.current) throw new NoEffectsProviderError();
150
+ return this.current;
151
+ }
152
+ subscribe(listener) {
153
+ this.listeners.add(listener);
154
+ return () => this.listeners.delete(listener);
155
+ }
156
+ }, _class);
4
157
 
5
158
  // src/effects/types.ts
6
159
  var EFFECT_KINDS = ["shader", "vector", "motion"];
@@ -65,7 +218,7 @@ function createEffectToolProvider(host) {
65
218
  try {
66
219
  return await run();
67
220
  } catch (error) {
68
- if (_chunkIOXKXQNWcjs.isEffectError.call(void 0, error)) throw new Error(error.message);
221
+ if (isEffectError(error)) throw new Error(error.message);
69
222
  throw error;
70
223
  }
71
224
  };
@@ -211,5 +364,23 @@ function createEffectToolProvider(host) {
211
364
 
212
365
 
213
366
 
214
- exports.EFFECT_KINDS = EFFECT_KINDS; exports.EFFECT_USES = EFFECT_USES; exports.createEffectToolProvider = createEffectToolProvider;
215
- //# sourceMappingURL=chunk-QDJKUBWE.cjs.map
367
+
368
+
369
+
370
+
371
+
372
+
373
+
374
+
375
+
376
+
377
+
378
+
379
+
380
+
381
+
382
+
383
+
384
+
385
+ exports.EFFECT_ERROR_CODES = EFFECT_ERROR_CODES; exports.EffectError = EffectError; exports.UnknownEffectError = UnknownEffectError; exports.EffectControlError = EffectControlError; exports.EffectUnsupportedError = EffectUnsupportedError; exports.EffectDisposedError = EffectDisposedError; exports.NoEffectsProviderError = NoEffectsProviderError; exports.isEffectError = isEffectError; exports.effectValueErrors = effectValueErrors; exports.resolveEffectValues = resolveEffectValues; exports.searchEffectSummaries = searchEffectSummaries; exports.createEffectPixels = createEffectPixels; exports.isEffectPixels = isEffectPixels; exports.srgbToLinear = srgbToLinear; exports.linearToSrgb = linearToSrgb; exports.encodeEffectFloat = encodeEffectFloat; exports.applyEffectMask = applyEffectMask; exports.EffectsSlot = EffectsSlot; exports.EFFECT_KINDS = EFFECT_KINDS; exports.EFFECT_USES = EFFECT_USES; exports.createEffectToolProvider = createEffectToolProvider;
386
+ //# sourceMappingURL=chunk-JODTP4DP.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/editor/editor/packages/core/dist/chunk-JODTP4DP.cjs","../src/effects/errors.ts","../src/effects/helpers.ts","../src/effects/types.ts","../src/effects/tools.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACA;ACAO,IAAM,mBAAA,EAAiD,CAAC,gBAAA,EAAkB,gBAAA,EAAkB,aAAA,EAAe,UAAA,EAAY,aAAa,CAAA;AAMpI,IAAM,YAAA,EAAN,MAAA,QAA0B,MAAM;AAAA,EAC7B;AAAA,EACA;AAAA,EAET,WAAA,CAAY,IAAA,EAAuB,OAAA,EAAiB,QAAA,EAAmB;AACtE,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,KAAA,EAAO,aAAA;AACZ,IAAA,IAAA,CAAK,KAAA,EAAO,IAAA;AACZ,IAAA,IAAA,CAAK,SAAA,EAAW,QAAA;AAAA,EACjB;AACD,CAAA;AAGO,IAAM,mBAAA,EAAN,MAAA,QAAiC,YAAY;AAAA,EACnD,WAAA,CAAY,QAAA,EAAkB,YAAA,EAAuB;AACpD,IAAA,KAAA;AAAA,MACC,gBAAA;AAAA,MACA,CAAA,gBAAA,EAAmB,QAAQ,CAAA,CAAA,EAAI,aAAA,EAAe,CAAA,IAAA,EAAO,YAAY,CAAA,EAAA;AACjE,MAAA;AACD,IAAA;AACY,IAAA;AACb,EAAA;AACD;AAGoD;AAC1C,EAAA;AAEgE,EAAA;AACL,IAAA;AACL,IAAA;AAAwB;AAC1E,IAAA;AACG,IAAA;AAChB,EAAA;AACD;AAGwD;AACP,EAAA;AACT,IAAA;AAC1B,IAAA;AACb,EAAA;AACD;AAGqD;AACtB,EAAA;AACkB,IAAA;AACnC,IAAA;AACb,EAAA;AACD;AAGwD;AACzC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C,MAAA;AAC0D,MAAA;AACD,MAAA;AACE,MAAA;AACzC,MAAA;AACA,QAAA;AACqC,QAAA;AACoB,QAAA;AACnB,QAAA;AAC/D,MAAA;AACD,IAAA;AACD,EAAA;AAEsC,EAAA;AACrC,IAAA;AACO,MAAA;AACC,MAAA;AAC0D,MAAA;AACpD,MAAA;AACZ,QAAA;AACS,UAAA;AAC6B,UAAA;AAChB,UAAA;AACd,UAAA;AACE,UAAA;AACA,UAAA;AACV,QAAA;AACmB,QAAA;AACpB,MAAA;AAC8D,MAAA;AACrC,MAAA;AACf,QAAA;AACuE,QAAA;AACjF,MAAA;AACD,IAAA;AACA,IAAA;AACO,MAAA;AACC,MAAA;AACyD,MAAA;AACnD,MAAA;AACZ,QAAA;AACS,UAAA;AACA,UAAA;AACqD,UAAA;AACpD,UAAA;AACA,UAAA;AACuB,UAAA;AACjC,QAAA;AACmB,QAAA;AACpB,MAAA;AACiE,MAAA;AACxC,MAAA;AACf,QAAA;AAC2D,QAAA;AACa,QAAA;AAClF,MAAA;AACD,IAAA;AACA,IAAA;AACO,MAAA;AACC,MAAA;AAC2D,MAAA;AACP,MAAA;AACM,MAAA;AACxC,MAAA;AACf,QAAA;AACqE,QAAA;AAC/E,MAAA;AACD,IAAA;AACD,EAAA;AAEO,EAAA;AACG,IAAA;AAC6C,IAAA;AACzC,IAAA;AACiC,MAAA;AACe,MAAA;AACX,MAAA;AAClD,IAAA;AACkB,IAAA;AACF,MAAA;AACe,MAAA;AACjB,MAAA;AACM,QAAA;AACZ,wBAAA;AACP,MAAA;AACD,IAAA;AACD,EAAA;AACD;AJgDwE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/editor/editor/packages/core/dist/chunk-JODTP4DP.cjs","sourcesContent":[null,"import type { SchemaValidationError } from '../tools/schema.js';\n\nexport type EffectErrorCode = 'unknown_effect' | 'invalid_values' | 'unsupported' | 'disposed' | 'no_provider';\n\nexport const EFFECT_ERROR_CODES: readonly EffectErrorCode[] = ['unknown_effect', 'invalid_values', 'unsupported', 'disposed', 'no_provider'];\n\n/**\n * Base of every effects error. Check `code` (or use `isEffectError`) rather than `instanceof`\n * across packages, since a provider may be bundled with its own copy of this class.\n */\nexport class EffectError extends Error {\n\treadonly code: EffectErrorCode;\n\treadonly effectId?: string;\n\n\tconstructor(code: EffectErrorCode, message: string, effectId?: string) {\n\t\tsuper(message);\n\t\tthis.name = 'EffectError';\n\t\tthis.code = code;\n\t\tthis.effectId = effectId;\n\t}\n}\n\n/** No effect has this id. */\nexport class UnknownEffectError extends EffectError {\n\tconstructor(effectId: string, providerName?: string) {\n\t\tsuper(\n\t\t\t'unknown_effect',\n\t\t\t`Unknown effect \"${effectId}\"${providerName ? ` in ${providerName}` : ''}. Call search_effects or list() for valid ids.`,\n\t\t\teffectId\n\t\t);\n\t\tthis.name = 'UnknownEffectError';\n\t}\n}\n\n/** Control values do not match the effect's control schema (unknown control, wrong type, out of range). */\nexport class EffectControlError extends EffectError {\n\treadonly details: readonly SchemaValidationError[];\n\n\tconstructor(effectId: string, details: readonly SchemaValidationError[]) {\n\t\tconst lines = details.map((d) => `- ${d.path || '/'}: ${d.message}`).join('\\n');\n\t\tsuper('invalid_values', `Invalid values for effect \"${effectId}\":\\n${lines}`, effectId);\n\t\tthis.name = 'EffectControlError';\n\t\tthis.details = details;\n\t}\n}\n\n/** The provider cannot do this (a vector effect asked for pixels, a size above `maxSize`, a missing input...). */\nexport class EffectUnsupportedError extends EffectError {\n\tconstructor(message: string, effectId?: string) {\n\t\tsuper('unsupported', message, effectId);\n\t\tthis.name = 'EffectUnsupportedError';\n\t}\n}\n\n/** The renderer was disposed. Create a new one. */\nexport class EffectDisposedError extends EffectError {\n\tconstructor(effectId: string) {\n\t\tsuper('disposed', `The renderer for \"${effectId}\" was disposed. Create a new renderer.`, effectId);\n\t\tthis.name = 'EffectDisposedError';\n\t}\n}\n\n/** No effects provider is registered with this editor. */\nexport class NoEffectsProviderError extends EffectError {\n\tconstructor() {\n\t\tsuper('no_provider', 'No effects provider is registered with this editor. The host must call setEffectsProvider(provider) first.');\n\t\tthis.name = 'NoEffectsProviderError';\n\t}\n}\n\n/** True for any effects error, including one thrown by another copy of this module. */\nexport function isEffectError(error: unknown): error is EffectError {\n\tif (error instanceof EffectError) return true;\n\tconst code = error instanceof Error ? (error as unknown as { code?: unknown }).code : undefined;\n\treturn typeof code === 'string' && EFFECT_ERROR_CODES.includes(code as EffectErrorCode);\n}\n","/**\n * Helpers for providers and editors: value validation, catalog search, pixel buffers, masking,\n * and a provider slot editors hold.\n */\n\nimport { validateJsonSchema, type SchemaValidationError } from '../tools/schema.js';\nimport { EffectControlError, NoEffectsProviderError } from './errors.js';\nimport type {\n\tEffectDescription,\n\tEffectImageSource,\n\tEffectPixels,\n\tEffectProvider,\n\tEffectSearchOptions,\n\tEffectSummary,\n\tEffectValues\n} from './types.js';\n\n// ---------------------------------------------------------------------------\n// Values\n// ---------------------------------------------------------------------------\n\n/** Problems with `values` against an effect's control schema (unknown controls, types, ranges). Partial values are fine. */\nexport function effectValueErrors(description: Pick<EffectDescription, 'controls'>, values: unknown): SchemaValidationError[] {\n\tif (values === undefined) return [];\n\treturn validateJsonSchema(values, { ...description.controls, required: [] });\n}\n\n/**\n * `values` over the effect's defaults, validated against its control schema. Throws\n * `EffectControlError` naming every bad control. Providers call this in `render`; editors call\n * it before saving values.\n */\nexport function resolveEffectValues(description: Pick<EffectDescription, 'id' | 'controls' | 'defaults'>, values?: EffectValues): Record<string, EffectValues[string]> {\n\tconst errors = effectValueErrors(description, values);\n\tif (errors.length) throw new EffectControlError(description.id, errors);\n\treturn { ...description.defaults, ...(values ?? {}) };\n}\n\n// ---------------------------------------------------------------------------\n// Search\n// ---------------------------------------------------------------------------\n\nconst matchesFilters = (e: EffectSummary, o: EffectSearchOptions) =>\n\t(!o.kind || e.kind === o.kind) && (!o.category || e.category === o.category) && (!o.use || e.uses.includes(o.use));\n\n/**\n * Filters a catalog and ranks it against `query` (every word must appear in the id, name,\n * category, tags or description; name matches rank first). An empty query keeps catalog order.\n * Providers can implement `list` and `search` with it.\n */\nexport function searchEffectSummaries<T extends EffectSummary>(catalog: readonly T[], query = '', options: EffectSearchOptions = {}): T[] {\n\tconst words = query.toLowerCase().split(/\\s+/).filter(Boolean);\n\tconst scored: { e: T; score: number; i: number }[] = [];\n\tcatalog.forEach((e, i) => {\n\t\tif (!matchesFilters(e, options)) return;\n\t\tconst name = e.name.toLowerCase();\n\t\tconst hay = [e.id, e.name, e.category, ...(e.tags ?? []), e.description ?? ''].join(' ').toLowerCase();\n\t\tlet score = 0;\n\t\tfor (const w of words) {\n\t\t\tif (!hay.includes(w)) return;\n\t\t\tscore += name.startsWith(w) ? 3 : name.includes(w) ? 2 : 1;\n\t\t}\n\t\tscored.push({ e, score, i });\n\t});\n\tscored.sort((a, b) => b.score - a.score || a.i - b.i);\n\tconst out = scored.map((s) => s.e);\n\treturn options.limit !== undefined ? out.slice(0, Math.max(0, options.limit)) : out;\n}\n\n// ---------------------------------------------------------------------------\n// Pixels\n// ---------------------------------------------------------------------------\n\n/** A transparent picture, with float samples when `float` is set. */\nexport function createEffectPixels(width: number, height: number, float = false): EffectPixels {\n\tconst n = Math.max(0, width * height * 4);\n\treturn { width, height, data: new Uint8ClampedArray(n), ...(float ? { float: new Float32Array(n) } : {}) };\n}\n\n/** True for an `EffectPixels` (rather than a host image object). */\nexport function isEffectPixels(source: EffectImageSource | unknown): source is EffectPixels {\n\treturn (\n\t\t!!source &&\n\t\ttypeof source === 'object' &&\n\t\t(source as EffectPixels).data instanceof Uint8ClampedArray &&\n\t\ttypeof (source as EffectPixels).width === 'number' &&\n\t\ttypeof (source as EffectPixels).height === 'number'\n\t);\n}\n\n/** sRGB-encoded 0–1 to linear light. */\nexport const srgbToLinear = (v: number) => (v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4));\n/** Linear light to sRGB-encoded (clamped below at 0; may exceed 1). */\nexport const linearToSrgb = (v: number) => (v > 0 ? (v <= 0.0031308 ? v * 12.92 : 1.055 * Math.pow(v, 1 / 2.4) - 0.055) : 0);\n\n/** Fills `pixels.data` from `pixels.float` (linear float to clamped 8-bit sRGB). */\nexport function encodeEffectFloat(pixels: EffectPixels): EffectPixels {\n\tconst f = pixels.float;\n\tif (!f) return pixels;\n\tconst d = pixels.data;\n\tfor (let i = 0; i < d.length; i += 4) {\n\t\td[i] = Math.round(linearToSrgb(f[i]) * 255);\n\t\td[i + 1] = Math.round(linearToSrgb(f[i + 1]) * 255);\n\t\td[i + 2] = Math.round(linearToSrgb(f[i + 2]) * 255);\n\t\td[i + 3] = Math.round(Math.min(1, Math.max(0, f[i + 3])) * 255);\n\t}\n\treturn pixels;\n}\n\n/**\n * Blends an effect `result` back over its `source` by `mask` coverage (alpha channel), in place\n * on `result`: where the mask is 0 the source shows, where it is 255 the result. Without a\n * source (generators), the result's alpha is multiplied by coverage. Editors use it when the\n * provider does not `supportsMask`. All three must have the same size.\n */\nexport function applyEffectMask(result: EffectPixels, mask: EffectPixels, source?: EffectPixels): EffectPixels {\n\tconst { data } = result;\n\tconst m = mask.data;\n\tfor (let i = 0; i < data.length; i += 4) {\n\t\tconst k = m[i + 3] / 255;\n\t\tif (k >= 1) continue;\n\t\tif (source) {\n\t\t\tfor (let c = 0; c < 4; c++) data[i + c] = source.data[i + c] + (data[i + c] - source.data[i + c]) * k;\n\t\t\tif (result.float && source.float) {\n\t\t\t\tfor (let c = 0; c < 4; c++) result.float[i + c] = source.float[i + c] + (result.float[i + c] - source.float[i + c]) * k;\n\t\t\t}\n\t\t} else {\n\t\t\tdata[i + 3] = data[i + 3] * k;\n\t\t\tif (result.float) result.float[i + 3] *= k;\n\t\t}\n\t}\n\treturn result;\n}\n\n// ---------------------------------------------------------------------------\n// The slot an editor keeps\n// ---------------------------------------------------------------------------\n\n/**\n * Holds an editor's effects provider. Controllers expose it as `effectsProvider`,\n * `setEffectsProvider(provider | null)` and `useEffects(provider)`; listeners hear every change.\n */\nexport class EffectsSlot {\n\tprivate current: EffectProvider | null = null;\n\tprivate readonly listeners = new Set<(provider: EffectProvider | null) => void>();\n\n\tget provider(): EffectProvider | null {\n\t\treturn this.current;\n\t}\n\n\tset(provider: EffectProvider | null): void {\n\t\tif (provider === this.current) return;\n\t\tthis.current = provider;\n\t\tfor (const l of [...this.listeners]) l(provider);\n\t}\n\n\t/** Sets `provider` and returns a function that clears it again (if it is still the one set). */\n\tuse(provider: EffectProvider): () => void {\n\t\tthis.set(provider);\n\t\treturn () => {\n\t\t\tif (this.current === provider) this.set(null);\n\t\t};\n\t}\n\n\t/** The provider, or a `NoEffectsProviderError`. */\n\trequire(): EffectProvider {\n\t\tif (!this.current) throw new NoEffectsProviderError();\n\t\treturn this.current;\n\t}\n\n\tsubscribe(listener: (provider: EffectProvider | null) => void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n}\n","/**\n * The effects contract: how an editor finds, describes and renders effects that live in another\n * package. This library ships no effects of its own here, only the shapes a provider fills in;\n * a host passes a provider to an editor (`setEffectsProvider`) and the editor degrades to its\n * old behaviour without one.\n *\n * Every time is in milliseconds. Pixels are straight-alpha RGBA rows, top to bottom.\n */\n\nimport type { JsonSchema } from '../tools/schema.js';\nimport type { FlairSvgAnimation } from '../animation-editor/flair.js';\n\n/** How an effect is drawn: a pixel shader, an animated vector picture, or motion applied to someone else's vector art. */\nexport type EffectKind = 'shader' | 'vector' | 'motion';\n\n/**\n * What an effect is for. An effect may have several uses.\n *\n * - `filter`: changes an input picture (`inputs.source`).\n * - `transition`: blends `inputs.from` into `inputs.to`; `progress` runs 0 → 1.\n * - `generator`: draws a picture from nothing (a background, a texture).\n * - `overlay`: draws something meant to sit over other content, usually with transparency.\n * - `title`: draws type or a graphic meant as a title.\n * - `motion`: animates vector art (`applyVectorEffect`).\n * - `interactive`: reacts to pointer, scroll or audio input at run time.\n */\nexport type EffectUse = 'filter' | 'transition' | 'generator' | 'overlay' | 'title' | 'motion' | 'interactive';\n\nexport const EFFECT_KINDS: readonly EffectKind[] = ['shader', 'vector', 'motion'];\nexport const EFFECT_USES: readonly EffectUse[] = ['filter', 'transition', 'generator', 'overlay', 'title', 'motion', 'interactive'];\n\n/** One entry of a provider's catalog. */\nexport interface EffectSummary {\n\t/** Stable id, saved in documents. Never reused for a different effect. */\n\tid: string;\n\tname: string;\n\tkind: EffectKind;\n\t/** The provider's own grouping (e.g. `gradient`, `light`, `transition`). */\n\tcategory: string;\n\tuses: readonly EffectUse[];\n\tdescription?: string;\n\ttags?: readonly string[];\n\t/** True when the effect's output has transparent pixels (it can sit over other content). */\n\ttransparent: boolean;\n\t/** True when the effect loops; its `duration` is then one cycle. */\n\tloop: boolean;\n\t/** Length of one play (ms). Absent for effects that do not change over time. */\n\tduration?: number;\n}\n\nexport interface EffectSearchOptions {\n\tkind?: EffectKind;\n\tcategory?: string;\n\tuse?: EffectUse;\n\t/** Most results to return. */\n\tlimit?: number;\n}\n\n/** One control value: a number, a `#rrggbb` colour or other string, a switch, or a vector of numbers. */\nexport type EffectValue = number | string | boolean | readonly number[];\nexport type EffectValues = Readonly<Record<string, EffectValue>>;\n\n/**\n * The controls of an effect as a strict JSON Schema: `type: 'object'`, `additionalProperties:\n * false`, and a `description` on every property (with units and range). `checkEffectProvider`\n * checks this.\n */\nexport type EffectControlSchema = JsonSchema & {\n\ttype: 'object';\n\tproperties: { readonly [control: string]: JsonSchema };\n\tadditionalProperties: false;\n};\n\nexport interface EffectPreset {\n\tname: string;\n\t/** Values to apply over the defaults. */\n\tvalues: EffectValues;\n}\n\n/**\n * A named input the effect reads. Filters read `source`, transitions `from` and `to`; a mask is\n * passed separately (`EffectRenderRequest.mask`), not as an input.\n */\nexport interface EffectInputSpec {\n\tname: string;\n\tkind: 'image' | 'audio';\n\tdescription: string;\n\trequired: boolean;\n}\n\n/** Everything an editor needs to show an effect's controls and render it. */\nexport interface EffectDescription extends EffectSummary {\n\tcontrols: EffectControlSchema;\n\t/** A value for every control. */\n\tdefaults: EffectValues;\n\tpresets: readonly EffectPreset[];\n\tinputs: readonly EffectInputSpec[];\n}\n\n/**\n * Pixels in and out of a renderer, shaped like `ImageData`.\n *\n * `data` is 8-bit sRGB with straight alpha and is always present. `float`, when present, is the\n * same picture as 32-bit floats in **linear light** (sRGB primaries), straight alpha, where colour\n * may exceed 1. Renderers created with `depth` 16 or 32 return `float` when the provider\n * `supportsFloat`; `data` is then its clamped sRGB encoding.\n */\nexport interface EffectPixels {\n\twidth: number;\n\theight: number;\n\tdata: Uint8ClampedArray;\n\tfloat?: Float32Array;\n}\n\n/**\n * An input picture. Always accepted as `EffectPixels`; a provider whose capabilities include\n * `supportsHostImages` also takes the host's own image objects, which saves a read back.\n */\nexport type EffectImageSource = EffectPixels | ImageBitmap | OffscreenCanvas | VideoFrame;\n\nexport interface EffectRendererOptions {\n\t/** Output size in pixels. */\n\twidth: number;\n\theight: number;\n\t/** Bits per channel of the target (default 8). 16 and 32 ask for `float` output. */\n\tdepth?: 8 | 16 | 32;\n}\n\nexport interface EffectRenderRequest {\n\t/** Effect time (ms), from the start of the effect. */\n\ttime: number;\n\t/** Control values; missing controls take their defaults. Invalid values reject with `EffectControlError`. */\n\tvalues?: EffectValues;\n\t/** Pictures for the effect's named inputs (see `EffectDescription.inputs`). */\n\tinputs?: Readonly<Record<string, EffectImageSource>>;\n\t/** Coverage (alpha channel, 0 = untouched) limiting where the effect applies. Only with `supportsMask`. */\n\tmask?: EffectImageSource;\n\t/** Transitions: how far from `from` to `to`, 0–1. Defaults to `time / duration`. */\n\tprogress?: number;\n}\n\n/** A live renderer for one effect at one size. Not safe for concurrent `render` calls. */\nexport interface EffectRenderer {\n\treadonly effectId: string;\n\treadonly width: number;\n\treadonly height: number;\n\treadonly depth: 8 | 16 | 32;\n\trender(request: EffectRenderRequest): Promise<EffectPixels>;\n\t/** Frees GPU or worker resources. Rendering afterwards rejects. */\n\tdispose(): void;\n}\n\n/** One change of an animated SVG (the shape of Flair's `SvgAnimation`). */\nexport type EffectSvgAnimation = FlairSvgAnimation;\n\n/** An animated SVG: markup plus changes to its elements (the shape of Flair's `SvgMotion`). */\nexport interface EffectVectorMotion {\n\tsvg: string;\n\tanimate?: readonly EffectSvgAnimation[];\n\t/** Length of one play (ms). */\n\tduration: number;\n\tloop: boolean;\n\t/** Ms held on the last frame before looping. */\n\thold?: number;\n}\n\n/** What a vector or motion effect is applied to: SVG markup, optionally with the ids of the elements to animate (default: all). */\nexport type EffectVectorTarget = string | { svg: string; nodeIds?: readonly string[] };\n\n/** What a provider can do, so editors can degrade cleanly. */\nexport interface EffectProviderCapabilities {\n\t/** Renders off the main thread. */\n\tsupportsWorker: boolean;\n\t/** Returns `float` pixels for depth 16 and 32 renderers. */\n\tsupportsFloat: boolean;\n\t/** Honours `EffectRenderRequest.mask`; otherwise the editor masks the result itself. */\n\tsupportsMask: boolean;\n\t/** Takes `ImageBitmap`, `OffscreenCanvas` or `VideoFrame` inputs, not only `EffectPixels`. */\n\tsupportsHostImages: boolean;\n\t/** Implements `applyVectorEffect`. */\n\tsupportsVector: boolean;\n\t/** Largest width or height a renderer accepts (px). */\n\tmaxSize?: number;\n}\n\ntype MaybePromise<T> = T | Promise<T>;\n\n/**\n * A source of effects. Implementations live outside this library (for example Flair's\n * `flairEffects()`); `createFakeEffectProvider` is a small reference implementation.\n *\n * Unknown ids reject or throw `UnknownEffectError`, invalid values `EffectControlError`, and an\n * operation the provider cannot do `EffectUnsupportedError`.\n */\nexport interface EffectProvider {\n\t/** Stable id of the provider, saved next to effect ids (e.g. `flair`). */\n\treadonly id: string;\n\treadonly name: string;\n\treadonly version?: string;\n\treadonly capabilities: EffectProviderCapabilities;\n\tlist(options?: EffectSearchOptions): MaybePromise<readonly EffectSummary[]>;\n\t/** Effects matching every word of `query` (in name, id, category, tags or description), best first. */\n\tsearch(query: string, options?: EffectSearchOptions): MaybePromise<readonly EffectSummary[]>;\n\tdescribe(id: string): MaybePromise<EffectDescription>;\n\t/** A pixel renderer. A `vector` effect may refuse with `EffectUnsupportedError` where it cannot lay out SVG (a Worker). */\n\tcreateRenderer(id: string, options: EffectRendererOptions): MaybePromise<EffectRenderer>;\n\t/**\n\t * Vector and motion effects as an animated SVG. Present when `capabilities.supportsVector`. A\n\t * `motion` effect animates the target's elements (`nodeIds`, else each top-level element with an\n\t * id); a `vector` effect brings its own picture and ignores the target. Refuse a target the\n\t * effect cannot use with `EffectUnsupportedError`.\n\t */\n\tapplyVectorEffect?(id: string, target: EffectVectorTarget, values?: EffectValues): MaybePromise<EffectVectorMotion>;\n}\n","/**\n * The agent tools for provider effects, shared by every editor that takes an `EffectProvider`:\n * `search_effects`, `describe_effect`, `list_applied_effects`, `apply_effect`, `update_effect` and\n * `remove_effect`. An editor supplies an `EffectToolHost` (what its targets are and how to change\n * them as one undo step each) and may add tools of its own (`extraTools`).\n *\n * Without a provider the read tools say so (and `list_applied_effects` still lists what a\n * document holds), and the write tools refuse with the reason. On a read-only surface the write\n * tools are hidden.\n */\n\nimport type { AgentTool, AgentToolProvider } from '../tools/registry.js';\nimport type { JsonSchema } from '../tools/schema.js';\nimport { isEffectError } from './errors.js';\nimport { EFFECT_KINDS, EFFECT_USES, type EffectDescription, type EffectProvider, type EffectSummary, type EffectUse } from './types.js';\n\n/** One effect applied to a target, as the tools report it. */\nexport interface AppliedEffectInfo {\n\t/** Its id on the target: what `update_effect` and `remove_effect` take. */\n\tid: string;\n\teffect: string;\n\tname?: string;\n\tprovider?: string;\n\t/** What it is on the target (e.g. `clip effect`, `effect clip`, `transition`, `smart filter`, `effect layer`). */\n\trole: string;\n\tenabled: boolean;\n\t/** 0–1, or keyframes, where the role has an opacity. */\n\topacity?: unknown;\n\t/** Its saved control values (numbers may be keyframes where the editor allows them). */\n\tvalues: Record<string, unknown>;\n\t/** Its place in the target's stack (0 = applied first), for stacked roles. */\n\tindex?: number;\n}\n\nexport interface EffectTargetEffects {\n\ttarget: string;\n\t/** A label for the target (a clip or layer name). */\n\tname?: string;\n\teffects: AppliedEffectInfo[];\n}\n\nexport interface EffectChangeResult {\n\ttarget: string;\n\t/** What was added, changed or removed. */\n\teffect: AppliedEffectInfo;\n\t/** The target's effects afterwards. */\n\teffects: AppliedEffectInfo[];\n\t/** Other things the change made (a new clip or layer id, ...). */\n\t[extra: string]: unknown;\n}\n\n/** What an editor gives the shared effect tools. */\nexport interface EffectToolHost {\n\t/** Provider id (unique per registry). */\n\tid: string;\n\t/** Always prefix tool names with `<namespace>__`. */\n\tnamespace?: string;\n\t/** Words for the editor's targets, e.g. `{ noun: 'clip', id: 'A clip id from get_video_project (e.g. \"c1\").' }`. */\n\ttarget: { noun: string; id: string };\n\t/** The uses `apply_effect` takes on a target (others go through `extraTools`). */\n\tapplyUses: readonly EffectUse[];\n\t/** Text added to `apply_effect`'s description: where the effect goes and how it is drawn. */\n\tapplyDetails: string;\n\t/** The current provider, or `null`. */\n\tprovider(): EffectProvider | null;\n\t/** Why edits are refused now (read-only), or `null`. */\n\treadOnlyReason(): string | null;\n\t/** Every target with effects, or one target (throws for an unknown id, naming valid ones). */\n\tlist(target?: string): EffectTargetEffects[];\n\tapply(target: string, effect: string, args: { values?: Record<string, unknown>; index?: number; enabled?: boolean; opacity?: number }): Promise<EffectChangeResult>;\n\tupdate(target: string, instance: string, changes: { values?: Record<string, unknown>; index?: number; enabled?: boolean; opacity?: number }): Promise<EffectChangeResult>;\n\tremove(target: string, instance: string): Promise<EffectChangeResult>;\n\t/** Editor-specific effect tools (transitions, effect clips, effect layers, keyframes). */\n\textraTools?: (context: EffectToolContext) => AgentTool[];\n\t/** Lets the tool list follow the provider and read-only changes. */\n\tsubscribe?: (notify: () => void) => () => void;\n}\n\n/** Shared pieces for `extraTools`. */\nexport interface EffectToolContext {\n\t/** The provider, or a thrown error saying none is registered. */\n\trequireProvider(): EffectProvider;\n\t/** The schema of a `values` argument. */\n\tvaluesSchema(what: string, keyframes?: boolean): JsonSchema;\n\t/** The schema of an `effect` argument for effects with one of `uses`. */\n\teffectIdSchema(uses: readonly EffectUse[]): JsonSchema;\n\treadonly annotations: typeof ANNOTATIONS;\n}\n\nconst ANNOTATIONS = {\n\tread: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },\n\twrite: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },\n\twriteIdempotent: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },\n\tdestructive: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false }\n} as const;\n\nconst NO_PROVIDER = 'No effects provider is registered with this editor, so there are no effects to search, describe or apply. The host app must register one (setEffectsProvider); effects already in the document are kept and shown as placeholders.';\n\nconst object = (properties: Record<string, JsonSchema>, required: string[] = []): JsonSchema & { type: 'object' } => ({\n\ttype: 'object',\n\tproperties,\n\t...(required.length ? { required } : {}),\n\tadditionalProperties: false\n});\n\n/** The catalog fetched once per provider, so tool schemas can list effect ids. */\ninterface Catalog {\n\tprovider: EffectProvider;\n\teffects: readonly EffectSummary[] | null;\n}\n\n/** Most effect ids listed in an `effect` argument's enum; larger catalogs are searched instead. */\nconst ENUM_LIMIT = 60;\n\nconst summaryOut = (e: EffectSummary) => ({\n\tid: e.id,\n\tname: e.name,\n\tkind: e.kind,\n\tcategory: e.category,\n\tuses: e.uses,\n\t...(e.description ? { description: e.description } : {}),\n\ttransparent: e.transparent,\n\tloop: e.loop,\n\t...(e.duration !== undefined ? { duration: e.duration } : {})\n});\n\n/** The agent tools for provider effects in one editor (see the module comment). */\nexport function createEffectToolProvider(host: EffectToolHost): AgentToolProvider {\n\tlet catalog: Catalog | null = null;\n\tconst listeners = new Set<() => void>();\n\tconst notify = () => listeners.forEach((l) => l());\n\n\t/** Fetches the catalog of a new provider in the background; the tool list changes when it lands. */\n\tconst catalogFor = (provider: EffectProvider | null): readonly EffectSummary[] | null => {\n\t\tif (!provider) return null;\n\t\tif (catalog?.provider !== provider) {\n\t\t\tconst entry: Catalog = { provider, effects: null };\n\t\t\tcatalog = entry;\n\t\t\tPromise.resolve()\n\t\t\t\t.then(() => provider.list())\n\t\t\t\t.then((effects) => {\n\t\t\t\t\tif (catalog === entry) {\n\t\t\t\t\t\tentry.effects = effects;\n\t\t\t\t\t\tnotify();\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.catch(() => {});\n\t\t}\n\t\treturn catalog.effects;\n\t};\n\n\tconst requireProvider = (): EffectProvider => {\n\t\tconst p = host.provider();\n\t\tif (!p) throw new Error(NO_PROVIDER);\n\t\treturn p;\n\t};\n\tconst writable = () => {\n\t\tconst reason = host.readOnlyReason();\n\t\tif (reason) throw new Error(reason);\n\t\treturn requireProvider();\n\t};\n\t/** Turns provider errors into messages a model can act on. */\n\tconst explain = async <T>(run: () => Promise<T>): Promise<T> => {\n\t\ttry {\n\t\t\treturn await run();\n\t\t} catch (error) {\n\t\t\tif (isEffectError(error)) throw new Error(error.message);\n\t\t\tthrow error;\n\t\t}\n\t};\n\n\tconst valuesSchema = (what: string, keyframes = false): JsonSchema => ({\n\t\ttype: 'object',\n\t\tdescription: `${what}: control name → value, as listed by describe_effect (its \"controls\" schema: types, ranges, units and defaults). Only the given controls change; colours are \"#rrggbb\".${keyframes ? ' A number control may instead be keyframes { keys: [{ t: ms from the start, v, ease }] }.' : ''} Unknown controls and out-of-range values are refused with the valid ones.`\n\t});\n\tconst effectIdSchema = (uses: readonly EffectUse[]): JsonSchema => {\n\t\tconst effects = catalogFor(host.provider())?.filter((e) => (e.kind !== 'motion' || uses.includes('motion')) && e.uses.some((u) => uses.includes(u)));\n\t\tconst base = `An effect id from search_effects (use ${uses.map((u) => `\"${u}\"`).join(' or ')}).`;\n\t\treturn effects && effects.length && effects.length <= ENUM_LIMIT\n\t\t\t? { type: 'string', enum: effects.map((e) => e.id), description: `${base} One of: ${effects.map((e) => `${e.id} (${e.name})`).join(', ')}.` }\n\t\t\t: { type: 'string', minLength: 1, description: base };\n\t};\n\tconst context: EffectToolContext = { requireProvider: writable, valuesSchema, effectIdSchema, annotations: ANNOTATIONS };\n\n\tconst TARGET = { type: 'string', minLength: 1, description: host.target.id } as const;\n\tconst INSTANCE = { type: 'string', minLength: 1, description: `The effect's id on the ${host.target.noun}, from list_applied_effects or apply_effect.` } as const;\n\tconst INDEX = { type: 'integer', minimum: 0, description: `Place in the ${host.target.noun}'s effect stack: 0 is applied first (default: the end, applied last).` } as const;\n\tconst OPACITY = { type: 'number', minimum: 0, maximum: 1, description: 'How much of the effect shows over its input, 0–1 (default 1).' } as const;\n\tconst ENABLED = { type: 'boolean', description: 'false turns the effect off but keeps it (default true).' } as const;\n\n\tconst readTools = (): AgentTool[] => [\n\t\t{\n\t\t\tname: 'search_effects',\n\t\t\ttitle: 'Search effects',\n\t\t\tdescription: `Searches the effects provider's catalog. Every word of query must appear in an effect's id, name, category, tags or description; filter by kind (shader, vector, motion), category or use (${EFFECT_USES.join(', ')}). For this editor, apply_effect takes uses ${host.applyUses.join(' or ')}. Returns { provider, effects: [{ id, name, kind, category, uses, description, transparent, loop, duration (ms) }], total }. With no provider registered it returns available: false and the reason. Call describe_effect next for an effect's controls.`,\n\t\t\tinputSchema: object({\n\t\t\t\tquery: { type: 'string', description: 'Words to match (default: every effect).' },\n\t\t\t\tkind: { type: 'string', enum: [...EFFECT_KINDS], description: 'shader (pixels), vector (animated SVG) or motion (animates vector art).' },\n\t\t\t\tcategory: { type: 'string', minLength: 1, description: 'The provider\\'s category, e.g. \"gradient\", \"light\", \"transition\".' },\n\t\t\t\tuse: { type: 'string', enum: [...EFFECT_USES], description: 'What the effect is for: filter changes a picture, transition blends two, generator draws a background, overlay draws over content, title draws a title, motion animates vector art, interactive reacts to input.' },\n\t\t\t\tlimit: { type: 'integer', minimum: 1, maximum: 200, description: 'Most effects to return (default 20).' }\n\t\t\t}),\n\t\t\tannotations: { title: 'Search effects', ...ANNOTATIONS.read },\n\t\t\thandler: async (args) => {\n\t\t\t\tconst p = host.provider();\n\t\t\t\tif (!p) return { available: false, reason: NO_PROVIDER, effects: [], total: 0 };\n\t\t\t\tconst found = await explain(async () => p.search((args.query as string | undefined) ?? '', { kind: args.kind, category: args.category, use: args.use }));\n\t\t\t\tconst limit = (args.limit as number | undefined) ?? 20;\n\t\t\t\treturn { available: true, provider: { id: p.id, name: p.name, capabilities: p.capabilities }, effects: found.slice(0, limit).map(summaryOut), total: found.length };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: 'describe_effect',\n\t\t\ttitle: 'Describe an effect',\n\t\t\tdescription: 'Returns one effect\\'s controls as a strict JSON Schema (each control described, with its type, range and units), its defaults, presets (named sets of values) and inputs, plus its summary. Use the control names and ranges for apply_effect and update_effect values. With no provider registered it returns available: false and the reason.',\n\t\t\tinputSchema: object({ effect: { type: 'string', minLength: 1, description: 'An effect id from search_effects or list_applied_effects.' } }, ['effect']),\n\t\t\tannotations: { title: 'Describe an effect', ...ANNOTATIONS.read },\n\t\t\thandler: async (args) => {\n\t\t\t\tconst p = host.provider();\n\t\t\t\tif (!p) return { available: false, reason: NO_PROVIDER };\n\t\t\t\tconst d: EffectDescription = await explain(async () => p.describe(args.effect as string));\n\t\t\t\treturn { available: true, ...summaryOut(d), controls: d.controls, defaults: d.defaults, presets: d.presets, inputs: d.inputs, appliesHere: (d.kind !== 'motion' || host.applyUses.includes('motion')) && d.uses.some((u) => host.applyUses.includes(u)) };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: 'list_applied_effects',\n\t\t\ttitle: 'List applied effects',\n\t\t\tdescription: `Lists the effects in the document: for each ${host.target.noun} that has any (or the one given), its effects in order with id, effect id, name, role, enabled, opacity and saved values. available is false for an effect the current provider does not have (or when none is registered): it is kept and drawn as a placeholder, and can still be removed. Works without a provider.`,\n\t\t\tinputSchema: object({ target: { ...TARGET, description: `${host.target.id} Leave out to list every ${host.target.noun} with effects.` } }),\n\t\t\tannotations: { title: 'List applied effects', ...ANNOTATIONS.read },\n\t\t\thandler: async (args) => {\n\t\t\t\tconst p = host.provider();\n\t\t\t\tconst known = new Set((p ? await explain(async () => p.list()) : []).map((e) => e.id));\n\t\t\t\tconst targets = host.list(args.target as string | undefined).map((t) => ({ ...t, effects: t.effects.map((e) => ({ ...e, available: known.has(e.effect) })) }));\n\t\t\t\treturn { provider: p ? { id: p.id, name: p.name } : null, ...(p ? {} : { reason: NO_PROVIDER }), targets };\n\t\t\t}\n\t\t}\n\t];\n\n\tconst writeTools = (): AgentTool[] => [\n\t\t{\n\t\t\tname: 'apply_effect',\n\t\t\ttitle: 'Apply an effect',\n\t\t\tdescription: `Adds a provider effect to a ${host.target.noun}. ${host.applyDetails} values are checked against describe_effect's controls first; nothing changes if any is wrong. One undo step. Returns the effect with its new id (for update_effect and remove_effect) and the ${host.target.noun}'s effects. Refused when no provider is registered.`,\n\t\t\tinputSchema: object(\n\t\t\t\t{\n\t\t\t\t\ttarget: TARGET,\n\t\t\t\t\teffect: effectIdSchema(host.applyUses),\n\t\t\t\t\tvalues: valuesSchema('Control values over the effect\\'s defaults', true),\n\t\t\t\t\tindex: INDEX,\n\t\t\t\t\tenabled: ENABLED,\n\t\t\t\t\topacity: OPACITY\n\t\t\t\t},\n\t\t\t\t['target', 'effect']\n\t\t\t),\n\t\t\tannotations: { title: 'Apply an effect', ...ANNOTATIONS.write },\n\t\t\thandler: async (args) => {\n\t\t\t\twritable();\n\t\t\t\treturn explain(() => host.apply(args.target as string, args.effect as string, { values: args.values, index: args.index, enabled: args.enabled, opacity: args.opacity }));\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: 'update_effect',\n\t\t\ttitle: 'Change an applied effect',\n\t\t\tdescription: `Changes one applied effect on a ${host.target.noun}: its values (merged over the current ones; null resets a control to its default), enabled, opacity or place in the stack. Values are checked against describe_effect's controls first. One undo step. Returns the effect as it is now and the ${host.target.noun}'s effects. Refused when no provider is registered.`,\n\t\t\tinputSchema: object(\n\t\t\t\t{\n\t\t\t\t\ttarget: TARGET,\n\t\t\t\t\teffect: INSTANCE,\n\t\t\t\t\tvalues: { ...valuesSchema('Control values to change', true), description: `${valuesSchema('Control values to change', true).description} null resets a control to its default.` },\n\t\t\t\t\tenabled: ENABLED,\n\t\t\t\t\topacity: OPACITY,\n\t\t\t\t\tindex: { ...INDEX, description: `Move it to this place in the ${host.target.noun}'s stack (0 = applied first).` }\n\t\t\t\t},\n\t\t\t\t['target', 'effect']\n\t\t\t),\n\t\t\tannotations: { title: 'Change an applied effect', ...ANNOTATIONS.writeIdempotent },\n\t\t\thandler: async (args) => {\n\t\t\t\twritable();\n\t\t\t\tif (args.values === undefined && args.enabled === undefined && args.opacity === undefined && args.index === undefined) throw new Error('Give at least one of values, enabled, opacity or index to change.');\n\t\t\t\treturn explain(() => host.update(args.target as string, args.effect as string, { values: args.values, enabled: args.enabled, opacity: args.opacity, index: args.index }));\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: 'remove_effect',\n\t\t\ttitle: 'Remove an applied effect',\n\t\t\tdescription: `Removes one applied effect from a ${host.target.noun} (an effect the provider no longer has included). One undo step. Returns what was removed and the ${host.target.noun}'s remaining effects. Refused when no provider is registered.`,\n\t\t\tinputSchema: object({ target: TARGET, effect: INSTANCE }, ['target', 'effect']),\n\t\t\tannotations: { title: 'Remove an applied effect', ...ANNOTATIONS.destructive },\n\t\t\thandler: async (args) => {\n\t\t\t\twritable();\n\t\t\t\treturn explain(() => host.remove(args.target as string, args.effect as string));\n\t\t\t}\n\t\t}\n\t];\n\n\treturn {\n\t\tid: host.id,\n\t\t...(host.namespace ? { namespace: host.namespace } : {}),\n\t\ttools: () => {\n\t\t\tconst extra = host.extraTools?.(context) ?? [];\n\t\t\tif (host.readOnlyReason()) return [...readTools(), ...extra.filter((t) => t.annotations?.readOnlyHint)];\n\t\t\treturn [...readTools(), ...writeTools(), ...extra];\n\t\t},\n\t\tsubscribe: (l) => {\n\t\t\tlisteners.add(l);\n\t\t\tconst off = host.subscribe?.(l);\n\t\t\treturn () => {\n\t\t\t\tlisteners.delete(l);\n\t\t\t\toff?.();\n\t\t\t};\n\t\t}\n\t};\n}\n"]}
@@ -1191,4 +1191,4 @@ export {
1191
1191
  simplifyRing,
1192
1192
  polygonToSvgPath
1193
1193
  };
1194
- //# sourceMappingURL=chunk-GLWZXQ4Q.js.map
1194
+ //# sourceMappingURL=chunk-KHNZ6MOU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/canvas/gradient.ts","../src/canvas/curveFit.ts","../src/canvas/shapeGeometry.ts"],"sourcesContent":["/**\n * Canvas gradient models, parsing, presets, and SVG defs generation.\n * Supports linear and radial gradients for shape fills, strokes, and freehand drawing.\n */\n\nexport interface GradientStop {\n\toffset: number; // 0 to 1\n\tcolor: string;\n\topacity?: number;\n}\n\nexport interface CanvasLinearGradient {\n\ttype: 'linear';\n\tangle?: number; // degrees clockwise, default 90 (top-to-bottom) or custom\n\tstops: GradientStop[];\n}\n\nexport interface CanvasRadialGradient {\n\ttype: 'radial';\n\tcx?: number; // 0 to 1 (default 0.5)\n\tcy?: number; // 0 to 1 (default 0.5)\n\tr?: number; // 0 to 1 (default 0.5)\n\tstops: GradientStop[];\n}\n\nexport type CanvasGradientDef = CanvasLinearGradient | CanvasRadialGradient;\n\nexport interface SvgGradientStop {\n\toffset: string;\n\tstopColor: string;\n\tstopOpacity?: number;\n}\n\nexport interface SvgGradientDef {\n\tid: string;\n\ttype: 'linear' | 'radial';\n\tattrs: Record<string, string | number>;\n\tstops: SvgGradientStop[];\n}\n\nexport const PIXERATE_BRAND_GRADIENT: CanvasLinearGradient = {\n\ttype: 'linear',\n\tangle: 135,\n\tstops: [\n\t\t{ offset: 0, color: '#8E51FF' },\n\t\t{ offset: 1, color: '#e12afb' }\n\t]\n};\n\nexport const CANVAS_GRADIENT_PRESETS: Record<string, CanvasLinearGradient> = {\n\tpixerate: PIXERATE_BRAND_GRADIENT,\n\tsunset: {\n\t\ttype: 'linear',\n\t\tangle: 90,\n\t\tstops: [\n\t\t\t{ offset: 0, color: '#f97316' },\n\t\t\t{ offset: 1, color: '#ec4899' }\n\t\t]\n\t},\n\tocean: {\n\t\ttype: 'linear',\n\t\tangle: 90,\n\t\tstops: [\n\t\t\t{ offset: 0, color: '#06b6d4' },\n\t\t\t{ offset: 1, color: '#3b82f6' }\n\t\t]\n\t},\n\taurora: {\n\t\ttype: 'linear',\n\t\tangle: 90,\n\t\tstops: [\n\t\t\t{ offset: 0, color: '#10b981' },\n\t\t\t{ offset: 1, color: '#6366f1' }\n\t\t]\n\t},\n\tneon: {\n\t\ttype: 'linear',\n\t\tangle: 90,\n\t\tstops: [\n\t\t\t{ offset: 0, color: '#a855f7' },\n\t\t\t{ offset: 1, color: '#ec4899' }\n\t\t]\n\t},\n\tamber: {\n\t\ttype: 'linear',\n\t\tangle: 90,\n\t\tstops: [\n\t\t\t{ offset: 0, color: '#f59e0b' },\n\t\t\t{ offset: 1, color: '#ef4444' }\n\t\t]\n\t},\n\tcosmic: {\n\t\ttype: 'linear',\n\t\tangle: 90,\n\t\tstops: [\n\t\t\t{ offset: 0, color: '#3b82f6' },\n\t\t\t{ offset: 0.5, color: '#8b5cf6' },\n\t\t\t{ offset: 1, color: '#ec4899' }\n\t\t]\n\t}\n};\n\n/** Whether an arbitrary value matches a CanvasGradientDef object. */\nexport function isCanvasGradient(value: unknown): value is CanvasGradientDef {\n\tif (!value || typeof value !== 'object') return false;\n\tconst val = value as Partial<CanvasGradientDef>;\n\tif (val.type !== 'linear' && val.type !== 'radial') return false;\n\tif (!Array.isArray(val.stops)) return false;\n\treturn true;\n}\n\n/**\n * Splits CSS function arguments respecting nested parentheses.\n * e.g. \"rgba(255, 0, 0, 0.5) 0%, #00f 100%\" -> [\"rgba(255, 0, 0, 0.5) 0%\", \"#00f 100%\"]\n */\nfunction splitCssArgs(str: string): string[] {\n\tconst parts: string[] = [];\n\tlet depth = 0;\n\tlet current = '';\n\tfor (let i = 0; i < str.length; i++) {\n\t\tconst char = str[i];\n\t\tif (char === '(') depth++;\n\t\telse if (char === ')') depth = Math.max(0, depth - 1);\n\t\tif (char === ',' && depth === 0) {\n\t\t\tif (current.trim()) parts.push(current.trim());\n\t\t\tcurrent = '';\n\t\t} else {\n\t\t\tcurrent += char;\n\t\t}\n\t}\n\tif (current.trim()) parts.push(current.trim());\n\treturn parts;\n}\n\n/** Parses CSS angle strings like \"90deg\", \"0.25turn\", \"1.57rad\" or named directions like \"to bottom\" */\nfunction parseCssAngle(val: string): number {\n\tconst trimmed = val.trim().toLowerCase();\n\tif (trimmed.endsWith('deg')) {\n\t\treturn parseFloat(trimmed);\n\t}\n\tif (trimmed.endsWith('turn')) {\n\t\treturn parseFloat(trimmed) * 360;\n\t}\n\tif (trimmed.endsWith('rad')) {\n\t\treturn (parseFloat(trimmed) * 180) / Math.PI;\n\t}\n\tif (trimmed.startsWith('to ')) {\n\t\tconst dir = trimmed.slice(3).trim();\n\t\tif (dir === 'bottom') return 180;\n\t\tif (dir === 'top') return 0;\n\t\tif (dir === 'right') return 90;\n\t\tif (dir === 'left') return 270;\n\t\tif (dir === 'bottom right' || dir === 'right bottom') return 135;\n\t\tif (dir === 'bottom left' || dir === 'left bottom') return 225;\n\t\tif (dir === 'top right' || dir === 'right top') return 45;\n\t\tif (dir === 'top left' || dir === 'left top') return 315;\n\t}\n\tconst n = parseFloat(trimmed);\n\treturn Number.isFinite(n) ? n : 180;\n}\n\n/**\n * Parses CSS linear-gradient or radial-gradient strings into CanvasGradientDef.\n * Supports forms like:\n * - linear-gradient(90deg, #ff0000 0%, #0000ff 100%)\n * - linear-gradient(to right, red, blue)\n * - radial-gradient(circle, red 0%, blue 100%)\n */\nexport function parseCssGradient(css: string): CanvasGradientDef | null {\n\tconst trimmed = css.trim();\n\tconst linearMatch = trimmed.match(/^linear-gradient\\s*\\((.*)\\)$/is);\n\tif (linearMatch) {\n\t\tconst rawArgs = splitCssArgs(linearMatch[1]);\n\t\tif (rawArgs.length === 0) return null;\n\t\tlet angle = 180; // default in CSS linear-gradient without direction is to bottom (180deg)\n\t\tlet stopStartIndex = 0;\n\n\t\tconst first = rawArgs[0].trim().toLowerCase();\n\t\tif (first.endsWith('deg') || first.endsWith('turn') || first.endsWith('rad') || first.startsWith('to ')) {\n\t\t\tangle = parseCssAngle(first);\n\t\t\tstopStartIndex = 1;\n\t\t}\n\n\t\tconst stopStrings = rawArgs.slice(stopStartIndex);\n\t\tif (stopStrings.length === 0) return null;\n\t\tconst stops = parseStopStrings(stopStrings);\n\t\tif (stops.length === 0) return null;\n\t\treturn {\n\t\t\ttype: 'linear',\n\t\t\tangle,\n\t\t\tstops\n\t\t};\n\t}\n\n\tconst radialMatch = trimmed.match(/^radial-gradient\\s*\\((.*)\\)$/is);\n\tif (radialMatch) {\n\t\tconst rawArgs = splitCssArgs(radialMatch[1]);\n\t\tif (rawArgs.length === 0) return null;\n\t\tlet stopStartIndex = 0;\n\t\tconst first = rawArgs[0].trim().toLowerCase();\n\t\tif (first.startsWith('circle') || first.startsWith('ellipse') || first.includes('at ')) {\n\t\t\tstopStartIndex = 1;\n\t\t}\n\t\tconst stopStrings = rawArgs.slice(stopStartIndex);\n\t\tif (stopStrings.length === 0) return null;\n\t\tconst stops = parseStopStrings(stopStrings);\n\t\tif (stops.length === 0) return null;\n\t\treturn {\n\t\t\ttype: 'radial',\n\t\t\tcx: 0.5,\n\t\t\tcy: 0.5,\n\t\t\tr: 0.5,\n\t\t\tstops\n\t\t};\n\t}\n\n\treturn null;\n}\n\nfunction parseStopStrings(stopStrings: string[]): GradientStop[] {\n\tconst count = stopStrings.length;\n\treturn stopStrings.map((str, idx) => {\n\t\tconst parts = str.trim().split(/\\s+(?=[0-9%])/);\n\t\tconst color = parts[0];\n\t\tlet offset = count === 1 ? 0 : idx / (count - 1);\n\t\tif (parts.length > 1) {\n\t\t\tconst posStr = parts[1].trim();\n\t\t\tif (posStr.endsWith('%')) {\n\t\t\t\toffset = parseFloat(posStr) / 100;\n\t\t\t} else {\n\t\t\t\tconst val = parseFloat(posStr);\n\t\t\t\tif (Number.isFinite(val)) offset = val;\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\toffset: Math.min(1, Math.max(0, offset)),\n\t\t\tcolor\n\t\t};\n\t});\n}\n\n/**\n * Resolves a paint value (which could be a CSS color, preset name, CSS gradient string, or CanvasGradientDef)\n * into either a CanvasGradientDef (if gradient) or null (if solid color or invalid).\n */\nexport function resolveCanvasGradient(value: unknown): CanvasGradientDef | null {\n\tif (!value) return null;\n\tif (isCanvasGradient(value)) return value;\n\tif (typeof value === 'string') {\n\t\tconst lower = value.trim().toLowerCase();\n\t\tif (CANVAS_GRADIENT_PRESETS[lower]) {\n\t\t\treturn CANVAS_GRADIENT_PRESETS[lower];\n\t\t}\n\t\tif (lower.startsWith('linear-gradient') || lower.startsWith('radial-gradient')) {\n\t\t\treturn parseCssGradient(value);\n\t\t}\n\t}\n\treturn null;\n}\n\n/**\n * Converts degrees clockwise (CSS angle: 0 = top, 90 = right, 180 = bottom, 270 = left)\n * to SVG linearGradient vector coordinates (x1, y1, x2, y2) normalized [0, 1].\n */\nexport function angleToSvgLinearCoords(angleDeg: number = 180): { x1: number; y1: number; x2: number; y2: number } {\n\t// Standard CSS angle: 0deg points UP (towards -Y in standard canvas coordinates)\n\t// Convert to standard mathematical angle in radians (0 at +X, counterclockwise)\n\t// CSS 0deg = Math 90deg (up)\n\t// CSS angle A -> Math theta = 90 - A\n\tconst rad = ((90 - angleDeg) * Math.PI) / 180;\n\t// Vector direction\n\tconst dx = Math.cos(rad);\n\tconst dy = -Math.sin(rad); // invert for SVG/screen y-down coords\n\n\t// Project from center (0.5, 0.5) to edges\n\tconst half = 0.5;\n\treturn {\n\t\tx1: Math.round((half - dx * half) * 1000) / 1000,\n\t\ty1: Math.round((half - dy * half) * 1000) / 1000,\n\t\tx2: Math.round((half + dx * half) * 1000) / 1000,\n\t\ty2: Math.round((half + dy * half) * 1000) / 1000\n\t};\n}\n\n/**\n * Converts a CanvasGradientDef to an SvgGradientDef descriptor ready for rendering `<linearGradient>` / `<radialGradient>`.\n */\nexport function gradientToSvgDef(gradient: CanvasGradientDef, id: string): SvgGradientDef {\n\tconst stops: SvgGradientStop[] = (gradient.stops ?? []).map((s) => ({\n\t\toffset: `${Math.round(s.offset * 1000) / 10}%`,\n\t\tstopColor: s.color,\n\t\tstopOpacity: s.opacity\n\t}));\n\n\tif (gradient.type === 'radial') {\n\t\treturn {\n\t\t\tid,\n\t\t\ttype: 'radial',\n\t\t\tattrs: {\n\t\t\t\tcx: gradient.cx !== undefined ? `${gradient.cx * 100}%` : '50%',\n\t\t\t\tcy: gradient.cy !== undefined ? `${gradient.cy * 100}%` : '50%',\n\t\t\t\tr: gradient.r !== undefined ? `${gradient.r * 100}%` : '50%'\n\t\t\t},\n\t\t\tstops\n\t\t};\n\t}\n\n\tconst coords = angleToSvgLinearCoords(gradient.angle ?? 180);\n\treturn {\n\t\tid,\n\t\ttype: 'linear',\n\t\tattrs: {\n\t\t\tx1: `${coords.x1 * 100}%`,\n\t\t\ty1: `${coords.y1 * 100}%`,\n\t\t\tx2: `${coords.x2 * 100}%`,\n\t\t\ty2: `${coords.y2 * 100}%`\n\t\t},\n\t\tstops\n\t};\n}\n","/**\n * Least-squares cubic Bézier fitting of point sequences (Schneider-style: fit one cubic with\n * fixed end tangents, reparameterise with Newton steps, split at the worst point), with\n * corner preservation by a turning-angle test.\n *\n * Portions ported from vectorcraft-main/crates/pathops/src/fit.rs and\n * vectorcraft-main/crates/pathops/src/edit.rs (MIT OR Apache-2.0, © ArtCraft Team and\n * contributors). See THIRD_PARTY_NOTICES.md.\n */\nimport type { Point } from './types.js';\n\n/** Same as `formatNumber` in shapeGeometry (kept local to avoid an import cycle). */\nfunction formatNumber(value: number, precision: number): string {\n\tconst factor = 10 ** precision;\n\tconst rounded = Math.round(value * factor) / factor;\n\treturn Object.is(rounded, -0) ? '0' : String(rounded);\n}\n\n/** One cubic Bézier segment. */\nexport interface CubicSegment {\n\tp0: Point;\n\tp1: Point;\n\tp2: Point;\n\tp3: Point;\n}\n\nexport interface FitCubicsOptions {\n\t/**\n\t * Vertices where the polyline turns by more than this many degrees stay sharp corners\n\t * (default 30). Use 180 to smooth through every vertex.\n\t */\n\tcornerAngleDeg?: number;\n\t/** Treat the points as a closed ring (the last point connects back to the first). */\n\tclosed?: boolean;\n}\n\n/** Maximum Newton reparameterisation rounds per fit. */\nconst MAX_REPARAM = 6;\n\ntype Vec = [number, number];\n\nconst sub = (a: Point, b: Point): Vec => [a[0] - b[0], a[1] - b[1]];\nconst add = (a: Point, v: Vec, s = 1): Vec => [a[0] + v[0] * s, a[1] + v[1] * s];\nconst dot = (a: Vec, b: Vec) => a[0] * b[0] + a[1] * b[1];\nconst dist = (a: Point, b: Point) => Math.hypot(a[0] - b[0], a[1] - b[1]);\n\nfunction unit(v: Vec): Vec | null {\n\tconst l = Math.hypot(v[0], v[1]);\n\treturn l > 1e-12 && Number.isFinite(l) ? [v[0] / l, v[1] / l] : null;\n}\n\nfunction evalCubic(c: CubicSegment, t: number): Vec {\n\tconst s = 1 - t;\n\tconst b0 = s * s * s;\n\tconst b1 = 3 * s * s * t;\n\tconst b2 = 3 * s * t * t;\n\tconst b3 = t * t * t;\n\treturn [\n\t\tb0 * c.p0[0] + b1 * c.p1[0] + b2 * c.p2[0] + b3 * c.p3[0],\n\t\tb0 * c.p0[1] + b1 * c.p1[1] + b2 * c.p2[1] + b3 * c.p3[1]\n\t];\n}\n\n/** Evaluates a cubic segment at `t` ∈ [0, 1]. */\nexport function cubicPointAt(c: CubicSegment, t: number): Point {\n\treturn evalCubic(c, t);\n}\n\nfunction dedup(points: readonly Point[]): Point[] {\n\tconst out: Point[] = [];\n\tfor (const p of points) {\n\t\tif (!Number.isFinite(p[0]) || !Number.isFinite(p[1])) continue;\n\t\tif (out.length === 0 || dist(out[out.length - 1], p) > 1e-12) out.push(p);\n\t}\n\treturn out;\n}\n\n/** Chord-length parameters (0 to 1), one per point. */\nfunction chordParams(pts: Point[]): number[] {\n\tconst u = [0];\n\tlet acc = 0;\n\tfor (let i = 1; i < pts.length; i++) {\n\t\tacc += dist(pts[i - 1], pts[i]);\n\t\tu.push(acc);\n\t}\n\treturn acc > 0 ? u.map((x) => x / acc) : u;\n}\n\n/** Solves the 2×2 normal equations for the handle lengths along the fixed tangents. */\nfunction generate(pts: Point[], u: number[], t0: Vec, t1: Vec): CubicSegment {\n\tconst p0 = pts[0];\n\tconst p3 = pts[pts.length - 1];\n\tconst dirIn: Vec = [-t1[0], -t1[1]];\n\tlet c00 = 0;\n\tlet c01 = 0;\n\tlet c11 = 0;\n\tlet x0 = 0;\n\tlet x1 = 0;\n\tfor (let i = 0; i < pts.length; i++) {\n\t\tconst t = u[i];\n\t\tconst s = 1 - t;\n\t\tconst b0 = s * s * s;\n\t\tconst b1 = 3 * s * s * t;\n\t\tconst b2 = 3 * s * t * t;\n\t\tconst b3 = t * t * t;\n\t\tconst a0: Vec = [t0[0] * b1, t0[1] * b1];\n\t\tconst a1: Vec = [dirIn[0] * b2, dirIn[1] * b2];\n\t\tc00 += dot(a0, a0);\n\t\tc01 += dot(a0, a1);\n\t\tc11 += dot(a1, a1);\n\t\tconst tmp: Vec = [\n\t\t\tpts[i][0] - (p0[0] * (b0 + b1) + p3[0] * (b2 + b3)),\n\t\t\tpts[i][1] - (p0[1] * (b0 + b1) + p3[1] * (b2 + b3))\n\t\t];\n\t\tx0 += dot(a0, tmp);\n\t\tx1 += dot(a1, tmp);\n\t}\n\tconst det = c00 * c11 - c01 * c01;\n\tconst seg = dist(p0, p3);\n\tconst eps = 1e-6 * seg;\n\tlet al = seg / 3;\n\tlet ar = seg / 3;\n\tif (Math.abs(det) > 1e-12) {\n\t\tal = (x0 * c11 - x1 * c01) / det;\n\t\tar = (c00 * x1 - c01 * x0) / det;\n\t}\n\tif (!Number.isFinite(al) || !Number.isFinite(ar) || al < eps || ar < eps) {\n\t\tal = seg / 3;\n\t\tar = seg / 3;\n\t}\n\t// Guard against wild handles on nearly degenerate data.\n\tconst cap = seg * 4 + 1e-9;\n\tal = Math.min(al, cap);\n\tar = Math.min(ar, cap);\n\treturn { p0, p1: add(p0, t0, al), p2: add(p3, dirIn, ar), p3 };\n}\n\n/** Largest distance between a point and the curve at its parameter, and that point's index. */\nfunction maxError(pts: Point[], c: CubicSegment, u: number[]): [number, number] {\n\tlet e = 0;\n\tlet idx = pts.length >> 1;\n\tfor (let i = 0; i < pts.length; i++) {\n\t\tconst d = dist(evalCubic(c, u[i]), pts[i]);\n\t\tif (d > e) {\n\t\t\te = d;\n\t\t\tidx = i;\n\t\t}\n\t}\n\treturn [e, idx];\n}\n\n/** One Newton–Raphson step towards the parameter of the point on `c` nearest `p`. */\nfunction newton(c: CubicSegment, p: Point, t: number): number {\n\tconst s = 1 - t;\n\tconst q = evalCubic(c, t);\n\tconst d1: Vec = [\n\t\t3 * (s * s * (c.p1[0] - c.p0[0]) + 2 * s * t * (c.p2[0] - c.p1[0]) + t * t * (c.p3[0] - c.p2[0])),\n\t\t3 * (s * s * (c.p1[1] - c.p0[1]) + 2 * s * t * (c.p2[1] - c.p1[1]) + t * t * (c.p3[1] - c.p2[1]))\n\t];\n\tconst d2: Vec = [\n\t\t6 * (s * (c.p2[0] - 2 * c.p1[0] + c.p0[0]) + t * (c.p3[0] - 2 * c.p2[0] + c.p1[0])),\n\t\t6 * (s * (c.p2[1] - 2 * c.p1[1] + c.p0[1]) + t * (c.p3[1] - 2 * c.p2[1] + c.p1[1]))\n\t];\n\tconst diff: Vec = [q[0] - p[0], q[1] - p[1]];\n\tconst num = dot(diff, d1);\n\tconst den = dot(d1, d1) + dot(diff, d2);\n\tif (Math.abs(den) < 1e-12) return t;\n\tconst nt = t - num / den;\n\treturn Number.isFinite(nt) ? Math.min(1, Math.max(0, nt)) : t;\n}\n\n/**\n * Best single cubic through `pts` with the given unit end tangents (`t1` points forward at\n * the end), starting from parameters `u`. Returns the curve, its max error and the index of\n * the worst point.\n */\nfunction fitSingleFrom(pts: Point[], u: number[], t0: Vec, t1: Vec): [CubicSegment, number, number] {\n\tlet best = generate(pts, u, t0, t1);\n\tlet [bestErr, bestSplit] = maxError(pts, best, u);\n\tconst params = u.slice();\n\tfor (let round = 0; round < MAX_REPARAM; round++) {\n\t\tfor (let i = 0; i < params.length; i++) params[i] = newton(best, pts[i], params[i]);\n\t\tconst c = generate(pts, params, t0, t1);\n\t\tconst [e, s] = maxError(pts, c, params);\n\t\tif (e < bestErr) {\n\t\t\tbest = c;\n\t\t\tbestErr = e;\n\t\t\tbestSplit = s;\n\t\t} else break;\n\t}\n\treturn [best, bestErr, bestSplit];\n}\n\n/**\n * The best single cubic from the first to the last of `points`, leaving along the unit tangent\n * `t0` and arriving along `t1` (forward), with the points starting at parameters `params`\n * (refined by Newton steps). Returns the curve and its largest point error.\n */\nexport function fitCubicWithTangents(points: readonly Point[], params: readonly number[], t0: Point, t1: Point): { curve: CubicSegment; error: number } {\n\tconst [curve, error] = fitSingleFrom(points.slice(), params.slice(), [t0[0], t0[1]], [t1[0], t1[1]]);\n\treturn { curve, error };\n}\n\nfunction fitRec(pts: Point[], t0: Vec, t1: Vec, tol: number, out: CubicSegment[], depth: number) {\n\tconst n = pts.length;\n\tif (n === 2) {\n\t\tconst d = dist(pts[0], pts[1]) / 3;\n\t\tout.push({ p0: pts[0], p1: add(pts[0], t0, d), p2: add(pts[1], t1, -d), p3: pts[1] });\n\t\treturn;\n\t}\n\tconst [c, err, splitAt] = fitSingleFrom(pts, chordParams(pts), t0, t1);\n\tif (err <= tol || depth > 40) {\n\t\tout.push(c);\n\t\treturn;\n\t}\n\t// Split at the worst point with a centre tangent estimated from its neighbours.\n\tconst split = Math.min(n - 2, Math.max(1, splitAt));\n\tconst tc = unit(sub(pts[split + 1], pts[split - 1])) ?? t0;\n\tfitRec(pts.slice(0, split + 1), t0, tc, tol, out, depth + 1);\n\tfitRec(pts.slice(split), tc, t1, tol, out, depth + 1);\n}\n\n/**\n * Unit tangent at `a` estimated from the parabola through `a`, `b`, `c` (chord-length\n * parameters): second-order accurate, so polylines sampled from curves get their true end\n * direction rather than the first chord's.\n */\nfunction tangentFrom(a: Point, b: Point, c: Point | undefined): Vec | null {\n\tconst chord = unit(sub(b, a));\n\tif (!c) return chord;\n\tconst d1 = dist(a, b);\n\tconst d2 = dist(b, c);\n\tif (!(d1 > 0) || !(d2 > 0)) return chord;\n\tconst ka = -(2 * d1 + d2) / (d1 * (d1 + d2));\n\tconst kb = (d1 + d2) / (d1 * d2);\n\tconst kc = -d1 / (d2 * (d1 + d2));\n\tconst est = unit([ka * a[0] + kb * b[0] + kc * c[0], ka * a[1] + kb * b[1] + kc * c[1]]);\n\t// Fall back to the chord when the estimate swings too far (noisy or sharp data).\n\treturn est && chord && dot(est, chord) > Math.cos(Math.PI / 4) ? est : chord;\n}\n\n/**\n * Fits a G1-continuous chain of cubics through `points` (an open run) with the unit\n * tangents `t0` (leaving the first point) and `t1` (arriving at the last point, forward);\n * both are estimated from the end points when omitted. Every point lies within `tolerance`\n * of the curve at its fitted parameter.\n */\nexport function fitCubicRun(points: readonly Point[], tolerance: number, t0?: Point, t1?: Point): CubicSegment[] {\n\tconst pts = dedup(points);\n\tconst out: CubicSegment[] = [];\n\tif (pts.length < 2) return out;\n\tconst n = pts.length;\n\tconst start = (t0 && unit([t0[0], t0[1]])) ?? tangentFrom(pts[0], pts[1], pts[2]) ?? [1, 0];\n\tconst back = tangentFrom(pts[n - 1], pts[n - 2], pts[n - 3]);\n\tconst end = (t1 && unit([t1[0], t1[1]])) ?? (back ? ([-back[0], -back[1]] as Vec) : [1, 0]);\n\tfitRec(pts, start, end, Math.max(tolerance, 1e-9), out, 0);\n\treturn out;\n}\n\n/** Turning angle in degrees between the directions `a`→`b` and `b`→`c`. */\nfunction turnDeg(a: Point, b: Point, c: Point): number {\n\tconst u = unit(sub(b, a));\n\tconst v = unit(sub(c, b));\n\tif (!u || !v) return 0;\n\treturn (Math.acos(Math.min(1, Math.max(-1, dot(u, v)))) * 180) / Math.PI;\n}\n\n/**\n * Corner vertices of a polyline. The turn at each vertex is measured to the nearest\n * neighbours at least `span` away on each side (so sample noise smaller than the fitting\n * tolerance does not read as corners), and only the sharpest vertex of a neighbourhood is\n * kept. End points of open polylines are not included.\n */\nfunction findCorners(pts: Point[], closed: boolean, cornerAngle: number, span: number): number[] {\n\tconst n = pts.length;\n\tconst at = (i: number) => pts[closed ? ((i % n) + n) % n : i];\n\tconst reach = (i: number, step: 1 | -1): number | null => {\n\t\tfor (let k = 1; k < (closed ? n : Infinity); k++) {\n\t\t\tconst j = i + step * k;\n\t\t\tif (!closed && (j < 0 || j >= n)) return k > 1 ? j - step : null;\n\t\t\tif (dist(at(j), pts[i]) >= span) return j;\n\t\t}\n\t\treturn null;\n\t};\n\tconst turns = new Float64Array(n);\n\tconst windows: [number, number][] = [];\n\tfor (let i = 0; i < n; i++) {\n\t\twindows.push([i, i]);\n\t\tif (!closed && (i === 0 || i === n - 1)) continue;\n\t\tconst prev = reach(i, -1);\n\t\tconst next = reach(i, 1);\n\t\tif (prev === null || next === null) continue;\n\t\twindows[i] = [prev, next];\n\t\tturns[i] = turnDeg(at(prev), pts[i], at(next));\n\t}\n\tconst corners: number[] = [];\n\tfor (let i = 0; i < n; i++) {\n\t\tif (!(turns[i] > cornerAngle)) continue;\n\t\tconst [lo, hi] = windows[i];\n\t\tlet sharpest = true;\n\t\tfor (let j = lo; j <= hi && sharpest; j++) {\n\t\t\tconst k = closed ? ((j % n) + n) % n : j;\n\t\t\tif (k === i || dist(pts[k], pts[i]) >= span) continue;\n\t\t\tif (turns[k] > turns[i] || (turns[k] === turns[i] && k < i)) sharpest = false;\n\t\t}\n\t\tif (sharpest) corners.push(i);\n\t}\n\treturn corners;\n}\n\n/**\n * Points to fit for a run of polyline vertices: the vertices, plus extra samples along edges\n * much longer than the run's typical edge so straight stretches stay straight.\n */\nfunction densify(run: Point[]): Point[] {\n\tif (run.length < 3) return run;\n\tconst lengths: number[] = [];\n\tfor (let i = 1; i < run.length; i++) lengths.push(dist(run[i - 1], run[i]));\n\tconst sorted = [...lengths].sort((a, b) => a - b);\n\tconst median = sorted[sorted.length >> 1];\n\tif (!(median > 0)) return run;\n\tconst out: Point[] = [run[0]];\n\tfor (let i = 1; i < run.length; i++) {\n\t\tconst len = lengths[i - 1];\n\t\tif (len > 2 * median) {\n\t\t\tconst steps = Math.min(64, Math.ceil(len / median));\n\t\t\tconst a = run[i - 1];\n\t\t\tconst b = run[i];\n\t\t\tfor (let k = 1; k < steps; k++) {\n\t\t\t\tconst t = k / steps;\n\t\t\t\tout.push([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]);\n\t\t\t}\n\t\t}\n\t\tout.push(run[i]);\n\t}\n\treturn out;\n}\n\n/**\n * Fits cubic Bézier segments to a polyline (`closed` for a ring), keeping vertices that turn\n * by more than `cornerAngleDeg` (default 30°) as sharp corners. Each stretch between corners\n * is fitted Schneider-style so that every input point is within `tolerance` of the result.\n *\n * Returns the segments in order (consecutive segments share end points; a closed result ends\n * where it starts). Fewer than two distinct points give an empty array.\n */\nexport function fitCubics(points: readonly Point[], tolerance: number, options: FitCubicsOptions = {}): CubicSegment[] {\n\tlet pts = dedup(points);\n\tconst closed = options.closed === true;\n\tif (closed && pts.length > 1 && dist(pts[0], pts[pts.length - 1]) <= 1e-12) pts = pts.slice(0, -1);\n\tif (pts.length < 2) return [];\n\tconst tol = Math.max(tolerance, 1e-6);\n\tconst cornerAngle = options.cornerAngleDeg ?? 30;\n\tconst n = pts.length;\n\tconst span = 4 * tol;\n\n\tif (!closed || n < 3) {\n\t\tconst corners = [0, ...(n > 2 ? findCorners(pts, false, cornerAngle, span) : []), n - 1];\n\t\tconst out: CubicSegment[] = [];\n\t\tfor (let k = 1; k < corners.length; k++) {\n\t\t\tconst run = pts.slice(corners[k - 1], corners[k] + 1);\n\t\t\tout.push(...fitCubicRun(densify(run), tol));\n\t\t}\n\t\tif (closed && n === 2) out.push(...fitCubicRun([pts[1], pts[0]], tol));\n\t\treturn out;\n\t}\n\n\tconst corners = findCorners(pts, true, cornerAngle, span);\n\tif (corners.length === 0) {\n\t\t// Smooth ring: start anywhere, with the same tangent leaving and arriving.\n\t\tconst ring = [...pts, pts[0]];\n\t\tconst t = unit(sub(pts[1], pts[n - 1])) ?? [1, 0];\n\t\t// (A central difference: already second-order accurate at the seam.)\n\t\treturn fitCubicRun(densify(ring), tol, t, t);\n\t}\n\tconst out: CubicSegment[] = [];\n\tfor (let k = 0; k < corners.length; k++) {\n\t\tconst from = corners[k];\n\t\tconst to = corners[(k + 1) % corners.length];\n\t\tconst run: Point[] = [];\n\t\tfor (let i = from; ; i = (i + 1) % n) {\n\t\t\trun.push(pts[i]);\n\t\t\tif (run.length > 1 && i === to) break;\n\t\t}\n\t\tout.push(...fitCubicRun(densify(run), tol));\n\t}\n\treturn out;\n}\n\n/** Whether a cubic is (within `tol`) the straight line from `p0` to `p3`. */\nexport function isStraightCubic(c: CubicSegment, tol: number): boolean {\n\tconst chord = sub(c.p3, c.p0);\n\tconst len = Math.hypot(chord[0], chord[1]);\n\tif (len < 1e-12) return dist(c.p1, c.p0) <= tol && dist(c.p2, c.p0) <= tol;\n\tconst dir: Vec = [chord[0] / len, chord[1] / len];\n\treturn [c.p1, c.p2].every((h) => {\n\t\tconst v = sub(h, c.p0);\n\t\tconst along = dot(v, dir);\n\t\tconst across = Math.abs(v[0] * dir[1] - v[1] * dir[0]);\n\t\treturn across <= tol && along >= -tol && along <= len + tol;\n\t});\n}\n\nexport interface FitPathDataOptions extends FitCubicsOptions {\n\t/** Fitting tolerance in path units (default 0.5). */\n\ttolerance?: number;\n\t/** Decimal places (default 3). */\n\tprecision?: number;\n\t/** Added to every point before formatting. */\n\toffset?: { x: number; y: number };\n\t/**\n\t * Keep the original polyline when fitting would need more segments than it has edges\n\t * (default `true`), so fitting never makes a path heavier.\n\t */\n\tnoWorse?: boolean;\n}\n\n/** SVG `d` for fitted segments (`L` for straight ones, `C` otherwise). */\nexport function cubicsToPathData(\n\tsegments: readonly CubicSegment[],\n\toptions: { precision?: number; offset?: { x: number; y: number }; closed?: boolean; straightTolerance?: number } = {}\n): string {\n\tif (segments.length === 0) return '';\n\tconst f = (n: number) => formatNumber(n, options.precision ?? 3);\n\tconst dx = options.offset?.x ?? 0;\n\tconst dy = options.offset?.y ?? 0;\n\tconst pt = (p: Point) => `${f(p[0] + dx)} ${f(p[1] + dy)}`;\n\tconst straight = options.straightTolerance ?? 1e-3;\n\tlet d = `M${pt(segments[0].p0)}`;\n\tsegments.forEach((c, i) => {\n\t\tconst last = options.closed && i === segments.length - 1;\n\t\tif (isStraightCubic(c, straight)) {\n\t\t\tif (!last) d += `L${pt(c.p3)}`;\n\t\t} else d += `C${pt(c.p1)} ${pt(c.p2)} ${pt(c.p3)}`;\n\t});\n\treturn options.closed ? `${d}Z` : d;\n}\n\nfunction polylineToPathData(points: readonly Point[], closed: boolean, options: FitPathDataOptions): string {\n\tif (points.length < 2) return '';\n\tconst f = (n: number) => formatNumber(n, options.precision ?? 3);\n\tconst dx = options.offset?.x ?? 0;\n\tconst dy = options.offset?.y ?? 0;\n\tlet d = `M${f(points[0][0] + dx)} ${f(points[0][1] + dy)}`;\n\tfor (let i = 1; i < points.length; i++) d += `L${f(points[i][0] + dx)} ${f(points[i][1] + dy)}`;\n\treturn closed ? `${d}Z` : d;\n}\n\n/**\n * Fits smooth curves to a polygon ring (closed by default) and returns SVG path data with\n * `C` curves for smooth stretches, `L` lines for straight ones and sharp corners kept.\n * Use it for boolean results of curved shapes or to smooth freehand strokes\n * (`{ closed: false }`, see `fitFreehandPath`).\n */\nexport function fitPathData(ring: readonly Point[], options: FitPathDataOptions = {}): string {\n\tconst closed = options.closed ?? true;\n\tconst tolerance = options.tolerance ?? 0.5;\n\tconst pts = dedup(ring);\n\tconst segments = fitCubics(pts, tolerance, { ...options, closed });\n\tif (segments.length === 0) return '';\n\tconst edges = closed ? pts.length : pts.length - 1;\n\tif (options.noWorse !== false) {\n\t\tconst straight = segments.filter((c) => isStraightCubic(c, tolerance * 0.02)).length;\n\t\t// Fitting only pays off when it removes vertices.\n\t\tif (segments.length >= edges && straight === segments.length) return polylineToPathData(pts, closed, options);\n\t\tif (segments.length > edges) return polylineToPathData(pts, closed, options);\n\t}\n\treturn cubicsToPathData(segments, {\n\t\tprecision: options.precision,\n\t\toffset: options.offset,\n\t\tclosed,\n\t\tstraightTolerance: tolerance * 0.02\n\t});\n}\n\n/**\n * Smooths a freehand stroke (pointer samples) into an open SVG path of cubic curves.\n * `tolerance` is the largest distance (in the points' units) a sample may be from the\n * curve (default 1); sharp turns above `cornerAngleDeg` (default 30) stay corners.\n */\nexport function fitFreehandPath(\n\tpoints: readonly Point[],\n\toptions: Omit<FitPathDataOptions, 'closed'> = {}\n): string {\n\treturn fitPathData(points, { tolerance: 1, ...options, closed: false });\n}\n","/**\n * Shape geometry: shape descriptions (rect, rounded rect, ellipse, regular polygon, star and\n * SVG path data) to polygons, SVG path parsing / flattening, and polygons back to path data.\n */\nimport type { Point } from './types.js';\nimport type { MultiPolygon, PolygonFillRule, PolygonRing } from './polygonBoolean.js';\nimport { fitPathData } from './curveFit.js';\n\n// ---------------------------------------------------------------------------\n// Shape descriptions\n// ---------------------------------------------------------------------------\n\nimport type { CanvasGradientDef, SvgGradientDef } from './gradient.js';\nimport type { CanvasBrushstroke } from './brushTypes.js';\nimport { gradientToSvgDef, resolveCanvasGradient } from './gradient.js';\n\n/** Paint shared by every shape kind. Colours are any CSS colour, preset name, or gradient definition. */\n/**\n * A provider effect (see `@pixerate/editor/effects`) drawn on a shape: `fill` paints the shape's\n * inside with the effect (clipped to its outline), `overlay` draws it over the node's box. Kept,\n * and not drawn, without an effects provider.\n */\nexport interface CanvasShapeEffect {\n\t/** The provider's effect id. */\n\teffect: string;\n\tprovider?: string;\n\tname?: string;\n\t/** Control values (over the effect's defaults). */\n\tvalues: Record<string, number | string | boolean | readonly number[]>;\n\tmode: 'fill' | 'overlay';\n\t/** 0–1 (default 1). */\n\topacity?: number;\n\t/** Animated effects play while true (default true); false holds the first frame. */\n\tplaying?: boolean;\n}\n\nexport interface ShapePaint {\n\t/** A provider effect drawn on the shape (see `CanvasShapeEffect`). */\n\teffect?: CanvasShapeEffect;\n\tfill?: string | CanvasGradientDef;\n\tstroke?: string | CanvasGradientDef;\n\tstrokeWidth?: number;\n\topacity?: number;\n\tstrokeLinecap?: 'round' | 'butt' | 'square';\n\tstrokeLinejoin?: 'round' | 'bevel' | 'miter';\n\tfillGradient?: CanvasGradientDef;\n\tstrokeGradient?: CanvasGradientDef;\n}\n\ninterface ShapeBase extends ShapePaint {\n\t/** Clockwise rotation in degrees (on a y-down canvas) about the centre of the node box. */\n\trotation?: number;\n}\n\n/** Rectangle filling the node box, optionally with rounded corners. */\nexport interface RectShape extends ShapeBase {\n\tkind: 'rect';\n\t/** One radius, or `[topLeft, topRight, bottomRight, bottomLeft]`. Clamped to fit. */\n\tcornerRadius?: number | readonly [number, number, number, number];\n}\n\n/** Ellipse (circle when the node is square) inscribed in the node box. */\nexport interface EllipseShape extends ShapeBase {\n\tkind: 'ellipse';\n}\n\n/** Regular polygon, stretched so its bounding box fills the node box. */\nexport interface RegularPolygonShape extends ShapeBase {\n\tkind: 'polygon';\n\t/** Number of sides (at least 3, default 6). The first vertex points up. */\n\tsides?: number;\n}\n\n/** Star, stretched so its bounding box fills the node box. */\nexport interface StarShape extends ShapeBase {\n\tkind: 'star';\n\t/** Number of points (at least 3, default 5). The first point points up. */\n\tpoints?: number;\n\t/** Inner radius as a fraction of the outer radius (default 0.5). */\n\tinnerRadius?: number;\n}\n\n/** Arbitrary SVG path data. */\nexport interface PathShape extends ShapeBase {\n\tkind: 'path';\n\td: string;\n\t/**\n\t * `[minX, minY, width, height]` of the path's coordinate space, scaled to the node box.\n\t * Without it the path coordinates are node-local pixels.\n\t */\n\tviewBox?: readonly [number, number, number, number];\n\t/** Fill rule (default `nonzero`, as in SVG). */\n\tfillRule?: PolygonFillRule;\n\t/**\n\t * Draw the path with a dry paint brush instead of an SVG stroke (a brushed freehand stroke):\n\t * the brush and pen profiles along the path. Rendered by `renderShapeBrushstroke`.\n\t */\n\tbrush?: CanvasBrushstroke;\n}\n\n/**\n * Shape description stored on a node as `data.shape`. Geometry is relative to the node\n * box (`0,0` to `width,height`), so resizing the node resizes the shape.\n */\nexport type ShapeDescription = RectShape | EllipseShape | RegularPolygonShape | StarShape | PathShape;\n\nexport type ShapeKind = ShapeDescription['kind'];\n\nexport const SHAPE_KINDS: readonly ShapeKind[] = ['rect', 'ellipse', 'polygon', 'star', 'path'];\n\n/** Whether a value is a supported shape description. */\nexport function isShapeDescription(value: unknown): value is ShapeDescription {\n\tif (!value || typeof value !== 'object') return false;\n\tconst kind = (value as { kind?: unknown }).kind;\n\tif (!SHAPE_KINDS.includes(kind as ShapeKind)) return false;\n\treturn kind !== 'path' || typeof (value as PathShape).d === 'string';\n}\n\nexport interface ShapeSize {\n\twidth: number;\n\theight: number;\n}\n\nexport interface FlattenOptions {\n\t/** Maximum distance between a curve and its polyline, in output units (default 0.25). */\n\ttolerance?: number;\n\t/** Upper bound on the segments one curve is split into (default 512). */\n\tmaxSegments?: number;\n}\n\n// ---------------------------------------------------------------------------\n// SVG path parsing\n// ---------------------------------------------------------------------------\n\n/** Normalised absolute path command produced by `parseSvgPath`. */\nexport type PathCommand =\n\t| { type: 'M'; x: number; y: number }\n\t| { type: 'L'; x: number; y: number }\n\t| { type: 'C'; x1: number; y1: number; x2: number; y2: number; x: number; y: number }\n\t| { type: 'Q'; x1: number; y1: number; x: number; y: number }\n\t| {\n\t\t\ttype: 'A';\n\t\t\trx: number;\n\t\t\try: number;\n\t\t\trotation: number;\n\t\t\tlargeArc: boolean;\n\t\t\tsweep: boolean;\n\t\t\tx: number;\n\t\t\ty: number;\n\t }\n\t| { type: 'Z' };\n\nconst PARAM_COUNTS: Record<string, number> = { m: 2, l: 2, h: 1, v: 1, c: 6, s: 4, q: 4, t: 2, a: 7, z: 0 };\n\n/** Character scanner for path data (handles `1.5.5`, `1e-3`, `-1-2` and compact arc flags). */\nclass PathScanner {\n\tprivate pos = 0;\n\tconstructor(private readonly text: string) {}\n\n\tprivate skip() {\n\t\twhile (this.pos < this.text.length && /[\\s,]/.test(this.text[this.pos])) this.pos++;\n\t}\n\n\t/** The next command letter, or `null` when a number (or the end) follows. */\n\tcommand(): string | null {\n\t\tthis.skip();\n\t\tconst ch = this.text[this.pos];\n\t\tif (ch && /[MmLlHhVvCcSsQqTtAaZz]/.test(ch)) {\n\t\t\tthis.pos++;\n\t\t\treturn ch;\n\t\t}\n\t\treturn null;\n\t}\n\n\tdone(): boolean {\n\t\tthis.skip();\n\t\treturn this.pos >= this.text.length;\n\t}\n\n\tnumber(): number | null {\n\t\tthis.skip();\n\t\tconst match = /^[+-]?(?:\\d+\\.?\\d*|\\.\\d+)(?:[eE][+-]?\\d+)?/.exec(this.text.slice(this.pos, this.pos + 64));\n\t\tif (!match) return null;\n\t\tthis.pos += match[0].length;\n\t\tconst value = Number(match[0]);\n\t\treturn Number.isFinite(value) ? value : null;\n\t}\n\n\tflag(): number | null {\n\t\tthis.skip();\n\t\tconst ch = this.text[this.pos];\n\t\tif (ch === '0' || ch === '1') {\n\t\t\tthis.pos++;\n\t\t\treturn ch === '1' ? 1 : 0;\n\t\t}\n\t\treturn null;\n\t}\n}\n\n/**\n * Parses SVG path data into absolute `M`, `L`, `C`, `Q`, `A` and `Z` commands. Relative\n * commands, `H` / `V`, smooth curves (`S` / `T`) and implicit repeated commands are\n * normalised. Parsing stops at the first malformed command (as browsers do).\n */\nexport function parseSvgPath(d: string): PathCommand[] {\n\tconst scanner = new PathScanner(d ?? '');\n\tconst commands: PathCommand[] = [];\n\tlet cx = 0;\n\tlet cy = 0;\n\tlet startX = 0;\n\tlet startY = 0;\n\tlet lastControl: { x: number; y: number; type: 'C' | 'Q' } | null = null;\n\tlet command = '';\n\n\twhile (!scanner.done()) {\n\t\tconst letter = scanner.command();\n\t\tif (letter) {\n\t\t\tcommand = letter;\n\t\t\tif (command === 'z' || command === 'Z') {\n\t\t\t\tcommands.push({ type: 'Z' });\n\t\t\t\tcx = startX;\n\t\t\t\tcy = startY;\n\t\t\t\tlastControl = null;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t} else if (!command || command === 'z' || command === 'Z') {\n\t\t\tbreak;\n\t\t}\n\t\tconst lower = command.toLowerCase();\n\t\tconst count = PARAM_COUNTS[lower];\n\t\tconst args: number[] = [];\n\t\tfor (let k = 0; k < count; k++) {\n\t\t\tconst value = lower === 'a' && (k === 3 || k === 4) ? scanner.flag() : scanner.number();\n\t\t\tif (value === null) return commands;\n\t\t\targs.push(value);\n\t\t}\n\t\tconst rel = command !== command.toUpperCase();\n\t\tconst ox = rel ? cx : 0;\n\t\tconst oy = rel ? cy : 0;\n\t\tswitch (lower) {\n\t\t\tcase 'm': {\n\t\t\t\tcx = args[0] + ox;\n\t\t\t\tcy = args[1] + oy;\n\t\t\t\tstartX = cx;\n\t\t\t\tstartY = cy;\n\t\t\t\tcommands.push({ type: 'M', x: cx, y: cy });\n\t\t\t\tlastControl = null;\n\t\t\t\t// Extra coordinate pairs after a moveto are implicit linetos.\n\t\t\t\tcommand = rel ? 'l' : 'L';\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'l':\n\t\t\t\tcx = args[0] + ox;\n\t\t\t\tcy = args[1] + oy;\n\t\t\t\tcommands.push({ type: 'L', x: cx, y: cy });\n\t\t\t\tlastControl = null;\n\t\t\t\tbreak;\n\t\t\tcase 'h':\n\t\t\t\tcx = args[0] + (rel ? cx : 0);\n\t\t\t\tcommands.push({ type: 'L', x: cx, y: cy });\n\t\t\t\tlastControl = null;\n\t\t\t\tbreak;\n\t\t\tcase 'v':\n\t\t\t\tcy = args[0] + (rel ? cy : 0);\n\t\t\t\tcommands.push({ type: 'L', x: cx, y: cy });\n\t\t\t\tlastControl = null;\n\t\t\t\tbreak;\n\t\t\tcase 'c': {\n\t\t\t\tconst c: PathCommand = {\n\t\t\t\t\ttype: 'C',\n\t\t\t\t\tx1: args[0] + ox,\n\t\t\t\t\ty1: args[1] + oy,\n\t\t\t\t\tx2: args[2] + ox,\n\t\t\t\t\ty2: args[3] + oy,\n\t\t\t\t\tx: args[4] + ox,\n\t\t\t\t\ty: args[5] + oy\n\t\t\t\t};\n\t\t\t\tcommands.push(c);\n\t\t\t\tlastControl = { x: c.x2, y: c.y2, type: 'C' };\n\t\t\t\tcx = c.x;\n\t\t\t\tcy = c.y;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 's': {\n\t\t\t\tconst x1: number = lastControl?.type === 'C' ? 2 * cx - lastControl.x : cx;\n\t\t\t\tconst y1: number = lastControl?.type === 'C' ? 2 * cy - lastControl.y : cy;\n\t\t\t\tconst c: PathCommand = {\n\t\t\t\t\ttype: 'C',\n\t\t\t\t\tx1,\n\t\t\t\t\ty1,\n\t\t\t\t\tx2: args[0] + ox,\n\t\t\t\t\ty2: args[1] + oy,\n\t\t\t\t\tx: args[2] + ox,\n\t\t\t\t\ty: args[3] + oy\n\t\t\t\t};\n\t\t\t\tcommands.push(c);\n\t\t\t\tlastControl = { x: c.x2, y: c.y2, type: 'C' };\n\t\t\t\tcx = c.x;\n\t\t\t\tcy = c.y;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'q': {\n\t\t\t\tconst c: PathCommand = { type: 'Q', x1: args[0] + ox, y1: args[1] + oy, x: args[2] + ox, y: args[3] + oy };\n\t\t\t\tcommands.push(c);\n\t\t\t\tlastControl = { x: c.x1, y: c.y1, type: 'Q' };\n\t\t\t\tcx = c.x;\n\t\t\t\tcy = c.y;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 't': {\n\t\t\t\tconst x1: number = lastControl?.type === 'Q' ? 2 * cx - lastControl.x : cx;\n\t\t\t\tconst y1: number = lastControl?.type === 'Q' ? 2 * cy - lastControl.y : cy;\n\t\t\t\tconst c: PathCommand = { type: 'Q', x1, y1, x: args[0] + ox, y: args[1] + oy };\n\t\t\t\tcommands.push(c);\n\t\t\t\tlastControl = { x: x1, y: y1, type: 'Q' };\n\t\t\t\tcx = c.x;\n\t\t\t\tcy = c.y;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'a': {\n\t\t\t\tconst c: PathCommand = {\n\t\t\t\t\ttype: 'A',\n\t\t\t\t\trx: Math.abs(args[0]),\n\t\t\t\t\try: Math.abs(args[1]),\n\t\t\t\t\trotation: args[2],\n\t\t\t\t\tlargeArc: args[3] !== 0,\n\t\t\t\t\tsweep: args[4] !== 0,\n\t\t\t\t\tx: args[5] + ox,\n\t\t\t\t\ty: args[6] + oy\n\t\t\t\t};\n\t\t\t\tcommands.push(c);\n\t\t\t\tlastControl = null;\n\t\t\t\tcx = c.x;\n\t\t\t\tcy = c.y;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn commands;\n}\n\n// ---------------------------------------------------------------------------\n// Curve flattening\n// ---------------------------------------------------------------------------\n\nfunction segmentCount(curvature: number, tolerance: number, max: number): number {\n\tif (!(curvature > 0)) return 1;\n\treturn Math.max(1, Math.min(max, Math.ceil(Math.sqrt(curvature / tolerance))));\n}\n\nfunction flattenCubic(\n\tout: Point[],\n\tp0: Point,\n\tx1: number,\n\ty1: number,\n\tx2: number,\n\ty2: number,\n\tx: number,\n\ty: number,\n\ttolerance: number,\n\tmax: number\n) {\n\t// Uniform subdivision error <= max|B''| / (8 n²) with |B''| <= 6 * max second difference.\n\tconst dd = Math.max(\n\t\tMath.hypot(p0[0] - 2 * x1 + x2, p0[1] - 2 * y1 + y2),\n\t\tMath.hypot(x1 - 2 * x2 + x, y1 - 2 * y2 + y)\n\t);\n\tconst n = segmentCount((6 * dd) / 8, tolerance, max);\n\tfor (let k = 1; k <= n; k++) {\n\t\tconst t = k / n;\n\t\tconst mt = 1 - t;\n\t\tconst a = mt * mt * mt;\n\t\tconst b = 3 * mt * mt * t;\n\t\tconst c = 3 * mt * t * t;\n\t\tconst e = t * t * t;\n\t\tout.push([a * p0[0] + b * x1 + c * x2 + e * x, a * p0[1] + b * y1 + c * y2 + e * y]);\n\t}\n}\n\nfunction flattenQuadratic(\n\tout: Point[],\n\tp0: Point,\n\tx1: number,\n\ty1: number,\n\tx: number,\n\ty: number,\n\ttolerance: number,\n\tmax: number\n) {\n\tconst dd = Math.hypot(p0[0] - 2 * x1 + x, p0[1] - 2 * y1 + y);\n\tconst n = segmentCount((2 * dd) / 8, tolerance, max);\n\tfor (let k = 1; k <= n; k++) {\n\t\tconst t = k / n;\n\t\tconst mt = 1 - t;\n\t\tout.push([mt * mt * p0[0] + 2 * mt * t * x1 + t * t * x, mt * mt * p0[1] + 2 * mt * t * y1 + t * t * y]);\n\t}\n}\n\nfunction arcSteps(radius: number, sweep: number, tolerance: number, max: number): number {\n\tif (radius <= tolerance) return Math.max(1, Math.ceil(Math.abs(sweep) / (Math.PI / 2)));\n\tconst step = 2 * Math.acos(1 - tolerance / radius);\n\treturn Math.max(1, Math.min(max, Math.ceil(Math.abs(sweep) / step)));\n}\n\n/** Flattens an SVG elliptical arc (endpoint parameterisation, SVG 1.1 F.6.5). */\nfunction flattenArc(\n\tout: Point[],\n\tp0: Point,\n\tcmd: Extract<PathCommand, { type: 'A' }>,\n\ttolerance: number,\n\tmax: number\n) {\n\tconst [x0, y0] = p0;\n\tlet { rx, ry } = cmd;\n\tconst { x, y } = cmd;\n\tif (x0 === x && y0 === y) return;\n\tif (rx === 0 || ry === 0) {\n\t\tout.push([x, y]);\n\t\treturn;\n\t}\n\tconst phi = (cmd.rotation * Math.PI) / 180;\n\tconst cos = Math.cos(phi);\n\tconst sin = Math.sin(phi);\n\tconst dx = (x0 - x) / 2;\n\tconst dy = (y0 - y) / 2;\n\tconst x1p = cos * dx + sin * dy;\n\tconst y1p = -sin * dx + cos * dy;\n\tconst lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);\n\tif (lambda > 1) {\n\t\tconst s = Math.sqrt(lambda);\n\t\trx *= s;\n\t\try *= s;\n\t}\n\tconst num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p;\n\tconst den = rx * rx * y1p * y1p + ry * ry * x1p * x1p;\n\tlet coef = den === 0 ? 0 : Math.sqrt(Math.max(0, num / den));\n\tif (cmd.largeArc === cmd.sweep) coef = -coef;\n\tconst cxp = (coef * rx * y1p) / ry;\n\tconst cyp = (-coef * ry * x1p) / rx;\n\tconst cx = cos * cxp - sin * cyp + (x0 + x) / 2;\n\tconst cy = sin * cxp + cos * cyp + (y0 + y) / 2;\n\tconst angle = (ux: number, uy: number, vx: number, vy: number) => {\n\t\tconst a = Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy);\n\t\treturn a;\n\t};\n\tconst theta1 = angle(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry);\n\tlet delta = angle((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry);\n\tif (!cmd.sweep && delta > 0) delta -= 2 * Math.PI;\n\telse if (cmd.sweep && delta < 0) delta += 2 * Math.PI;\n\tconst n = arcSteps(Math.max(rx, ry), delta, tolerance, max);\n\tfor (let k = 1; k < n; k++) {\n\t\tconst t = theta1 + (delta * k) / n;\n\t\tconst ex = rx * Math.cos(t);\n\t\tconst ey = ry * Math.sin(t);\n\t\tout.push([cos * ex - sin * ey + cx, sin * ex + cos * ey + cy]);\n\t}\n\tout.push([x, y]);\n}\n\n/**\n * Flattens SVG path data into closed rings (one per subpath; open subpaths are closed the\n * way SVG fills them). Curves are approximated within `tolerance`.\n */\nexport function flattenSvgPath(d: string | PathCommand[], options: FlattenOptions = {}): PolygonRing[] {\n\tconst tolerance = options.tolerance && options.tolerance > 0 ? options.tolerance : 0.25;\n\tconst max = options.maxSegments ?? 512;\n\tconst commands = typeof d === 'string' ? parseSvgPath(d) : d;\n\tconst rings: PolygonRing[] = [];\n\tlet current: Point[] = [];\n\tlet start: Point = [0, 0];\n\tconst flush = () => {\n\t\tif (current.length >= 3) rings.push(current);\n\t\tcurrent = [];\n\t};\n\tconst last = (): Point => current[current.length - 1] ?? start;\n\tfor (const cmd of commands) {\n\t\tswitch (cmd.type) {\n\t\t\tcase 'M':\n\t\t\t\tflush();\n\t\t\t\tstart = [cmd.x, cmd.y];\n\t\t\t\tcurrent = [start];\n\t\t\t\tbreak;\n\t\t\tcase 'L':\n\t\t\t\tif (current.length === 0) current = [start];\n\t\t\t\tcurrent.push([cmd.x, cmd.y]);\n\t\t\t\tbreak;\n\t\t\tcase 'C':\n\t\t\t\tif (current.length === 0) current = [start];\n\t\t\t\tflattenCubic(current, last(), cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y, tolerance, max);\n\t\t\t\tbreak;\n\t\t\tcase 'Q':\n\t\t\t\tif (current.length === 0) current = [start];\n\t\t\t\tflattenQuadratic(current, last(), cmd.x1, cmd.y1, cmd.x, cmd.y, tolerance, max);\n\t\t\t\tbreak;\n\t\t\tcase 'A':\n\t\t\t\tif (current.length === 0) current = [start];\n\t\t\t\tflattenArc(current, last(), cmd, tolerance, max);\n\t\t\t\tbreak;\n\t\t\tcase 'Z':\n\t\t\t\tflush();\n\t\t\t\t// A command after Z without a moveto starts at the subpath start.\n\t\t\t\tbreak;\n\t\t}\n\t}\n\tflush();\n\treturn rings.map(dedupeRing).filter((r) => r.length >= 3);\n}\n\nfunction dedupeRing(ring: Point[]): Point[] {\n\tconst out: Point[] = [];\n\tfor (const p of ring) {\n\t\tconst prev = out[out.length - 1];\n\t\tif (!prev || prev[0] !== p[0] || prev[1] !== p[1]) out.push(p);\n\t}\n\twhile (out.length > 1 && out[0][0] === out[out.length - 1][0] && out[0][1] === out[out.length - 1][1]) out.pop();\n\treturn out;\n}\n\n// ---------------------------------------------------------------------------\n// Shapes to polygons\n// ---------------------------------------------------------------------------\n\nfunction cornerRadii(shape: RectShape, width: number, height: number): [number, number, number, number] {\n\tconst raw = shape.cornerRadius ?? 0;\n\tlet radii = (typeof raw === 'number' ? [raw, raw, raw, raw] : [...raw]).map((r) =>\n\t\tNumber.isFinite(r) && r > 0 ? r : 0\n\t) as [number, number, number, number];\n\t// Scale all radii down together when adjacent corners would overlap (CSS rule).\n\tconst factor = Math.min(\n\t\t1,\n\t\twidth / Math.max(radii[0] + radii[1], 1e-12),\n\t\theight / Math.max(radii[1] + radii[2], 1e-12),\n\t\twidth / Math.max(radii[2] + radii[3], 1e-12),\n\t\theight / Math.max(radii[3] + radii[0], 1e-12)\n\t);\n\tif (factor < 1) radii = radii.map((r) => r * factor) as [number, number, number, number];\n\treturn radii;\n}\n\n/** Unit vertices of a regular polygon / star, stretched to fill the box. */\nfunction polygonVertices(count: number, inner: number | null, width: number, height: number): Point[] {\n\tconst raw: Point[] = [];\n\tconst total = inner === null ? count : count * 2;\n\tfor (let k = 0; k < total; k++) {\n\t\tconst angle = -Math.PI / 2 + (k * 2 * Math.PI) / total;\n\t\tconst r = inner !== null && k % 2 === 1 ? inner : 1;\n\t\traw.push([r * Math.cos(angle), r * Math.sin(angle)]);\n\t}\n\tlet minX = Infinity;\n\tlet minY = Infinity;\n\tlet maxX = -Infinity;\n\tlet maxY = -Infinity;\n\tfor (const [x, y] of raw) {\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\tconst sx = width / (maxX - minX || 1);\n\tconst sy = height / (maxY - minY || 1);\n\treturn raw.map(([x, y]) => [(x - minX) * sx, (y - minY) * sy]);\n}\n\nfunction rotationTransform(shape: ShapeDescription, size: ShapeSize): ((p: Point) => Point) | null {\n\tconst deg = shape.rotation ?? 0;\n\tif (!deg || !Number.isFinite(deg)) return null;\n\tconst rad = (deg * Math.PI) / 180;\n\tconst cos = Math.cos(rad);\n\tconst sin = Math.sin(rad);\n\tconst cx = size.width / 2;\n\tconst cy = size.height / 2;\n\treturn ([x, y]) => [cx + (x - cx) * cos - (y - cy) * sin, cy + (x - cx) * sin + (y - cy) * cos];\n}\n\n/**\n * SVG path data for a shape in node-local pixels (exact curves: arcs for rounded corners\n * and ellipses), plus the fill rule and a `transform` for rotation / path view boxes.\n * Use it to render a shape; use `shapeToPolygon` for geometry.\n */\nexport function getShapeSvg(\n\tshape: ShapeDescription,\n\tsize: ShapeSize\n): { d: string; transform?: string; fillRule: PolygonFillRule } {\n\tconst { width: w, height: h } = size;\n\tconst f = (n: number) => formatNumber(n, 3);\n\tconst transforms: string[] = [];\n\tif (shape.rotation) transforms.push(`rotate(${f(shape.rotation)} ${f(w / 2)} ${f(h / 2)})`);\n\tlet d = '';\n\tlet fillRule: PolygonFillRule = 'nonzero';\n\tswitch (shape.kind) {\n\t\tcase 'rect': {\n\t\t\tconst [tl, tr, br, bl] = cornerRadii(shape, w, h);\n\t\t\tif (tl + tr + br + bl === 0) {\n\t\t\t\td = `M0 0H${f(w)}V${f(h)}H0Z`;\n\t\t\t} else {\n\t\t\t\tconst arc = (r: number, x: number, y: number) => (r > 0 ? `A${f(r)} ${f(r)} 0 0 1 ${f(x)} ${f(y)}` : '');\n\t\t\t\td =\n\t\t\t\t\t`M${f(tl)} 0H${f(w - tr)}${arc(tr, w, tr)}V${f(h - br)}${arc(br, w - br, h)}` +\n\t\t\t\t\t`H${f(bl)}${arc(bl, 0, h - bl)}V${f(tl)}${arc(tl, tl, 0)}Z`;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'ellipse': {\n\t\t\tconst rx = w / 2;\n\t\t\tconst ry = h / 2;\n\t\t\td = `M0 ${f(ry)}A${f(rx)} ${f(ry)} 0 1 1 ${f(w)} ${f(ry)}A${f(rx)} ${f(ry)} 0 1 1 0 ${f(ry)}Z`;\n\t\t\tbreak;\n\t\t}\n\t\tcase 'polygon':\n\t\tcase 'star': {\n\t\t\tconst points =\n\t\t\t\tshape.kind === 'polygon'\n\t\t\t\t\t? polygonVertices(Math.max(3, Math.floor(shape.sides ?? 6)), null, w, h)\n\t\t\t\t\t: polygonVertices(Math.max(3, Math.floor(shape.points ?? 5)), clampRatio(shape.innerRadius), w, h);\n\t\t\td = ringsToPath([points], f);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'path': {\n\t\t\td = shape.d;\n\t\t\tfillRule = shape.fillRule ?? 'nonzero';\n\t\t\tconst vb = validViewBox(shape.viewBox);\n\t\t\tif (vb) {\n\t\t\t\ttransforms.push(\n\t\t\t\t\t`scale(${f(w / vb[2])} ${f(h / vb[3])})`,\n\t\t\t\t\t`translate(${f(-vb[0])} ${f(-vb[1])})`\n\t\t\t\t);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn transforms.length > 0 ? { d, transform: transforms.join(' '), fillRule } : { d, fillRule };\n}\n\n/** Everything a renderer needs to draw a shape as one SVG `<path>`. */\nexport interface ShapeRenderData {\n\t/** SVG `viewBox` (`0 0 width height`): node-local pixels. */\n\tviewBox: string;\n\twidth: number;\n\theight: number;\n\td: string;\n\ttransform?: string;\n\tfillRule: PolygonFillRule;\n\tfill: string;\n\tstroke: string;\n\tstrokeWidth: number;\n\topacity?: number;\n\tstrokeLinecap?: 'round' | 'butt' | 'square';\n\tstrokeLinejoin?: 'round' | 'bevel' | 'miter';\n\t/** Gradient def for the fill, when fill uses a gradient. */\n\tfillGradient?: SvgGradientDef;\n\t/** Gradient def for the stroke, when stroke uses a gradient. */\n\tstrokeGradient?: SvgGradientDef;\n}\n\nexport interface GetShapeRenderDataOptions {\n\t/** Unique ID suffix or base ID used when generating SVG gradient IDs (default: auto random). */\n\tid?: string;\n}\n\n/**\n * Resolves the SVG drawing of a shape for a node size. Without a size, a path's view box\n * size (or 100x100) is used. Paint defaults: `fill: currentColor`, `stroke: none`,\n * `strokeWidth: 1`. Supports solid colors, CSS gradients, presets, and CanvasGradientDef.\n */\nexport function getShapeRenderData(\n\tshape: ShapeDescription,\n\tsize: Partial<ShapeSize> = {},\n\toptions: GetShapeRenderDataOptions = {}\n): ShapeRenderData {\n\tconst vb = shape.kind === 'path' ? validViewBox(shape.viewBox) : null;\n\tconst width = size.width && size.width > 0 ? size.width : vb ? vb[2] : 100;\n\tconst height = size.height && size.height > 0 ? size.height : vb ? vb[3] : 100;\n\tconst svg = getShapeSvg(shape, { width, height });\n\n\tconst baseId = options.id || Math.random().toString(36).slice(2, 9);\n\n\t// Resolve fill (gradient or solid)\n\tlet fillStr = 'currentColor';\n\tlet fillGradientDef: SvgGradientDef | undefined;\n\tconst rawFill = shape.fillGradient ?? shape.fill;\n\tconst resolvedFillGradient = resolveCanvasGradient(rawFill);\n\tif (resolvedFillGradient) {\n\t\tconst gradId = `shape-fill-${baseId}`;\n\t\tfillGradientDef = gradientToSvgDef(resolvedFillGradient, gradId);\n\t\tfillStr = `url(#${gradId})`;\n\t} else if (typeof shape.fill === 'string') {\n\t\tfillStr = shape.fill;\n\t} else if (shape.fill === undefined) {\n\t\tfillStr = 'currentColor';\n\t}\n\n\t// Resolve stroke (gradient or solid)\n\tlet strokeStr = 'none';\n\tlet strokeGradientDef: SvgGradientDef | undefined;\n\tconst rawStroke = shape.strokeGradient ?? shape.stroke;\n\tconst resolvedStrokeGradient = resolveCanvasGradient(rawStroke);\n\tif (resolvedStrokeGradient) {\n\t\tconst gradId = `shape-stroke-${baseId}`;\n\t\tstrokeGradientDef = gradientToSvgDef(resolvedStrokeGradient, gradId);\n\t\tstrokeStr = `url(#${gradId})`;\n\t} else if (typeof shape.stroke === 'string') {\n\t\tstrokeStr = shape.stroke;\n\t} else if (shape.stroke === undefined) {\n\t\tstrokeStr = 'none';\n\t}\n\n\tconst data: ShapeRenderData = {\n\t\tviewBox: `0 0 ${formatNumber(width, 3)} ${formatNumber(height, 3)}`,\n\t\twidth,\n\t\theight,\n\t\td: svg.d,\n\t\tfillRule: svg.fillRule,\n\t\tfill: fillStr,\n\t\tstroke: strokeStr,\n\t\tstrokeWidth: shape.strokeWidth ?? 1\n\t};\n\tif (svg.transform) data.transform = svg.transform;\n\tif (shape.opacity !== undefined) data.opacity = shape.opacity;\n\tif (shape.strokeLinecap) data.strokeLinecap = shape.strokeLinecap;\n\tif (shape.strokeLinejoin) data.strokeLinejoin = shape.strokeLinejoin;\n\tif (fillGradientDef) data.fillGradient = fillGradientDef;\n\tif (strokeGradientDef) data.strokeGradient = strokeGradientDef;\n\treturn data;\n}\n\nfunction clampRatio(value: number | undefined): number {\n\tif (value === undefined || !Number.isFinite(value)) return 0.5;\n\treturn Math.min(1, Math.max(0.01, value));\n}\n\nfunction validViewBox(vb: PathShape['viewBox']): readonly [number, number, number, number] | null {\n\tif (!vb || vb.length !== 4 || !vb.every(Number.isFinite) || vb[2] <= 0 || vb[3] <= 0) return null;\n\treturn vb;\n}\n\n/**\n * Converts a shape to rings in node-local pixels (rotation applied), flattening curves at\n * `tolerance`. Returns the rings with the fill rule they must be read with.\n */\nexport function shapeToPolygon(\n\tshape: ShapeDescription,\n\tsize: ShapeSize,\n\toptions: FlattenOptions = {}\n): { rings: PolygonRing[]; fillRule: PolygonFillRule } {\n\tconst { width: w, height: h } = size;\n\tif (!(w > 0) || !(h > 0)) return { rings: [], fillRule: 'nonzero' };\n\tlet rings: PolygonRing[];\n\tlet fillRule: PolygonFillRule = 'nonzero';\n\tif (shape.kind === 'path') {\n\t\tfillRule = shape.fillRule ?? 'nonzero';\n\t\tconst vb = validViewBox(shape.viewBox);\n\t\tif (vb) {\n\t\t\tconst sx = w / vb[2];\n\t\t\tconst sy = h / vb[3];\n\t\t\t// Flatten in path units with the tolerance scaled to stay within `tolerance` px.\n\t\t\tconst tolerance = (options.tolerance ?? 0.25) / Math.max(sx, sy);\n\t\t\trings = flattenSvgPath(shape.d, { ...options, tolerance }).map((ring) =>\n\t\t\t\tring.map(([x, y]) => [(x - vb[0]) * sx, (y - vb[1]) * sy] as Point)\n\t\t\t);\n\t\t} else {\n\t\t\trings = flattenSvgPath(shape.d, options);\n\t\t}\n\t} else {\n\t\tconst { d } = getShapeSvg({ ...shape, rotation: 0 }, size);\n\t\trings = flattenSvgPath(d, options);\n\t}\n\tconst rotate = rotationTransform(shape, size);\n\tif (rotate) rings = rings.map((ring) => ring.map(rotate));\n\treturn { rings, fillRule };\n}\n\n// ---------------------------------------------------------------------------\n// Polygons to path data\n// ---------------------------------------------------------------------------\n\n/** Formats a number with at most `precision` decimals, without trailing zeros. */\nexport function formatNumber(value: number, precision = 3): string {\n\tconst factor = 10 ** precision;\n\tconst rounded = Math.round(value * factor) / factor;\n\treturn Object.is(rounded, -0) ? '0' : String(rounded);\n}\n\nfunction ringsToPath(rings: readonly (readonly Point[])[], f: (n: number) => string): string {\n\tlet d = '';\n\tfor (const ring of rings) {\n\t\tif (ring.length < 2) continue;\n\t\td += `M${f(ring[0][0])} ${f(ring[0][1])}`;\n\t\tfor (let i = 1; i < ring.length; i++) d += `L${f(ring[i][0])} ${f(ring[i][1])}`;\n\t\td += 'Z';\n\t}\n\treturn d;\n}\n\n/** Perpendicular distance from `p` to the segment `a`–`b`. */\nfunction segmentDistance(p: Point, a: Point, b: Point): number {\n\tconst dx = b[0] - a[0];\n\tconst dy = b[1] - a[1];\n\tconst len2 = dx * dx + dy * dy;\n\tif (len2 === 0) return Math.hypot(p[0] - a[0], p[1] - a[1]);\n\tconst t = Math.max(0, Math.min(1, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / len2));\n\treturn Math.hypot(p[0] - (a[0] + t * dx), p[1] - (a[1] + t * dy));\n}\n\nfunction rdp(points: Point[], tolerance: number): Point[] {\n\tif (points.length <= 2) return points;\n\tconst keep = new Uint8Array(points.length);\n\tkeep[0] = 1;\n\tkeep[points.length - 1] = 1;\n\tconst stack: [number, number][] = [[0, points.length - 1]];\n\twhile (stack.length) {\n\t\tconst [s, e] = stack.pop()!;\n\t\tlet maxDist = -1;\n\t\tlet index = -1;\n\t\tfor (let i = s + 1; i < e; i++) {\n\t\t\tconst dist = segmentDistance(points[i], points[s], points[e]);\n\t\t\tif (dist > maxDist) {\n\t\t\t\tmaxDist = dist;\n\t\t\t\tindex = i;\n\t\t\t}\n\t\t}\n\t\tif (index !== -1 && maxDist > tolerance) {\n\t\t\tkeep[index] = 1;\n\t\t\tstack.push([s, index], [index, e]);\n\t\t}\n\t}\n\treturn points.filter((_, i) => keep[i]);\n}\n\n/**\n * Simplifies a closed ring with Ramer–Douglas–Peucker at `tolerance`. Returns an empty\n * ring when fewer than three points survive.\n */\nexport function simplifyRing(ring: readonly Point[], tolerance: number): Point[] {\n\tif (ring.length <= 3 || !(tolerance > 0)) return [...ring];\n\t// Anchor on the point farthest from the first one so the closing seam is not lost.\n\tlet far = 0;\n\tlet farDist = -1;\n\tfor (let i = 1; i < ring.length; i++) {\n\t\tconst dist = Math.hypot(ring[i][0] - ring[0][0], ring[i][1] - ring[0][1]);\n\t\tif (dist > farDist) {\n\t\t\tfarDist = dist;\n\t\t\tfar = i;\n\t\t}\n\t}\n\tconst first = rdp(ring.slice(0, far + 1) as Point[], tolerance);\n\tconst second = rdp([...ring.slice(far), ring[0]] as Point[], tolerance);\n\tconst out = [...first.slice(0, -1), ...second.slice(0, -1)];\n\treturn out.length >= 3 ? out : [];\n}\n\nexport interface PolygonToPathOptions {\n\t/** Decimal places in the output (default 3). */\n\tprecision?: number;\n\t/** Ramer–Douglas–Peucker tolerance; `0` (default) keeps every vertex. */\n\tsimplify?: number;\n\t/** Added to every point before formatting (e.g. to make coordinates node-local). */\n\toffset?: { x: number; y: number };\n\t/**\n\t * `'lines'` (default) writes every ring as `M`/`L`/`Z`. `'fit'` fits cubic Béziers to each\n\t * ring (`fitPathData`), so flattened curves come back as smooth `C` curves while sharp\n\t * corners (turning more than `cornerAngleDeg`) and straight edges stay as they are.\n\t */\n\tcurves?: 'lines' | 'fit';\n\t/** Curve-fitting tolerance in path units for `curves: 'fit'` (default 0.25). */\n\tcurveTolerance?: number;\n\t/** Corner threshold in degrees for `curves: 'fit'` (default 30). */\n\tcornerAngleDeg?: number;\n}\n\n/**\n * Converts a multi-polygon (or a list of rings) to SVG path data using `M`/`L`/`Z`. Holes\n * keep their opposite orientation, so the path fills correctly with either fill rule.\n */\nexport function polygonToSvgPath(input: MultiPolygon | PolygonRing[], options: PolygonToPathOptions = {}): string {\n\tconst precision = options.precision ?? 3;\n\tconst f = (n: number) => formatNumber(n, precision);\n\tconst dx = options.offset?.x ?? 0;\n\tconst dy = options.offset?.y ?? 0;\n\tconst rings: Point[][] = [];\n\tconst fit = options.curves === 'fit';\n\tlet fitted = '';\n\tfor (const item of input as any[]) {\n\t\tconst list: Point[][] =\n\t\t\titem.length > 0 && Array.isArray(item[0]) && Array.isArray(item[0][0]) ? item : [item];\n\t\tfor (const ring of list) {\n\t\t\tlet r = ring;\n\t\t\tif (options.simplify && options.simplify > 0) r = simplifyRing(r, options.simplify);\n\t\t\tif (r.length < 3) continue;\n\t\t\tif (fit) {\n\t\t\t\tfitted += fitPathData(r, {\n\t\t\t\t\ttolerance: options.curveTolerance ?? 0.25,\n\t\t\t\t\tcornerAngleDeg: options.cornerAngleDeg,\n\t\t\t\t\tprecision,\n\t\t\t\t\toffset: { x: dx, y: dy }\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\trings.push(dx || dy ? r.map(([x, y]) => [x + dx, y + dy] as Point) : r);\n\t\t}\n\t}\n\treturn fit ? fitted : ringsToPath(rings, f);\n}\n"],"mappings":";AAwCO,IAAM,0BAAgD;AAAA,EAC5D,MAAM;AAAA,EACN,OAAO;AAAA,EACP,OAAO;AAAA,IACN,EAAE,QAAQ,GAAG,OAAO,UAAU;AAAA,IAC9B,EAAE,QAAQ,GAAG,OAAO,UAAU;AAAA,EAC/B;AACD;AAEO,IAAM,0BAAgE;AAAA,EAC5E,UAAU;AAAA,EACV,QAAQ;AAAA,IACP,MAAM;AAAA,IACN,OAAO;AAAA,IACP,OAAO;AAAA,MACN,EAAE,QAAQ,GAAG,OAAO,UAAU;AAAA,MAC9B,EAAE,QAAQ,GAAG,OAAO,UAAU;AAAA,IAC/B;AAAA,EACD;AAAA,EACA,OAAO;AAAA,IACN,MAAM;AAA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