@moondraft/import 0.0.0-stage → 0.2.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 (337) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/LICENSE +34 -0
  3. package/README.md +36 -2
  4. package/SOURCE.md +394 -0
  5. package/dist/adapter/convert.d.ts +144 -0
  6. package/dist/adapter/convert.js +2811 -0
  7. package/dist/adapter/figma-descriptions.d.ts +7 -0
  8. package/dist/adapter/figma-descriptions.js +34 -0
  9. package/dist/adapter/figma-grids.d.ts +12 -0
  10. package/dist/adapter/figma-grids.js +175 -0
  11. package/dist/adapter/figma-handoff.d.ts +12 -0
  12. package/dist/adapter/figma-handoff.js +167 -0
  13. package/dist/adapter/figma-hyperlinks.d.ts +13 -0
  14. package/dist/adapter/figma-hyperlinks.js +77 -0
  15. package/dist/adapter/figma.d.ts +12 -0
  16. package/dist/adapter/figma.js +40 -0
  17. package/dist/adapter/file-components.d.ts +20 -0
  18. package/dist/adapter/file-components.js +352 -0
  19. package/dist/adapter/file-resources.d.ts +29 -0
  20. package/dist/adapter/file-resources.js +851 -0
  21. package/dist/adapter/image-crop.d.ts +18 -0
  22. package/dist/adapter/image-crop.js +30 -0
  23. package/dist/adapter/index.d.ts +6 -0
  24. package/dist/adapter/index.js +9 -0
  25. package/dist/adapter/link.d.ts +49 -0
  26. package/dist/adapter/link.js +892 -0
  27. package/dist/adapter/payload.d.ts +31 -0
  28. package/dist/adapter/payload.js +78 -0
  29. package/dist/adapter/shapes.d.ts +31 -0
  30. package/dist/adapter/shapes.js +75 -0
  31. package/dist/adapter/variables.d.ts +45 -0
  32. package/dist/adapter/variables.js +106 -0
  33. package/dist/figma-file.d.ts +38 -0
  34. package/dist/figma-file.js +97 -0
  35. package/dist/figma-worker.d.ts +11 -0
  36. package/dist/figma-worker.js +12 -0
  37. package/dist/figma.d.ts +26 -0
  38. package/dist/figma.js +230 -0
  39. package/dist/index.d.ts +29 -0
  40. package/dist/index.js +50 -0
  41. package/dist/report.d.ts +42 -0
  42. package/dist/report.js +142 -0
  43. package/dist/serialize.d.ts +7 -0
  44. package/dist/serialize.js +79 -0
  45. package/dist/svg.d.ts +33 -0
  46. package/dist/svg.js +44 -0
  47. package/dist/syntax.d.ts +8 -0
  48. package/dist/syntax.js +19 -0
  49. package/dist/taco/figma-import/clipboard.d.ts +25 -0
  50. package/dist/taco/figma-import/clipboard.js +87 -0
  51. package/dist/taco/figma-import/clipboardSize.d.ts +31 -0
  52. package/dist/taco/figma-import/clipboardSize.js +107 -0
  53. package/dist/taco/figma-import/container/compression.d.ts +9 -0
  54. package/dist/taco/figma-import/container/compression.js +174 -0
  55. package/dist/taco/figma-import/container/error.d.ts +15 -0
  56. package/dist/taco/figma-import/container/error.js +19 -0
  57. package/dist/taco/figma-import/container/kiwiContainer.d.ts +41 -0
  58. package/dist/taco/figma-import/container/kiwiContainer.js +61 -0
  59. package/dist/taco/figma-import/container/limits.d.ts +22 -0
  60. package/dist/taco/figma-import/container/limits.js +22 -0
  61. package/dist/taco/figma-import/container/zip.d.ts +14 -0
  62. package/dist/taco/figma-import/container/zip.js +154 -0
  63. package/dist/taco/figma-import/figFile.d.ts +34 -0
  64. package/dist/taco/figma-import/figFile.js +91 -0
  65. package/dist/taco/figma-import/figFileDocument.d.ts +25 -0
  66. package/dist/taco/figma-import/figFileDocument.js +100 -0
  67. package/dist/taco/figma-import/import/blobs.d.ts +10 -0
  68. package/dist/taco/figma-import/import/blobs.js +23 -0
  69. package/dist/taco/figma-import/import/carry.d.ts +24 -0
  70. package/dist/taco/figma-import/import/carry.js +66 -0
  71. package/dist/taco/figma-import/import/componentProps.d.ts +90 -0
  72. package/dist/taco/figma-import/import/componentProps.js +329 -0
  73. package/dist/taco/figma-import/import/componentSets.d.ts +85 -0
  74. package/dist/taco/figma-import/import/componentSets.js +647 -0
  75. package/dist/taco/figma-import/import/converters/effects.d.ts +31 -0
  76. package/dist/taco/figma-import/import/converters/effects.js +127 -0
  77. package/dist/taco/figma-import/import/converters/ellipse.d.ts +7 -0
  78. package/dist/taco/figma-import/import/converters/ellipse.js +54 -0
  79. package/dist/taco/figma-import/import/converters/exportSettings.d.ts +4 -0
  80. package/dist/taco/figma-import/import/converters/exportSettings.js +49 -0
  81. package/dist/taco/figma-import/import/converters/frame.d.ts +21 -0
  82. package/dist/taco/figma-import/import/converters/frame.js +63 -0
  83. package/dist/taco/figma-import/import/converters/gradient.d.ts +74 -0
  84. package/dist/taco/figma-import/import/converters/gradient.js +108 -0
  85. package/dist/taco/figma-import/import/converters/group.d.ts +19 -0
  86. package/dist/taco/figma-import/import/converters/group.js +30 -0
  87. package/dist/taco/figma-import/import/converters/image.d.ts +13 -0
  88. package/dist/taco/figma-import/import/converters/image.js +94 -0
  89. package/dist/taco/figma-import/import/converters/layout.d.ts +33 -0
  90. package/dist/taco/figma-import/import/converters/layout.js +187 -0
  91. package/dist/taco/figma-import/import/converters/line.d.ts +11 -0
  92. package/dist/taco/figma-import/import/converters/line.js +40 -0
  93. package/dist/taco/figma-import/import/converters/rectangle.d.ts +3 -0
  94. package/dist/taco/figma-import/import/converters/rectangle.js +11 -0
  95. package/dist/taco/figma-import/import/converters/section.d.ts +8 -0
  96. package/dist/taco/figma-import/import/converters/section.js +29 -0
  97. package/dist/taco/figma-import/import/converters/shared.d.ts +71 -0
  98. package/dist/taco/figma-import/import/converters/shared.js +372 -0
  99. package/dist/taco/figma-import/import/converters/text.d.ts +54 -0
  100. package/dist/taco/figma-import/import/converters/text.js +707 -0
  101. package/dist/taco/figma-import/import/converters/vector.d.ts +105 -0
  102. package/dist/taco/figma-import/import/converters/vector.js +609 -0
  103. package/dist/taco/figma-import/import/converters/vectorNetwork.d.ts +114 -0
  104. package/dist/taco/figma-import/import/converters/vectorNetwork.js +503 -0
  105. package/dist/taco/figma-import/import/fields.d.ts +15 -0
  106. package/dist/taco/figma-import/import/fields.js +29 -0
  107. package/dist/taco/figma-import/import/instances.d.ts +184 -0
  108. package/dist/taco/figma-import/import/instances.js +1530 -0
  109. package/dist/taco/figma-import/import/nestingCycles.d.ts +86 -0
  110. package/dist/taco/figma-import/import/nestingCycles.js +488 -0
  111. package/dist/taco/figma-import/import/slots.d.ts +56 -0
  112. package/dist/taco/figma-import/import/slots.js +96 -0
  113. package/dist/taco/figma-import/import/styles.d.ts +48 -0
  114. package/dist/taco/figma-import/import/styles.js +48 -0
  115. package/dist/taco/figma-import/import/tree.d.ts +66 -0
  116. package/dist/taco/figma-import/import/tree.js +194 -0
  117. package/dist/taco/figma-import/import/types.d.ts +232 -0
  118. package/dist/taco/figma-import/import/types.js +33 -0
  119. package/dist/taco/figma-import/import/variables.d.ts +137 -0
  120. package/dist/taco/figma-import/import/variables.js +769 -0
  121. package/dist/taco/figma-import/import/variantTrees.d.ts +20 -0
  122. package/dist/taco/figma-import/import/variantTrees.js +520 -0
  123. package/dist/taco/figma-import/import/walk.d.ts +207 -0
  124. package/dist/taco/figma-import/import/walk.js +1464 -0
  125. package/dist/taco/figma-import/index.d.ts +22 -0
  126. package/dist/taco/figma-import/index.js +13 -0
  127. package/dist/taco/figma-import/kiwi/byteReader.d.ts +37 -0
  128. package/dist/taco/figma-import/kiwi/byteReader.js +151 -0
  129. package/dist/taco/figma-import/kiwi/error.d.ts +14 -0
  130. package/dist/taco/figma-import/kiwi/error.js +29 -0
  131. package/dist/taco/figma-import/kiwi/limits.d.ts +18 -0
  132. package/dist/taco/figma-import/kiwi/limits.js +18 -0
  133. package/dist/taco/figma-import/kiwi/message.d.ts +12 -0
  134. package/dist/taco/figma-import/kiwi/message.js +147 -0
  135. package/dist/taco/figma-import/kiwi/schema.d.ts +42 -0
  136. package/dist/taco/figma-import/kiwi/schema.js +206 -0
  137. package/dist/taco/figma-import/kiwi/types.d.ts +46 -0
  138. package/dist/taco/figma-import/kiwi/types.js +18 -0
  139. package/dist/taco/model/agent-hidden-fields.d.ts +20 -0
  140. package/dist/taco/model/agent-hidden-fields.js +29 -0
  141. package/dist/taco/model/asset-users.d.ts +23 -0
  142. package/dist/taco/model/asset-users.js +128 -0
  143. package/dist/taco/model/auto-layout-lines.d.ts +32 -0
  144. package/dist/taco/model/auto-layout-lines.js +70 -0
  145. package/dist/taco/model/codec.d.ts +444 -0
  146. package/dist/taco/model/codec.js +5665 -0
  147. package/dist/taco/model/color.d.ts +11 -0
  148. package/dist/taco/model/color.js +61 -0
  149. package/dist/taco/model/comment-operations.d.ts +102 -0
  150. package/dist/taco/model/comment-operations.js +227 -0
  151. package/dist/taco/model/component-evaluation.d.ts +96 -0
  152. package/dist/taco/model/component-evaluation.js +555 -0
  153. package/dist/taco/model/component-expressions.d.ts +242 -0
  154. package/dist/taco/model/component-expressions.js +1082 -0
  155. package/dist/taco/model/component-properties.d.ts +111 -0
  156. package/dist/taco/model/component-properties.js +339 -0
  157. package/dist/taco/model/component-samples.d.ts +83 -0
  158. package/dist/taco/model/component-samples.js +290 -0
  159. package/dist/taco/model/component-validity.d.ts +85 -0
  160. package/dist/taco/model/component-validity.js +397 -0
  161. package/dist/taco/model/components.d.ts +155 -0
  162. package/dist/taco/model/components.js +505 -0
  163. package/dist/taco/model/connector-ends.d.ts +20 -0
  164. package/dist/taco/model/connector-ends.js +188 -0
  165. package/dist/taco/model/connector-geometry.d.ts +74 -0
  166. package/dist/taco/model/connector-geometry.js +293 -0
  167. package/dist/taco/model/corner-radii.d.ts +26 -0
  168. package/dist/taco/model/corner-radii.js +47 -0
  169. package/dist/taco/model/derivations.d.ts +81 -0
  170. package/dist/taco/model/derivations.js +151 -0
  171. package/dist/taco/model/export-settings.d.ts +53 -0
  172. package/dist/taco/model/export-settings.js +156 -0
  173. package/dist/taco/model/expressions/ast.d.ts +153 -0
  174. package/dist/taco/model/expressions/ast.js +6 -0
  175. package/dist/taco/model/expressions/cache.d.ts +23 -0
  176. package/dist/taco/model/expressions/cache.js +43 -0
  177. package/dist/taco/model/expressions/check.d.ts +72 -0
  178. package/dist/taco/model/expressions/check.js +517 -0
  179. package/dist/taco/model/expressions/completion.d.ts +61 -0
  180. package/dist/taco/model/expressions/completion.js +421 -0
  181. package/dist/taco/model/expressions/evaluate.d.ts +32 -0
  182. package/dist/taco/model/expressions/evaluate.js +519 -0
  183. package/dist/taco/model/expressions/forms.d.ts +84 -0
  184. package/dist/taco/model/expressions/forms.js +200 -0
  185. package/dist/taco/model/expressions/index.d.ts +14 -0
  186. package/dist/taco/model/expressions/index.js +17 -0
  187. package/dist/taco/model/expressions/lexer.d.ts +42 -0
  188. package/dist/taco/model/expressions/lexer.js +213 -0
  189. package/dist/taco/model/expressions/library.d.ts +33 -0
  190. package/dist/taco/model/expressions/library.js +117 -0
  191. package/dist/taco/model/expressions/names.d.ts +43 -0
  192. package/dist/taco/model/expressions/names.js +99 -0
  193. package/dist/taco/model/expressions/parser.d.ts +15 -0
  194. package/dist/taco/model/expressions/parser.js +438 -0
  195. package/dist/taco/model/expressions/rename.d.ts +34 -0
  196. package/dist/taco/model/expressions/rename.js +46 -0
  197. package/dist/taco/model/expressions/source.d.ts +15 -0
  198. package/dist/taco/model/expressions/source.js +161 -0
  199. package/dist/taco/model/expressions/types.d.ts +119 -0
  200. package/dist/taco/model/expressions/types.js +102 -0
  201. package/dist/taco/model/expressions/values.d.ts +97 -0
  202. package/dist/taco/model/expressions/values.js +160 -0
  203. package/dist/taco/model/geometry-limits.d.ts +16 -0
  204. package/dist/taco/model/geometry-limits.js +67 -0
  205. package/dist/taco/model/geometry.d.ts +47 -0
  206. package/dist/taco/model/geometry.js +193 -0
  207. package/dist/taco/model/group-bounds.d.ts +38 -0
  208. package/dist/taco/model/group-bounds.js +144 -0
  209. package/dist/taco/model/id-table.d.ts +37 -0
  210. package/dist/taco/model/id-table.js +80 -0
  211. package/dist/taco/model/index.d.ts +25 -0
  212. package/dist/taco/model/index.js +27 -0
  213. package/dist/taco/model/instance-resolver.d.ts +376 -0
  214. package/dist/taco/model/instance-resolver.js +1778 -0
  215. package/dist/taco/model/layer-syntax.d.ts +340 -0
  216. package/dist/taco/model/layer-syntax.js +3506 -0
  217. package/dist/taco/model/layout/constraints.d.ts +84 -0
  218. package/dist/taco/model/layout/constraints.js +445 -0
  219. package/dist/taco/model/layout/frame-layout.d.ts +46 -0
  220. package/dist/taco/model/layout/frame-layout.js +618 -0
  221. package/dist/taco/model/layout/node-sizing.d.ts +163 -0
  222. package/dist/taco/model/layout/node-sizing.js +486 -0
  223. package/dist/taco/model/legacy-connector-caps.d.ts +15 -0
  224. package/dist/taco/model/legacy-connector-caps.js +70 -0
  225. package/dist/taco/model/linear-call.d.ts +48 -0
  226. package/dist/taco/model/linear-call.js +58 -0
  227. package/dist/taco/model/new-nodes.d.ts +145 -0
  228. package/dist/taco/model/new-nodes.js +277 -0
  229. package/dist/taco/model/node-builder.d.ts +449 -0
  230. package/dist/taco/model/node-builder.js +2294 -0
  231. package/dist/taco/model/node-table-watch.d.ts +36 -0
  232. package/dist/taco/model/node-table-watch.js +63 -0
  233. package/dist/taco/model/node-transform.d.ts +39 -0
  234. package/dist/taco/model/node-transform.js +79 -0
  235. package/dist/taco/model/node-users-index.d.ts +10 -0
  236. package/dist/taco/model/node-users-index.js +82 -0
  237. package/dist/taco/model/operation-references.d.ts +80 -0
  238. package/dist/taco/model/operation-references.js +399 -0
  239. package/dist/taco/model/operations.d.ts +610 -0
  240. package/dist/taco/model/operations.js +2882 -0
  241. package/dist/taco/model/overlay-table.d.ts +71 -0
  242. package/dist/taco/model/overlay-table.js +171 -0
  243. package/dist/taco/model/override-remap.d.ts +69 -0
  244. package/dist/taco/model/override-remap.js +230 -0
  245. package/dist/taco/model/parent-table.d.ts +53 -0
  246. package/dist/taco/model/parent-table.js +193 -0
  247. package/dist/taco/model/problem-collector.d.ts +27 -0
  248. package/dist/taco/model/problem-collector.js +101 -0
  249. package/dist/taco/model/sha256.d.ts +10 -0
  250. package/dist/taco/model/sha256.js +79 -0
  251. package/dist/taco/model/shape-geometry.d.ts +96 -0
  252. package/dist/taco/model/shape-geometry.js +368 -0
  253. package/dist/taco/model/shared-node-table.d.ts +97 -0
  254. package/dist/taco/model/shared-node-table.js +546 -0
  255. package/dist/taco/model/slots.d.ts +113 -0
  256. package/dist/taco/model/slots.js +281 -0
  257. package/dist/taco/model/stroke-settings.d.ts +37 -0
  258. package/dist/taco/model/stroke-settings.js +90 -0
  259. package/dist/taco/model/svg-path-import.d.ts +89 -0
  260. package/dist/taco/model/svg-path-import.js +219 -0
  261. package/dist/taco/model/text-measurement.d.ts +142 -0
  262. package/dist/taco/model/text-measurement.js +846 -0
  263. package/dist/taco/model/text-reads.d.ts +66 -0
  264. package/dist/taco/model/text-reads.js +128 -0
  265. package/dist/taco/model/text-sizer.d.ts +358 -0
  266. package/dist/taco/model/text-sizer.js +996 -0
  267. package/dist/taco/model/theme-users.d.ts +59 -0
  268. package/dist/taco/model/theme-users.js +312 -0
  269. package/dist/taco/model/thumbnail.d.ts +15 -0
  270. package/dist/taco/model/thumbnail.js +34 -0
  271. package/dist/taco/model/types.d.ts +2369 -0
  272. package/dist/taco/model/types.js +366 -0
  273. package/dist/taco/model/unknown-property.d.ts +5 -0
  274. package/dist/taco/model/unknown-property.js +7 -0
  275. package/dist/taco/model/validated-documents.d.ts +22 -0
  276. package/dist/taco/model/validated-documents.js +22 -0
  277. package/dist/taco/model/variable-modes.d.ts +61 -0
  278. package/dist/taco/model/variable-modes.js +438 -0
  279. package/dist/taco/model/variable-references.d.ts +54 -0
  280. package/dist/taco/model/variable-references.js +183 -0
  281. package/dist/taco/model/variables.d.ts +24 -0
  282. package/dist/taco/model/variables.js +151 -0
  283. package/dist/taco/model/vector-network.d.ts +34 -0
  284. package/dist/taco/model/vector-network.js +411 -0
  285. package/dist/taco/svg-import/import-svg.d.ts +36 -0
  286. package/dist/taco/svg-import/import-svg.js +729 -0
  287. package/dist/taco/svg-import/index.d.ts +3 -0
  288. package/dist/taco/svg-import/index.js +3 -0
  289. package/dist/taco/svg-import/limits/limits.d.ts +79 -0
  290. package/dist/taco/svg-import/limits/limits.js +160 -0
  291. package/dist/taco/svg-import/paint/gradients.d.ts +64 -0
  292. package/dist/taco/svg-import/paint/gradients.js +429 -0
  293. package/dist/taco/svg-import/paint/paint.d.ts +32 -0
  294. package/dist/taco/svg-import/paint/paint.js +162 -0
  295. package/dist/taco/svg-import/paths/paths.d.ts +58 -0
  296. package/dist/taco/svg-import/paths/paths.js +205 -0
  297. package/dist/taco/svg-import/public-types.d.ts +279 -0
  298. package/dist/taco/svg-import/public-types.js +56 -0
  299. package/dist/taco/svg-import/report/report.d.ts +44 -0
  300. package/dist/taco/svg-import/report/report.js +79 -0
  301. package/dist/taco/svg-import/reuse/reuse.d.ts +99 -0
  302. package/dist/taco/svg-import/reuse/reuse.js +840 -0
  303. package/dist/taco/svg-import/shapes/shapes.d.ts +35 -0
  304. package/dist/taco/svg-import/shapes/shapes.js +386 -0
  305. package/dist/taco/svg-import/structure/effects.d.ts +26 -0
  306. package/dist/taco/svg-import/structure/effects.js +618 -0
  307. package/dist/taco/svg-import/structure/image.d.ts +24 -0
  308. package/dist/taco/svg-import/structure/image.js +495 -0
  309. package/dist/taco/svg-import/structure/walk.d.ts +85 -0
  310. package/dist/taco/svg-import/structure/walk.js +544 -0
  311. package/dist/taco/svg-import/style/color.d.ts +40 -0
  312. package/dist/taco/svg-import/style/color.js +275 -0
  313. package/dist/taco/svg-import/style/computed.d.ts +214 -0
  314. package/dist/taco/svg-import/style/computed.js +1534 -0
  315. package/dist/taco/svg-import/style/css.d.ts +127 -0
  316. package/dist/taco/svg-import/style/css.js +541 -0
  317. package/dist/taco/svg-import/style/media.d.ts +25 -0
  318. package/dist/taco/svg-import/style/media.js +307 -0
  319. package/dist/taco/svg-import/style/properties.d.ts +43 -0
  320. package/dist/taco/svg-import/style/properties.js +135 -0
  321. package/dist/taco/svg-import/style/selector-reach.d.ts +30 -0
  322. package/dist/taco/svg-import/style/selector-reach.js +169 -0
  323. package/dist/taco/svg-import/style/selector-validity.d.ts +14 -0
  324. package/dist/taco/svg-import/style/selector-validity.js +307 -0
  325. package/dist/taco/svg-import/text/text.d.ts +29 -0
  326. package/dist/taco/svg-import/text/text.js +545 -0
  327. package/dist/taco/svg-import/transform/matrix.d.ts +111 -0
  328. package/dist/taco/svg-import/transform/matrix.js +229 -0
  329. package/dist/taco/svg-import/tree/element-data.d.ts +52 -0
  330. package/dist/taco/svg-import/tree/element-data.js +155 -0
  331. package/dist/taco/svg-import/tree/elements.d.ts +36 -0
  332. package/dist/taco/svg-import/tree/elements.js +121 -0
  333. package/dist/taco/svg-import/units/length.d.ts +43 -0
  334. package/dist/taco/svg-import/units/length.js +125 -0
  335. package/dist/taco/svg-import/units/viewbox.d.ts +35 -0
  336. package/dist/taco/svg-import/units/viewbox.js +77 -0
  337. package/package.json +55 -4
@@ -0,0 +1,1464 @@
1
+ import { formatExpressionName, buildParentMap, componentNestingGraph, entryOf, findComponentCycle, fitAllGroups, layerPathKey, nodeLocalTransform, ownedChildIds, parseLayerPath, } from "../../model/index.js";
2
+ import { field, guidText, isObject } from "./fields.js";
3
+ import { isDetachedStyle } from "./styles.js";
4
+ import { convertEllipse } from "./converters/ellipse.js";
5
+ import { sniffImageMimeType } from "./converters/image.js";
6
+ import { convertFrame, isFigmaGroup } from "./converters/frame.js";
7
+ import { stackChildFields } from "./converters/layout.js";
8
+ import { convertGroup } from "./converters/group.js";
9
+ import { convertLine } from "./converters/line.js";
10
+ import { convertRectangle } from "./converters/rectangle.js";
11
+ import { bindingsDroppedBy, bindsField, dropSizingWhereFilled, dropUnheldSizing, instanceFields, overrideKeyOf, shownSymbol, symbolsNamedBy, unbindInnerBindings } from "./instances.js";
12
+ import { isSlotContent, slotBindingOf, slotFillsOf, slotSizeMismatch } from "./slots.js";
13
+ import { componentsByKeyOf, propertiesOf, propertyExpressions, variantDefIds } from "./componentProps.js";
14
+ import { mergeComponentSets, planSet, withoutVariantParts } from "./componentSets.js";
15
+ import { nestingMemo, nestingSearch, swapsToCut } from "./nestingCycles.js";
16
+ import { convertSection } from "./converters/section.js";
17
+ import { convertText, figmaTextStyle } from "./converters/text.js";
18
+ import { convertBooleanOperation, convertStarOrPolygon, convertVector, whyFlattened } from "./converters/vector.js";
19
+ import { blobReader } from "./blobs.js";
20
+ import { carry, carryMarks, clearConstraints, withImageCrop } from "./carry.js";
21
+ import { nodeEffects } from "./converters/effects.js";
22
+ import { frameGeometry, visualStyle } from "./converters/shared.js";
23
+ import { bindLayerVariables, figmaVariableModes, foldsVariableAlpha, keptFontSize, readFigmaVariables } from "./variables.js";
24
+ import { buildFigmaTree, chooseRoots, rootSourceOf, withAncestorTransforms } from "./tree.js";
25
+ import { DEFAULT_FIGMA_IMPORT_LIMITS, FigmaImportError } from "./types.js";
26
+ /**
27
+ * The converter for each Figma node type, keyed by the `NodeChange.type` enum
28
+ * name. The walk itself turns a SYMBOL into a component (its root made by
29
+ * `convertFrame`, with an instance of it where the SYMBOL sits) and an
30
+ * INSTANCE into an instance (see `instanceFields`).
31
+ */
32
+ const CONVERTERS = {
33
+ BOOLEAN_OPERATION: convertBooleanOperation,
34
+ ELLIPSE: convertEllipse,
35
+ FRAME: convertFrame,
36
+ GROUP: convertGroup,
37
+ LINE: convertLine,
38
+ RECTANGLE: convertRectangle,
39
+ REGULAR_POLYGON: convertStarOrPolygon,
40
+ ROUNDED_RECTANGLE: convertRectangle,
41
+ SECTION: convertSection,
42
+ STAR: convertStarOrPolygon,
43
+ TEXT: convertText,
44
+ VECTOR: convertVector,
45
+ };
46
+ /** The converter for a node type; own keys only, so "constructor" finds nothing. */
47
+ export function converterFor(type) {
48
+ return Object.hasOwn(CONVERTERS, type) ? CONVERTERS[type] : undefined;
49
+ }
50
+ function pathText(link) {
51
+ const segments = [];
52
+ for (let at = link; at !== null; at = at.parent)
53
+ segments.push(`${at.node.type} ${JSON.stringify(at.node.name)}`);
54
+ return segments.reverse().join(" > ");
55
+ }
56
+ /** A node's `layerType`: its Figma type, or `GROUP` for a FRAME Figma uses as a group. */
57
+ function layerTypeOf(node) {
58
+ return node.type === "FRAME" && isFigmaGroup(node.change) ? "GROUP" : node.type;
59
+ }
60
+ /** At most this many layer types are named in counts; Figma has fewer node types, so only a crafted message goes past it. */
61
+ const NAMED_LAYER_TYPES_LIMIT = 32;
62
+ /** The `layerType` that counts layers of types met after `NAMED_LAYER_TYPES_LIMIT` others. */
63
+ const OTHER_LAYER_TYPE = "OTHER";
64
+ /** The bindings an instance keeps on its own node; it binds the rest of its root through an override of the root. */
65
+ const INSTANCE_OWN_BINDINGS = new Set(["width", "height", "visibility", "opacity"]);
66
+ function addCount(counts, type, count) {
67
+ counts.set(type, (counts.get(type) ?? 0) + count);
68
+ }
69
+ function countedType(node, inside) {
70
+ const type = layerTypeOf(node);
71
+ if (inside.named.has(type))
72
+ return type;
73
+ if (inside.named.size >= NAMED_LAYER_TYPES_LIMIT)
74
+ return OTHER_LAYER_TYPE;
75
+ inside.named.add(type);
76
+ return type;
77
+ }
78
+ function layersInsideMap(node, inside) {
79
+ const known = inside.counts.get(node.children);
80
+ if (known !== undefined)
81
+ return known;
82
+ // Pre-order, so types are in the order first met. Each kept list met on the way
83
+ // gets its own counts, added to the enclosing counts when its layers are done.
84
+ const open = [new Map()];
85
+ const stack = [{ close: node.children }];
86
+ for (let i = node.children.length - 1; i >= 0; i--)
87
+ stack.push({ enter: node.children[i] });
88
+ for (let item = stack.pop(); item !== undefined; item = stack.pop()) {
89
+ if ("close" in item) {
90
+ const done = open.pop();
91
+ inside.counts.set(item.close, done);
92
+ const outer = open.at(-1);
93
+ if (outer !== undefined)
94
+ for (const [type, count] of done)
95
+ addCount(outer, type, count);
96
+ continue;
97
+ }
98
+ const child = item.enter;
99
+ // Variables and collections are not layers; they are imported or reported on their own.
100
+ if (child.type === "VARIABLE" || child.type === "VARIABLE_SET")
101
+ continue;
102
+ addCount(open.at(-1), countedType(child, inside), 1);
103
+ if (child.children.length === 0)
104
+ continue;
105
+ const cached = inside.counts.get(child.children);
106
+ if (cached !== undefined) {
107
+ for (const [type, count] of cached)
108
+ addCount(open.at(-1), type, count);
109
+ continue;
110
+ }
111
+ if (inside.kept.has(child.children)) {
112
+ open.push(new Map());
113
+ stack.push({ close: child.children });
114
+ }
115
+ for (let i = child.children.length - 1; i >= 0; i--)
116
+ stack.push({ enter: child.children[i] });
117
+ }
118
+ return inside.counts.get(node.children);
119
+ }
120
+ function layersInsideByType(node, cache) {
121
+ return [...layersInsideMap(node, cache)].map(([layerType, count]) => ({ layerType, count }));
122
+ }
123
+ function countLayersInside(node, cache) {
124
+ let total = 0;
125
+ for (const count of layersInsideMap(node, cache).values())
126
+ total += count;
127
+ return total;
128
+ }
129
+ function layersText(count) {
130
+ return count === 1 ? "the 1 layer inside it" : `the ${String(count)} layers inside it`;
131
+ }
132
+ /**
133
+ * Imports a decoded Figma Kiwi `NODE_CHANGES` message (from a clipboard
134
+ * paste or a .fig file) as Taco nodes. Throws `FigmaImportError` when the
135
+ * message is refused; everything that is imported inexactly or not at all is
136
+ * in the result's `report`.
137
+ */
138
+ export function importFigmaMessage(message, options) {
139
+ return walkMessage(message, options, false).result;
140
+ }
141
+ /** Reads file definitions before expression merging for the native document adapter.
142
+ * @param message - Decoded Kiwi node changes.
143
+ * @param options - Reader ID and image sources.
144
+ * @returns Converted geometry and its original definition relationships.
145
+ * @internal
146
+ */
147
+ export function readFileMessage(message, options) {
148
+ const { result, sources } = walkMessage(message, options, true);
149
+ return { ...result, sources };
150
+ }
151
+ // Keep the exported lookup independent of the layer walk's temporary maps and blob reader.
152
+ function styleLookup(tree) {
153
+ let stylesByKey;
154
+ const styleKey = (styleType, key) => `${styleType}\u0000${key}`;
155
+ return (reference, styleType) => {
156
+ if (!isObject(reference))
157
+ return undefined;
158
+ const guid = reference["guid"];
159
+ let found;
160
+ if (isObject(guid) && Number.isInteger(guid["sessionID"]) && Number.isInteger(guid["localID"]))
161
+ found = tree.nodes.get(guidText(guid, "style reference"));
162
+ if (found?.change["styleType"] !== styleType) {
163
+ const key = isObject(reference["assetRef"]) ? reference["assetRef"]["key"] : undefined;
164
+ if (typeof key !== "string")
165
+ return undefined;
166
+ if (stylesByKey === undefined) {
167
+ stylesByKey = new Map();
168
+ for (const node of tree.nodes.values()) {
169
+ const nodeKey = node.change["key"];
170
+ const nodeType = node.change["styleType"];
171
+ if (typeof nodeType !== "string" || typeof nodeKey !== "string")
172
+ continue;
173
+ const byKey = styleKey(nodeType, nodeKey);
174
+ if (!stylesByKey.has(byKey))
175
+ stylesByKey.set(byKey, node);
176
+ }
177
+ }
178
+ found = stylesByKey.get(styleKey(styleType, key));
179
+ }
180
+ return found;
181
+ };
182
+ }
183
+ /** Reads converted layers with their original Figma nodes for Moondraft's adapters. */
184
+ export function walkMessage(message, options, native, distinctSources) {
185
+ const rootSource = rootSourceOf(message, options.roots);
186
+ const limits = { ...DEFAULT_FIGMA_IMPORT_LIMITS[rootSource], ...options.limits };
187
+ const tree = buildFigmaTree(message, limits);
188
+ const sharedStyle = (node) => ["TEXT", "FILL", "EFFECT"].includes(String(node.change["styleType"]));
189
+ const skipStyle = (node) => node.change["styleType"] === "GRID" || native && sharedStyle(node);
190
+ const chosen = chooseRoots(message, tree, rootSource);
191
+ const insideCache = { counts: new Map(), kept: new Set(), named: new Set() };
192
+ for (const group of chosen.groups)
193
+ for (const root of group.roots)
194
+ insideCache.kept.add(root.children);
195
+ const report = [];
196
+ const blob = blobReader(message);
197
+ const assets = {};
198
+ const missingImages = new Set();
199
+ const image = (hash, size) => {
200
+ const id = `figma-image-${hash}`;
201
+ if (Object.hasOwn(assets, id))
202
+ return assets[id];
203
+ if (missingImages.has(hash))
204
+ return null;
205
+ missingImages.add(hash);
206
+ const supplied = options.images?.(hash);
207
+ if (supplied === undefined)
208
+ return `image ${hash.slice(0, 8)} was not supplied`;
209
+ const mimeType = supplied.mimeType ?? sniffImageMimeType(supplied.bytes);
210
+ if (mimeType === undefined)
211
+ return `image ${hash.slice(0, 8)} is not a PNG, JPEG, GIF or WebP file`;
212
+ const width = supplied.width ?? size?.width;
213
+ const height = supplied.height ?? size?.height;
214
+ return assets[id] = { id, hash, mimeType, bytes: supplied.bytes, ...(width !== undefined ? { width } : {}), ...(height !== undefined ? { height } : {}) };
215
+ };
216
+ const paintIndices = new Map();
217
+ const effectFields = new Map();
218
+ const trackPaints = native ? {
219
+ paintIndices(source, indices) { paintIndices.set(source, indices); },
220
+ effectField(effect, path) { effectFields.set(effect, path); },
221
+ } : {};
222
+ const vectorCommands = { left: limits.vectorCommands, limit: limits.vectorCommands };
223
+ // `withLayersInside`: the entry leaves out the layers inside the node too.
224
+ const add = (link, kind, reason, withLayersInside = false) => {
225
+ const { node } = link;
226
+ const layersInside = withLayersInside ? layersInsideByType(node, insideCache) : [];
227
+ report.push({ nodeId: node.id, nodeType: node.type, nodePath: pathText(link), layerType: layerTypeOf(node), kind, reason, layersInside });
228
+ };
229
+ for (const id of chosen.missing) {
230
+ report.push({ nodeId: id, nodeType: "", nodePath: "", layerType: "", kind: "node-left-out", reason: "the copied node is not in the message", layersInside: [] });
231
+ }
232
+ // A node outside the walk (a variable) is reported with the path up its parents.
233
+ // A loop, not recursion: the parent chain can be as long as the message.
234
+ const variableLinkOf = (node) => {
235
+ const chain = [];
236
+ for (let at = node; at !== undefined; at = at.parentId === undefined ? undefined : tree.nodes.get(at.parentId))
237
+ chain.push(at);
238
+ return chain.reduceRight((parent, at) => ({ node: at, parent }), null);
239
+ };
240
+ const variables = options.bindVariables === false ? undefined
241
+ : readFigmaVariables(tree.nodes.values(), options.idSource, (node, kind, reason) => add(variableLinkOf(node), kind, reason), native);
242
+ if (variables === undefined) {
243
+ for (const node of tree.nodes.values()) {
244
+ if (node.type === "VARIABLE_SET" || node.type === "VARIABLE") {
245
+ add(variableLinkOf(node), "node-left-out", `the variable${node.type === "VARIABLE" ? "" : " collection"} is not imported: this import adds no variables to the document`);
246
+ }
247
+ }
248
+ }
249
+ const nodes = [];
250
+ // Page-walk nodes already imported, so a copied node listed again is reported, not imported twice.
251
+ const visited = new Set();
252
+ // Nodes imported as component layers, for the orphan check.
253
+ const inComponents = new Set();
254
+ // Override fields left out, reported once per field name with a count.
255
+ const leftOutFields = new Map();
256
+ // Other reasons said once per kind and reason, with a count and the first node met.
257
+ const counted = new Map();
258
+ const addCounted = (link, kind, reason) => {
259
+ if (native) {
260
+ add(link, kind, reason);
261
+ return;
262
+ }
263
+ const key = `${kind}\n${reason}`;
264
+ const seen = counted.get(key);
265
+ if (seen === undefined)
266
+ counted.set(key, { link, kind, reason, count: 1 });
267
+ else
268
+ seen.count += 1;
269
+ };
270
+ // The shared text styles (`FigmaImportResult.textStyles`): one for each Figma text style a layer names, made the first time.
271
+ const textStyles = {};
272
+ const textStyleUses = new Map();
273
+ let textStylesByKey;
274
+ const textStyleNode = (reference) => {
275
+ if (!isObject(reference) || native && isDetachedStyle(reference))
276
+ return undefined;
277
+ const guid = reference["guid"];
278
+ if (isObject(guid) && Number.isInteger(guid["sessionID"]) && Number.isInteger(guid["localID"])) {
279
+ const found = tree.nodes.get(guidText(guid, "styleIdForText"));
280
+ if (found !== undefined && (!native || found.change["styleType"] === "TEXT"))
281
+ return found;
282
+ }
283
+ // A library style is named by its key; the message may carry a copy of it.
284
+ const key = isObject(reference["assetRef"]) ? reference["assetRef"]["key"] : undefined;
285
+ if (typeof key !== "string")
286
+ return undefined;
287
+ if (textStylesByKey === undefined) {
288
+ textStylesByKey = new Map();
289
+ for (const node of tree.nodes.values()) {
290
+ const nodeKey = node.change["key"];
291
+ if (node.change["styleType"] === "TEXT" && typeof nodeKey === "string" && !textStylesByKey.has(nodeKey))
292
+ textStylesByKey.set(nodeKey, node);
293
+ }
294
+ }
295
+ return textStylesByKey.get(key);
296
+ };
297
+ const styleNodeFor = styleLookup(tree);
298
+ const styleList = (reference, styleType) => {
299
+ const found = styleNodeFor(reference, styleType);
300
+ if (found === undefined)
301
+ return undefined;
302
+ const list = styleType === "EFFECT" ? "effects" : "fillPaints";
303
+ return field(found.change, list, "list", `${styleType === "EFFECT" ? "effect" : "colour"} style ${found.id}`) ?? [];
304
+ };
305
+ // The text layers with font metadata that name each text style, in message order, so a style's auto line height
306
+ // comes from the font's own metric even when the first layer that names it has none.
307
+ let textStyleLayers;
308
+ const layersNaming = (style) => {
309
+ if (textStyleLayers === undefined) {
310
+ const found = new Map();
311
+ textStyleLayers = found;
312
+ for (const node of tree.nodes.values()) {
313
+ const derived = node.change["derivedTextData"];
314
+ if (node.type !== "TEXT" || !isObject(derived) || !Array.isArray(derived["fontMetaData"]) || derived["fontMetaData"].length === 0)
315
+ continue;
316
+ const textData = node.change["textData"];
317
+ const table = isObject(textData) && Array.isArray(textData["styleOverrideTable"]) ? textData["styleOverrideTable"] : [];
318
+ const named = new Set();
319
+ for (const fields of [node.change, ...table]) {
320
+ const styleNode = isObject(fields) ? textStyleNode(fields["styleIdForText"]) : undefined;
321
+ if (styleNode === undefined || named.has(styleNode))
322
+ continue;
323
+ named.add(styleNode);
324
+ const list = found.get(styleNode);
325
+ if (list === undefined)
326
+ found.set(styleNode, [node.change]);
327
+ else
328
+ list.push(node.change);
329
+ }
330
+ }
331
+ }
332
+ return textStyleLayers.get(style) ?? [];
333
+ };
334
+ // The numbers and colours the variable bindings of `node` give, in the modes it uses (`NodeWalk.variableNumber`,
335
+ // `NodeWalk.variableColor`); with `shownBy`, in
336
+ // the modes that instance shows it in.
337
+ const variableNumberOf = (node, shownBy) => variables === undefined ? {} : {
338
+ variableNumber: (data) => {
339
+ if (native && !variables.positiveLengthOf(data, node.id))
340
+ return undefined;
341
+ const read = variables.numberOf(data, node, `node ${node.id} variableConsumptionMap`, shownBy);
342
+ return "value" in read ? read.value : undefined;
343
+ },
344
+ variableColor: (data) => {
345
+ const read = variables.colorOf(data, node, `node ${node.id} stopsVar`, shownBy);
346
+ return "value" in read ? read.value : undefined;
347
+ },
348
+ ...(native && {
349
+ copiedPaintAlpha: (paint, opacity) => foldsVariableAlpha(paint, opacity, node, variables, node.id, shownBy),
350
+ textFillStyle: (reference) => styleNodeFor(reference, "FILL")?.id,
351
+ textColorVariable: (data) => {
352
+ const variable = variables.variableOf(data, node.id);
353
+ return "id" in variable && variable.type === "color" ? variable.id : null;
354
+ },
355
+ fontSizeVariable: (data) => variables.positiveLengthOf(data, node.id),
356
+ }),
357
+ keptFontSize: (layer) => keptFontSize(layer, node, variables, shownBy),
358
+ };
359
+ // `link` is null for a layer converted alone, which reports nothing.
360
+ const textStyleFor = (link) => (reference, layer) => {
361
+ const say = (kind, reason) => { if (link !== null)
362
+ addCounted(link, kind, reason); };
363
+ const node = textStyleNode(reference);
364
+ if (native && isDetachedStyle(reference))
365
+ return undefined;
366
+ if (node?.change["styleType"] !== "TEXT") {
367
+ say("approximated", "the text's Figma text style is not in the message; its values are kept as direct formatting");
368
+ return undefined;
369
+ }
370
+ let use = textStyleUses.get(node);
371
+ if (use === undefined) {
372
+ if (options.textStyles === false)
373
+ use = { change: node.change };
374
+ else {
375
+ const id = options.idSource();
376
+ const style = figmaTextStyle(node.change, node.name, say, `text style ${node.id}`, [...(layer === undefined ? [] : [layer]), ...layersNaming(node)], variableNumberOf(node).variableNumber);
377
+ textStyles[id] = style;
378
+ use = { change: node.change, shared: { id, style } };
379
+ }
380
+ textStyleUses.set(node, use);
381
+ }
382
+ if (use.shared === undefined)
383
+ say("approximated", `text style ${JSON.stringify(node.name)} is imported as fixed properties: this import adds no text styles to the document`);
384
+ return use;
385
+ };
386
+ const roots = [];
387
+ // Each frame given a stack, with the map from Figma node to converted node of the walk it was made in, for `settleStacks`.
388
+ const stacks = [];
389
+ const pages = [];
390
+ // The layer each Figma node went to (`FigmaImportResult.layerIds`).
391
+ const layerIds = {};
392
+ const placements = new Map();
393
+ // Which components to import: every SYMBOL of a file, or under the copied roots, and every SYMBOL these name, directly or through others.
394
+ const componentIds = new Map();
395
+ const symbolOrder = [];
396
+ const nests = new Map();
397
+ {
398
+ const pending = [];
399
+ // The SYMBOLs and sets by component key, for the components an instance swap property prefers.
400
+ let byKey;
401
+ const wantPreferred = (change) => {
402
+ for (const def of Array.isArray(change["componentPropDefs"]) ? change["componentPropDefs"] : []) {
403
+ const values = isObject(def) && isObject(def["preferredValues"]) ? def["preferredValues"]["instanceSwapValues"] : undefined;
404
+ if (!Array.isArray(values))
405
+ continue;
406
+ if (byKey === undefined) {
407
+ byKey = new Map();
408
+ for (const node of tree.nodes.values()) {
409
+ const key = node.change["componentKey"];
410
+ if (typeof key === "string" && key !== "" && (node.type === "SYMBOL" || node.change["isStateGroup"] === true) && !byKey.has(key))
411
+ byKey.set(key, node);
412
+ }
413
+ }
414
+ for (const value of values) {
415
+ const found = isObject(value) && typeof value["key"] === "string" ? byKey.get(value["key"]) : undefined;
416
+ if (found?.type === "SYMBOL")
417
+ want(found.id);
418
+ else if (found !== undefined)
419
+ for (const child of found.children)
420
+ want(child.id);
421
+ }
422
+ }
423
+ };
424
+ const want = (symbolId) => {
425
+ const symbol = tree.nodes.get(symbolId);
426
+ // A SYMBOL without a complete size or transform has no root frame (`framedBase`), so instances of it are left out.
427
+ if (symbol?.type !== "SYMBOL" || componentIds.has(symbolId) || frameGeometry(symbol) === null)
428
+ return;
429
+ componentIds.set(symbolId, options.idSource());
430
+ symbolOrder.push(symbol);
431
+ pending.push(symbol);
432
+ // A variant's swap defaults are on its set, and an instance can switch to any of its set's variants.
433
+ const owner = symbol.parentId === undefined ? undefined : tree.nodes.get(symbol.parentId);
434
+ wantPreferred(symbol.change);
435
+ if (owner?.change["isStateGroup"] === true) {
436
+ for (const named of symbolsNamedBy(owner.change))
437
+ want(named);
438
+ wantPreferred(owner.change);
439
+ for (const sibling of owner.children)
440
+ if (sibling.type === "SYMBOL")
441
+ want(sibling.id);
442
+ }
443
+ };
444
+ const nest = (inSymbol, symbolId) => {
445
+ let set = nests.get(inSymbol);
446
+ if (set === undefined)
447
+ nests.set(inSymbol, set = new Set());
448
+ set.add(symbolId);
449
+ };
450
+ // A copied root's nodes are scanned once, so copied roots inside each other are not walked again. A SYMBOL's scan stops at
451
+ // SYMBOLs inside it, so it meets each node at most once without this set, and still adds its edges for nodes a copied root met first.
452
+ const scanned = new Set();
453
+ const scan = (from, inSymbol) => {
454
+ const stack = [from];
455
+ // The content an instance puts in a slot sits elsewhere in the message (an internal page), but is imported with the instance.
456
+ const contents = new Set();
457
+ for (let at = stack.pop(); at !== undefined; at = stack.pop()) {
458
+ if (at.type === "SYMBOL" && at !== from) {
459
+ want(at.id);
460
+ // A SYMBOL inside a component is placed there as an instance of it.
461
+ if (inSymbol !== undefined)
462
+ nest(inSymbol, at.id);
463
+ continue;
464
+ }
465
+ if (inSymbol === undefined) {
466
+ if (scanned.has(at))
467
+ continue;
468
+ scanned.add(at);
469
+ }
470
+ for (const named of symbolsNamedBy(at.change))
471
+ want(named);
472
+ const shown = at.type === "INSTANCE" ? shownSymbol(at) : undefined;
473
+ if (inSymbol !== undefined && shown !== undefined && tree.nodes.get(shown)?.type === "SYMBOL")
474
+ nest(inSymbol, shown);
475
+ stack.push(...at.children);
476
+ if (at.type !== "INSTANCE")
477
+ continue;
478
+ for (const { contentId } of slotFillsOf(at)) {
479
+ const content = tree.nodes.get(contentId);
480
+ if (content !== undefined && isSlotContent(content) && !contents.has(content)) {
481
+ contents.add(content);
482
+ stack.push(content);
483
+ }
484
+ }
485
+ }
486
+ };
487
+ // A file brings every component on its pages, used or not, as Figma's assets panel lists them; a clipboard only those it uses.
488
+ // An internal-only page holds Figma's own copies (older versions, components of other files), which come only when used.
489
+ if (!chosen.groups.some((group) => group.page === null)) {
490
+ const internal = new Set(chosen.internalPages);
491
+ const pageOf = (node) => {
492
+ let at = node;
493
+ while (at !== undefined && at.type !== "CANVAS")
494
+ at = at.parentId === undefined ? undefined : tree.nodes.get(at.parentId);
495
+ return at;
496
+ };
497
+ for (const node of tree.nodes.values()) {
498
+ if (node.type !== "SYMBOL")
499
+ continue;
500
+ const page = pageOf(node);
501
+ if (page === undefined || !internal.has(page))
502
+ want(node.id);
503
+ }
504
+ }
505
+ for (const group of chosen.groups)
506
+ for (const root of group.roots) {
507
+ if (root.type === "SYMBOL")
508
+ want(root.id);
509
+ else
510
+ scan(root, undefined);
511
+ }
512
+ for (let symbol = pending.pop(); symbol !== undefined; symbol = pending.pop())
513
+ scan(symbol, symbol.id);
514
+ }
515
+ // Nestings that would put a component inside itself: the edges that close a cycle, found depth first.
516
+ const cut = new Set();
517
+ {
518
+ const state = new Map();
519
+ for (const start of symbolOrder) {
520
+ if (state.has(start.id))
521
+ continue;
522
+ const stack = [{ id: start.id, next: (nests.get(start.id) ?? new Set()).values() }];
523
+ state.set(start.id, "open");
524
+ while (stack.length > 0) {
525
+ const top = stack.at(-1);
526
+ const step = top.next.next();
527
+ if (step.done === true) {
528
+ state.set(top.id, "done");
529
+ stack.pop();
530
+ continue;
531
+ }
532
+ const seen = state.get(step.value);
533
+ if (seen === "open")
534
+ cut.add(`${top.id}>${step.value}`);
535
+ else if (seen === undefined) {
536
+ state.set(step.value, "open");
537
+ stack.push({ id: step.value, next: (nests.get(step.value) ?? new Set()).values() });
538
+ }
539
+ }
540
+ }
541
+ }
542
+ // A component's name for the report, which names no layer ids.
543
+ const nameOf = (symbolId) => JSON.stringify(tree.nodes.get(symbolId)?.name || "Component");
544
+ const linkOf = (node) => {
545
+ const chain = [];
546
+ for (let at = node; at !== undefined && at.type !== "DOCUMENT"; at = at.parentId === undefined ? undefined : tree.nodes.get(at.parentId))
547
+ chain.push(at);
548
+ let link = null;
549
+ for (let i = chain.length - 1; i >= 0; i--)
550
+ link = { node: chain[i], parent: link };
551
+ return link;
552
+ };
553
+ // Converts a layer on its own for instance overrides: no children, no reports, its own vector budget. The same layer with the
554
+ // same override fields is converted once, so instances that repeat an override spend no more of the budget.
555
+ const aloneCommands = { left: limits.vectorCommands, limit: limits.vectorCommands };
556
+ const convertAloneOnce = (node, fields, shownBy) => {
557
+ const converter = node.type === "INSTANCE" || node.type === "SYMBOL" ? convertFrame : converterFor(node.type);
558
+ if (converter === undefined)
559
+ return null;
560
+ let leftOut = false;
561
+ const converted = converter(node, {
562
+ newId: () => "override", convertChildren: () => [], blob, image, vectorCommands: aloneCommands, textStyle: textStyleFor(null), styleList, ...trackPaints, ...variableNumberOf(node, shownBy),
563
+ ...(native && { plainTextPaint: (range) => range?.["fillPaints"] !== undefined || range?.["styleIdForFill"] !== undefined
564
+ ? fields["textData"] !== undefined : fields["fillPaints"] !== undefined || fields["styleIdForFill"] !== undefined }),
565
+ report: (kind) => { if (kind === "node-left-out")
566
+ leftOut = true; },
567
+ });
568
+ return leftOut ? null : converted;
569
+ };
570
+ const aloneCache = new Map();
571
+ const convertAlone = (node, fields = {}, shownBy) => {
572
+ let byFields = aloneCache.get(node);
573
+ if (byFields === undefined)
574
+ aloneCache.set(node, byFields = new Map());
575
+ // An instance's modes may give a bound line height another value, so each instance converts the layer once.
576
+ const key = shownBy === undefined ? JSON.stringify(fields) : `${shownBy.instance.id}\u0000${JSON.stringify(fields)}`;
577
+ const cached = byFields.get(key);
578
+ if (cached) {
579
+ // Equal override values reuse geometry, but each occurrence has its own source lists.
580
+ if (native && fields !== cached.fields) {
581
+ for (const list of ["fillPaints", "strokePaints"]) {
582
+ const original = cached.fields[list], current = fields[list];
583
+ const indices = Array.isArray(original) && paintIndices.get(original);
584
+ if (indices && Array.isArray(current))
585
+ paintIndices.set(current, indices);
586
+ }
587
+ const original = cached.fields["effects"], current = fields["effects"];
588
+ if (Array.isArray(original) && Array.isArray(current))
589
+ original.forEach((effect, i) => {
590
+ const path = effectFields.get(effect);
591
+ if (path)
592
+ effectFields.set(current[i], path);
593
+ });
594
+ }
595
+ return cached.layer;
596
+ }
597
+ const converted = convertAloneOnce(Object.keys(fields).length === 0 ? node : { ...node, change: { ...node.change, ...fields } }, fields, shownBy);
598
+ byFields.set(key, { layer: converted, fields });
599
+ return converted;
600
+ };
601
+ // The bindings a layer would take, for instance overrides: the same reasons as `bindLayerVariables`, on a copy.
602
+ const bindingsOf = (layer, figma, shownBy) => {
603
+ const copy = { ...layer };
604
+ let leftOut;
605
+ let approximated;
606
+ bindLayerVariables(copy, figma, variables, (kind, reason) => {
607
+ if (kind === "property-left-out")
608
+ leftOut = reason;
609
+ else if (kind === "approximated")
610
+ approximated = reason;
611
+ }, [], shownBy, styleList);
612
+ const bindings = (copy.variableBindings ?? {});
613
+ return { bindings, ...(leftOut === undefined ? {} : { leftOut }), ...(approximated === undefined ? {} : { approximated }), layer: copy };
614
+ };
615
+ // Instances whose overrides are read once every component is imported.
616
+ // `walk` and `depth` are the component walk and depth the instance was met at, for the content it puts in slots.
617
+ const instances = [];
618
+ const instanceOf = (frame, componentId) => {
619
+ const { type: _type, children: _children, layout: _layout, clipContent: _clip, style: _style, ...placement } = frame;
620
+ return { ...placement, type: "instance", componentId };
621
+ };
622
+ const stack = [];
623
+ // Every node converted, by any walk (page or component), for the variable bindings once stacks are settled.
624
+ const everyImported = [];
625
+ const omittedSubtrees = new Set();
626
+ /** Runs the steps on `stack` until it is empty. `walkVisited` holds the nodes this walk imported; `imported` the converted node of each. */
627
+ // Moondraft patch 0010: whether the walk places a node in a horizontal or vertical stack it imported (a grid imports
628
+ // as absolute, and a root has no imported parent), and the node is not absolute in it.
629
+ const inAutoLayoutFlow = (step) => step.inStack === true && step.node.change["stackPositioning"] !== "ABSOLUTE";
630
+ const runSteps = (walkVisited, imported, rootList) => {
631
+ for (let step = stack.pop(); step !== undefined; step = stack.pop()) {
632
+ const { depth, node, component } = step;
633
+ const link = { node, parent: step.parent };
634
+ if (depth > limits.depth) {
635
+ throw new FigmaImportError("too-deep", `node ${node.id} (${pathText(link)}) is nested ${String(depth)} levels deep, over the limit of ${String(limits.depth)} (limits.depth)`);
636
+ }
637
+ if (walkVisited.has(node.id)) {
638
+ add(link, "node-left-out", "already imported as part of another copied node");
639
+ continue;
640
+ }
641
+ if (isSlotContent(node) && step.host !== true) {
642
+ omittedSubtrees.add(step.source ?? node);
643
+ add(link, "node-left-out", "a slot's content frame is imported only as the content of the instances that put it in a slot");
644
+ continue;
645
+ }
646
+ walkVisited.add(node.id);
647
+ // A parent is converted before its children, so a parent with a layer has it by now.
648
+ if (skipStyle(node) || native && (node.type === "VARIABLE" || node.type === "VARIABLE_SET"))
649
+ continue;
650
+ const parentLayer = step.parent === null || !Object.hasOwn(layerIds, step.parent.node.id) ? undefined : layerIds[step.parent.node.id];
651
+ // A left-out node takes the layers inside it along; the reason says how many.
652
+ const leaveOut = (reason) => {
653
+ omittedSubtrees.add(step.source ?? node);
654
+ if (parentLayer !== undefined && !Object.hasOwn(layerIds, node.id))
655
+ layerIds[node.id] = parentLayer;
656
+ const inside = node.children.length === 0 ? 0 : countLayersInside(node, insideCache);
657
+ add(link, "node-left-out", inside === 0 ? reason : `${reason}; ${layersText(inside)} left out with it`, true);
658
+ };
659
+ const isRoot = component !== undefined && depth === 1;
660
+ let converted;
661
+ let childIds;
662
+ if (node.type === "SYMBOL" && !isRoot) {
663
+ // A component placed on a page shows there as an instance of it.
664
+ const frame = convertAlone(node);
665
+ const componentId = componentIds.get(node.id);
666
+ if (frame?.type !== "frame" || componentId === undefined) {
667
+ leaveOut("the component has no complete size or transform");
668
+ continue;
669
+ }
670
+ if (component !== undefined && cut.has(`${component.symbolId}>${node.id}`)) {
671
+ leaveOut(`the component ${nameOf(node.id)} contains an instance of the component it is in, which would nest a component in itself`);
672
+ continue;
673
+ }
674
+ converted = { ...instanceOf(frame, componentId), id: options.idSource() };
675
+ if (rootSource === "pages" && component === undefined)
676
+ placements.set(converted.id, node.id);
677
+ }
678
+ else if (node.type === "INSTANCE") {
679
+ const symbolId = shownSymbol(node);
680
+ const componentId = symbolId === undefined ? undefined : componentIds.get(symbolId);
681
+ if (symbolId === undefined) {
682
+ leaveOut("the instance names no component (symbolData.symbolID)");
683
+ continue;
684
+ }
685
+ if (componentId === undefined) {
686
+ leaveOut(tree.nodes.get(symbolId)?.type === "SYMBOL" ? `its component ${symbolId} has no complete size or transform`
687
+ : `its component ${symbolId} is not in the message`);
688
+ continue;
689
+ }
690
+ if (component !== undefined && cut.has(`${component.symbolId}>${symbolId}`)) {
691
+ leaveOut(`its component ${nameOf(symbolId)} contains an instance of the component it is in, which would nest a component in itself`);
692
+ continue;
693
+ }
694
+ const frame = convertFrame(node, {
695
+ ...(native && { ...trackPaints, styleList, ...variableNumberOf(node) }),
696
+ newId: () => options.idSource(), convertChildren: () => [], blob, image, vectorCommands,
697
+ report: (kind, reason) => (kind === "node-left-out" ? leaveOut(reason) : add(link, kind, reason)),
698
+ });
699
+ if (frame?.type !== "frame")
700
+ continue;
701
+ const stub = instanceOf(frame, componentId);
702
+ instances.push({ stub: stub, figma: node, self: frame, owner: component?.symbolId, link, walk: component, depth, fills: slotFillsOf(node), slotFills: [] });
703
+ converted = stub;
704
+ }
705
+ else {
706
+ const converter = node.type === "SYMBOL" ? convertFrame : converterFor(node.type);
707
+ if (converter === undefined) {
708
+ leaveOut(`Figma node type "${node.type}" is not imported yet`);
709
+ continue;
710
+ }
711
+ converted = converter(node, {
712
+ newId: () => options.idSource(),
713
+ convertChildren: () => (childIds ??= []),
714
+ inFlow: inAutoLayoutFlow(step),
715
+ report: (kind, reason) => (kind === "node-left-out" ? leaveOut(reason) : add(link, kind, reason)),
716
+ blob,
717
+ image,
718
+ vectorCommands,
719
+ textStyle: textStyleFor(link),
720
+ styleList, ...trackPaints,
721
+ ...variableNumberOf(node),
722
+ });
723
+ }
724
+ if (converted === null)
725
+ continue;
726
+ carryMarks(converted);
727
+ if (step.inSection === true)
728
+ clearConstraints(converted);
729
+ let slotFrame = step.inSlotFrame === true;
730
+ if (component !== undefined && step.content === true)
731
+ inComponents.add(node.id);
732
+ else if (component !== undefined) {
733
+ inComponents.add(node.id);
734
+ const slot = slotBindingOf(node, converted, isRoot, slotFrame, component.properties, (kind, reason) => addCounted(link, kind, reason));
735
+ if (slot !== undefined) {
736
+ Object.assign(converted, { slot });
737
+ slotFrame = true;
738
+ }
739
+ const key = overrideKeyOf(node);
740
+ if (!component.layers.has(key))
741
+ component.layers.set(key, { figma: node, node: converted });
742
+ if (node.type === "BOOLEAN_OPERATION" && childIds === undefined) {
743
+ // A flattened one's operands are not layers, so an override of one names the boolean operation in its report line.
744
+ const operands = [...node.children];
745
+ for (let i = 0; i < operands.length; i++) {
746
+ const operand = operands[i];
747
+ const operandKey = overrideKeyOf(operand);
748
+ if (!component.flattened.has(operandKey))
749
+ component.flattened.set(operandKey, node.name);
750
+ operands.push(...operand.children);
751
+ }
752
+ }
753
+ const expressions = propertyExpressions(node, isRoot, component.properties, (kind, reason) => addCounted(link, kind, reason));
754
+ if (Object.keys(expressions).length > 0)
755
+ Object.assign(converted, { expressions: { ...converted.expressions, ...expressions } });
756
+ const swapProperty = expressions["componentId"] === undefined ? undefined : component.properties.find((property) => formatExpressionName(property.definition.name) === expressions["componentId"]);
757
+ if (swapProperty !== undefined)
758
+ component.boundSwaps.add(swapProperty.definition.id);
759
+ }
760
+ nodes.push(converted);
761
+ // Every layer built counts against limits.nodes: a component's layers once, and each instance as one layer.
762
+ if (nodes.length > limits.nodes) {
763
+ throw new FigmaImportError("too-many-nodes", `the import has built ${String(nodes.length)} layers from ${String(tree.nodes.size)} node changes, over the limit of ${String(limits.nodes)} for ${rootSource === "pages" ? "a whole file" : "a paste"}; raise options.limits.nodes to import it`);
764
+ }
765
+ if (!Object.hasOwn(layerIds, node.id) || isRoot)
766
+ layerIds[node.id] = converted.id;
767
+ // Keyed by the message's own node, which is what a stack's `children` list holds.
768
+ imported.set(step.source ?? step.node, { node: converted, figma: node, link });
769
+ everyImported.push({ node: converted, figma: node, link });
770
+ if (converted.type === "frame" && converted.layout.kind !== "absolute")
771
+ stacks.push({ node: converted, figma: node, link, imported });
772
+ step.into.push(converted.id);
773
+ if (step.into === rootList)
774
+ roots.push(converted);
775
+ if (childIds === undefined) {
776
+ if (node.type === "BOOLEAN_OPERATION") {
777
+ for (const child of node.children)
778
+ omittedSubtrees.add(child);
779
+ const why = whyFlattened(node, inAutoLayoutFlow(step));
780
+ add(link, "approximated", `the boolean operation is flattened to its outline; its operands are not imported${why === undefined ? "" : `: ${why}`}`, true);
781
+ }
782
+ else if (node.children.length > 0 && node.type !== "INSTANCE" && node.type !== "SYMBOL") {
783
+ for (const child of node.children)
784
+ omittedSubtrees.add(child);
785
+ add(link, "property-left-out", `${layersText(countLayersInside(node, insideCache))} left out: a ${node.type} has no children in Taco`, true);
786
+ }
787
+ continue;
788
+ }
789
+ const inSection = node.type === "SECTION" || (step.inSection === true && converted.type === "group");
790
+ const inStack = converted.type === "frame" && converted.layout.kind !== "absolute";
791
+ for (let i = node.children.length - 1; i >= 0; i--) {
792
+ stack.push({
793
+ node: node.children[i], depth: depth + 1, parent: link, into: childIds, inSection, ...(component !== undefined ? { component } : {}),
794
+ ...(step.content === true ? { content: true } : {}), ...(slotFrame ? { inSlotFrame: true } : {}), ...(inStack ? { inStack: true } : {}),
795
+ });
796
+ }
797
+ }
798
+ };
799
+ // The components first, so instances can name their layers.
800
+ const components = [];
801
+ const importedComponents = new Map();
802
+ const componentOf = (symbolId) => componentIds.get(symbolId);
803
+ const componentsByKey = componentsByKeyOf(tree.nodes, componentOf);
804
+ // A file's keys follow its Figma nodes, so converting it again gives the same keys; a paste's are random (see `componentKeySource`).
805
+ const takenKeys = new Set();
806
+ const keySource = options.componentKeySource ?? (rootSource === "pages" ? ({ figmaId, componentKey }) => {
807
+ const key = componentKey !== undefined && !takenKeys.has(componentKey) ? componentKey : `figma-${figmaId}`;
808
+ takenKeys.add(key);
809
+ return key;
810
+ } : () => globalThis.crypto.randomUUID());
811
+ const keyOf = (node) => {
812
+ const componentKey = field(node.change, "componentKey", "string", `node ${node.id}`);
813
+ return keySource({ figmaId: node.id, ...(componentKey === undefined || componentKey === "" ? {} : { componentKey }) });
814
+ };
815
+ const setOf = (symbol) => {
816
+ const owner = symbol.parentId === undefined ? undefined : tree.nodes.get(symbol.parentId);
817
+ return owner?.change["isStateGroup"] === true ? owner : undefined;
818
+ };
819
+ // A component's name without the parts that only list variant values; one with nothing else takes its set's name.
820
+ const componentNameOf = (node) => {
821
+ const name = withoutVariantParts(node.name);
822
+ const set = name === "" ? setOf(node) : undefined;
823
+ return name !== "" ? name : set !== undefined ? componentNameOf(set) : "Component";
824
+ };
825
+ const setProperties = new Map();
826
+ // The property defs whose dropped preferred values are already reported (`propertiesOf`).
827
+ const reportedDefs = new WeakSet();
828
+ for (const symbol of symbolOrder) {
829
+ const symbolLink = linkOf(symbol);
830
+ const report = (kind, reason) => addCounted(symbolLink, kind, reason);
831
+ const properties = propertiesOf(symbol, tree.nodes, componentOf, componentsByKey, report, reportedDefs);
832
+ const set = native && setOf(symbol);
833
+ if (set) {
834
+ let shared = setProperties.get(set);
835
+ if (!shared) {
836
+ shared = propertiesOf(set, tree.nodes, componentOf, componentsByKey, (kind, reason) => add(variableLinkOf(set), kind, reason), reportedDefs);
837
+ setProperties.set(set, shared);
838
+ }
839
+ const own = new Set(properties.map(p => p.definition.id));
840
+ properties.push(...shared.filter(p => !own.has(p.definition.id)));
841
+ }
842
+ const walk = { symbolId: symbol.id, properties, layers: new Map(), boundSwaps: new Set(), flattened: new Map() };
843
+ const into = [];
844
+ stack.push({ node: symbol, depth: 1, parent: symbolLink.parent, into, component: walk });
845
+ // The SYMBOL's step runs first, so its root is the first node this walk adds.
846
+ const first = nodes.length;
847
+ runSteps(new Set(), new Map(), null);
848
+ const root = into.length === 0 ? undefined : nodes[first];
849
+ // `want` only takes a SYMBOL whose root `convertFrame` converts.
850
+ if (root?.type !== "frame")
851
+ throw new Error(`component ${symbol.id} has no root frame after its walk`);
852
+ // A component root sits at 0, 0 unturned; the instance on the page carries the placement.
853
+ Object.assign(root, { frame: { ...root.frame, x: 0, y: 0 }, rotation: 0 });
854
+ delete root.flipX;
855
+ delete root.flipY;
856
+ const componentId = componentIds.get(symbol.id);
857
+ components.push({
858
+ id: componentId, key: keyOf(symbol), name: componentNameOf(symbol), rootId: root.id,
859
+ ...(properties.length > 0 ? { properties: properties.map((property) => property.definition) } : {}),
860
+ });
861
+ importedComponents.set(symbol.id, {
862
+ symbol, componentId, root, properties, variantDefs: variantDefIds(symbol, tree.nodes), layers: walk.layers, boundSwaps: walk.boundSwaps, flattened: walk.flattened,
863
+ });
864
+ }
865
+ // An internal-only page is not imported, but the components on it that imported layers use are.
866
+ for (const page of chosen.internalPages) {
867
+ let used = 0;
868
+ for (const { symbol } of importedComponents.values()) {
869
+ let top = linkOf(symbol);
870
+ while (top?.parent != null)
871
+ top = top.parent;
872
+ if (top?.node === page)
873
+ used += 1;
874
+ }
875
+ if (used === 0) {
876
+ add({ node: page, parent: null }, "node-left-out", `internal-only page; it and ${layersText(countLayersInside(page, insideCache))} are never imported`, true);
877
+ }
878
+ else {
879
+ add({ node: page, parent: null }, "node-left-out", `internal-only page; it is not imported, apart from the ${String(used)} component${used === 1 ? "" : "s"} on it that imported layers use`);
880
+ }
881
+ }
882
+ const ancestorTransforms = new Map();
883
+ const pageImported = new Map();
884
+ for (const group of chosen.groups) {
885
+ const pageRoots = [];
886
+ const parent = group.page === null ? null : { node: group.page, parent: null };
887
+ // Copied roots may sit inside frames of the message; page roots already sit on their page.
888
+ const rootNode = (root) => (group.page === null ? withAncestorTransforms(root, tree, ancestorTransforms) : root);
889
+ for (let i = group.roots.length - 1; i >= 0; i--) {
890
+ const root = group.roots[i];
891
+ stack.push({ node: rootNode(root), depth: 1, parent, into: pageRoots, source: root });
892
+ }
893
+ runSteps(visited, pageImported, pageRoots);
894
+ if (group.page !== null) {
895
+ const left = [];
896
+ const variableModes = figmaVariableModes(group.page, variables, left);
897
+ if (native)
898
+ for (const _ of left)
899
+ add({ node: group.page, parent: null }, "property-left-out", "variable mode");
900
+ else if (left.length > 0)
901
+ add({ node: group.page, parent: null }, "property-left-out", `variable modes left out: ${left.join("; ")}`);
902
+ pages.push({ figmaId: group.page.id, name: group.page.name, roots: pageRoots, ...(Object.keys(variableModes).length > 0 ? { variableModes } : {}) });
903
+ }
904
+ }
905
+ // The content each instance puts in a slot, converted into a slot host: the content frame becomes the host and its children
906
+ // the content. Instances met in content come after, so their content is converted too. Each fill converts its content again,
907
+ // so two instances that share a content frame get copies with their own ids. `instanceFields` links the hosts.
908
+ const slotContents = new Set();
909
+ for (let index = 0; index < instances.length; index++) {
910
+ const entry = instances[index];
911
+ for (const fill of entry.fills) {
912
+ const content = tree.nodes.get(fill.contentId);
913
+ if (content === undefined || !isSlotContent(content) || content.type !== "FRAME") {
914
+ addCounted(entry.link, "property-left-out", "the content placed in a slot is not in the message; the slot shows its component's own layers");
915
+ continue;
916
+ }
917
+ slotContents.add(content.id);
918
+ const into = [];
919
+ const first = everyImported.length;
920
+ const hadLayer = Object.hasOwn(layerIds, content.id);
921
+ stack.push({ node: content, depth: entry.depth + 1, parent: entry.link, into, content: true, host: true, ...(entry.walk === undefined ? {} : { component: entry.walk }) });
922
+ runSteps(new Set(), new Map(), null);
923
+ const host = everyImported[first]?.node;
924
+ if (into.length === 0 || host?.type !== "frame")
925
+ continue;
926
+ Object.assign(host, { slotHost: true });
927
+ // The content frame is no layer: its own fields go on the slot frame as overrides, and the host takes no bindings.
928
+ everyImported.splice(first, 1);
929
+ if (!hadLayer)
930
+ delete layerIds[content.id];
931
+ entry.slotFills.push({ keys: fill.keys, defId: fill.defId, host, content });
932
+ }
933
+ }
934
+ const finished = instances.map((entry) => ({ ...entry, refusedSwaps: new Map(), swaps: new Set(), nested: new Map(), heldSizing: new Map(), filledSlots: [], said: [] }));
935
+ const nodeRecord = Object.fromEntries(nodes.map((node) => [node.id, node]));
936
+ const occurrenceFields = new Map();
937
+ const instanceBoxes = new Map();
938
+ const instanceFillSizes = new Map();
939
+ // Resolve inherited swaps by imported layer IDs. A holder can be finished later in file order or lose a
940
+ // swap in the cycle check. Revisit just the instances that consulted a path whose answer changed.
941
+ const pathSwaps = new Map();
942
+ const readers = new Map();
943
+ let sourceOverrideKeys;
944
+ const hasSourceKey = (key) => {
945
+ if (tree.nodes.has(key))
946
+ return true;
947
+ if (!sourceOverrideKeys) {
948
+ sourceOverrideKeys = new Set();
949
+ for (const node of tree.nodes.values()) {
950
+ const guid = node.change["overrideKey"];
951
+ if (isObject(guid) && Number.isInteger(guid["sessionID"]) && Number.isInteger(guid["localID"]))
952
+ sourceOverrideKeys.add(overrideKeyOf(node));
953
+ }
954
+ }
955
+ return sourceOverrideKeys.has(key);
956
+ };
957
+ const finish = (entry, pending) => {
958
+ const { stub, figma, self, link, refusedSwaps, said } = entry;
959
+ const component = importedComponents.get(shownSymbol(figma));
960
+ if (component === undefined)
961
+ return;
962
+ said.length = 0;
963
+ delete stub["overrides"];
964
+ delete stub["propertyValues"];
965
+ delete stub["slots"];
966
+ const fields = new Map();
967
+ const made = instanceFields(figma, component, self, {
968
+ ...(native && {
969
+ fileOverride(path, change) {
970
+ fields.set(path, { ...fields.get(path), ...change });
971
+ },
972
+ fileLayout(boxes, fillOnly) {
973
+ const id = stub["id"];
974
+ instanceBoxes.delete(id);
975
+ instanceFillSizes.delete(id);
976
+ if (boxes.size)
977
+ (fillOnly ? instanceFillSizes : instanceBoxes).set(id, boxes);
978
+ },
979
+ }),
980
+ slotFills: entry.slotFills,
981
+ component: (symbolId) => importedComponents.get(symbolId),
982
+ refusedSwaps,
983
+ hasSourceKey,
984
+ nestedSwaps(holder, path) {
985
+ let paths = readers.get(holder);
986
+ if (!paths)
987
+ readers.set(holder, paths = new Map());
988
+ let used = paths.get(path);
989
+ if (!used)
990
+ paths.set(path, used = new Set());
991
+ used.add(entry);
992
+ return pathSwaps.get(holder)?.get(path);
993
+ },
994
+ nodes: nodeRecord,
995
+ convertAlone,
996
+ bindingsOf,
997
+ report: (kind, reason) => said.push(() => addCounted(link, kind, reason)),
998
+ hasTextStyle: (reference) => textStyleNode(reference)?.change["styleType"] === "TEXT",
999
+ styleList,
1000
+ bindsLineHeight: (layer) => {
1001
+ const textData = layer.change["textData"];
1002
+ const table = isObject(textData) && Array.isArray(textData["styleOverrideTable"]) ? textData["styleOverrideTable"] : [];
1003
+ return [layer.change, ...table].some((fields) => isObject(fields) && (bindsField(fields, "LINE_HEIGHT")
1004
+ || bindsField(textStyleNode(fields["styleIdForText"])?.change ?? {}, "LINE_HEIGHT")));
1005
+ },
1006
+ leftOutField: (name) => said.push(() => {
1007
+ if (native) {
1008
+ add(link, "property-left-out", `override field "${name}" is not imported`);
1009
+ return;
1010
+ }
1011
+ const seen = leftOutFields.get(name);
1012
+ if (seen === undefined)
1013
+ leftOutFields.set(name, { link, count: 1 });
1014
+ else
1015
+ seen.count += 1;
1016
+ }),
1017
+ });
1018
+ if (fields.size)
1019
+ occurrenceFields.set(stub["id"], fields);
1020
+ else
1021
+ occurrenceFields.delete(stub["id"]);
1022
+ const holder = nodeRecord[stub["id"]];
1023
+ const previous = pathSwaps.get(holder);
1024
+ pathSwaps.set(holder, made.pathSwaps);
1025
+ for (const [path, used] of readers.get(holder) ?? []) {
1026
+ const before = previous?.get(path), after = made.pathSwaps.get(path);
1027
+ if (before?.symbol !== after?.symbol || JSON.stringify(before?.properties) !== JSON.stringify(after?.properties)) {
1028
+ for (const reader of used)
1029
+ pending.add(reader);
1030
+ }
1031
+ }
1032
+ Object.assign(stub, made.fields);
1033
+ entry.swaps = made.swaps;
1034
+ entry.nested = made.nested;
1035
+ entry.heldSizing = made.heldSizing;
1036
+ entry.filledSlots = made.filledSlots;
1037
+ };
1038
+ const finishAll = (pending) => {
1039
+ const touched = new Set();
1040
+ for (const entry of pending) {
1041
+ pending.delete(entry);
1042
+ finish(entry, pending);
1043
+ touched.add(entry);
1044
+ }
1045
+ return touched;
1046
+ };
1047
+ finishAll(new Set(finished));
1048
+ // The nesting check, over the walks that resolving a component or a page instance can take from a component into another
1049
+ // (`nestingSearch`): through the instances placed inside components, and through each swap an instance makes by an override
1050
+ // or an instance swap property value, from the component whose layer it swaps, while the component that holds that instance
1051
+ // (or the page instance) is on the walk. So only swaps that resolve together form a cycle. The swaps of instances inside
1052
+ // components are checked first, then each page instance's swaps against those kept, so a cycle that a page instance closes
1053
+ // costs that instance's swap, not a swap every instance of a component shows. Each cycle found loses a swap, by file order
1054
+ // (`swapsToCut`). A swap left out takes along what the instance sets inside the component that swap would show, so an
1055
+ // enclosing override may now resolve against a different component.
1056
+ {
1057
+ const symbolOf = new Map([...componentIds].map(([symbolId, componentId]) => [componentId, symbolId]));
1058
+ const kept = new Map();
1059
+ const nodesById = new Map(nodes.map((node) => [node.id, node]));
1060
+ const refreshKept = (symbolId) => {
1061
+ const targets = new Set();
1062
+ kept.set(symbolId, targets);
1063
+ const root = importedComponents.get(symbolId).root;
1064
+ for (const pending = [root.id], seen = new Set(); pending.length > 0;) {
1065
+ const id = pending.pop();
1066
+ const node = seen.has(id) ? undefined : nodesById.get(id);
1067
+ seen.add(id);
1068
+ if (node?.type === "instance")
1069
+ targets.add(symbolOf.get(node.componentId));
1070
+ if (node !== undefined)
1071
+ pending.push(...ownedChildIds(node));
1072
+ }
1073
+ };
1074
+ for (const symbolId of importedComponents.keys())
1075
+ refreshKept(symbolId);
1076
+ const order = symbolOrder.map((symbol) => symbol.id);
1077
+ const fileIndex = new Map(order.map((id, at) => [id, at]));
1078
+ const componentEntries = finished.filter((entry) => entry.owner !== undefined);
1079
+ const pageEntries = finished.filter((entry) => entry.owner === undefined);
1080
+ const pageOwners = new Map(pageEntries.map((entry, at) => [entry, `#${String(at)}`]));
1081
+ const ownerOf = (entry) => entry.owner ?? pageOwners.get(entry);
1082
+ const swapsOf = (entries) => entries.flatMap((entry) => [...entry.swaps].map((swap) => {
1083
+ const [from, to] = swap.split(">");
1084
+ return { from, to, owner: ownerOf(entry) };
1085
+ }));
1086
+ // Cuts swaps of `cutting` until no walk from `roots` (a SYMBOL, and the page instance resolved) meets a component twice.
1087
+ const check = (cutting, fixed, roots) => {
1088
+ const byOwner = new Map();
1089
+ for (const entry of cutting) {
1090
+ let list = byOwner.get(ownerOf(entry));
1091
+ if (list === undefined)
1092
+ byOwner.set(ownerOf(entry), list = []);
1093
+ list.push(entry);
1094
+ }
1095
+ let memo = nestingMemo();
1096
+ // The swaps each entry of `cutting` makes, as the search holds them.
1097
+ const made = new Map(cutting.map((entry) => [entry, swapsOf([entry])]));
1098
+ const buildSearch = () => nestingSearch(order, kept, [...fixed, ...[...made.values()].flat()]);
1099
+ let search = buildSearch();
1100
+ for (let i = 0; i < roots.length;) {
1101
+ const [root, rootOwner] = roots[i];
1102
+ const cycle = search(root, rootOwner, memo);
1103
+ if (cycle === null) {
1104
+ i++;
1105
+ continue;
1106
+ }
1107
+ const keptSteps = new Map();
1108
+ const swaps = [];
1109
+ for (const { from, to, owner } of cycle) {
1110
+ if (owner !== undefined && byOwner.has(owner))
1111
+ swaps.push(`${from}>${to}`);
1112
+ else
1113
+ keptSteps.set(from, new Set([to]));
1114
+ }
1115
+ const ids = cycle.map((step) => step.from).sort((a, b) => fileIndex.get(a) - fileIndex.get(b));
1116
+ const cut = swapsToCut(ids, keptSteps, swaps);
1117
+ if (cut.size === 0)
1118
+ throw new Error(`the nesting check found a cycle with no swap to leave out, through ${ids.map(nameOf).join(" > ")}`);
1119
+ const changed = new Set();
1120
+ for (const { from, to, owner } of cycle) {
1121
+ const swap = `${from}>${to}`;
1122
+ if (!cut.has(swap))
1123
+ continue;
1124
+ const reason = from === to ? `to ${nameOf(to)} inside ${nameOf(from)} itself is left out: it would nest a component in itself`
1125
+ : `to ${nameOf(to)} inside ${nameOf(from)} is left out: ${nameOf(to)} can contain ${nameOf(from)}, so it would nest a component in itself`;
1126
+ for (const entry of byOwner.get(owner)) {
1127
+ if (!entry.swaps.has(swap))
1128
+ continue;
1129
+ entry.refusedSwaps.set(swap, reason);
1130
+ changed.add(entry);
1131
+ }
1132
+ }
1133
+ const gone = [];
1134
+ let gained = false;
1135
+ const slotOwners = new Set();
1136
+ for (const entry of finishAll(changed)) {
1137
+ // A newly reachable slot host can contain instances even if its holder gained no swap.
1138
+ if (entry.owner !== undefined && entry.slotFills.length)
1139
+ slotOwners.add(entry.owner);
1140
+ const previous = made.get(entry);
1141
+ if (!previous)
1142
+ continue; // Page swaps are checked after the component swaps settle.
1143
+ const retained = previous.filter(swap => entry.swaps.has(`${swap.from}>${swap.to}`));
1144
+ if (retained.length < entry.swaps.size) {
1145
+ made.set(entry, swapsOf([entry]));
1146
+ gained = true;
1147
+ }
1148
+ else if (retained.length < previous.length) {
1149
+ made.set(entry, retained);
1150
+ for (const swap of previous)
1151
+ if (!entry.swaps.has(`${swap.from}>${swap.to}`))
1152
+ gone.push(swap);
1153
+ }
1154
+ }
1155
+ if (gained || slotOwners.size > 0) {
1156
+ for (const owner of slotOwners)
1157
+ refreshKept(owner);
1158
+ // A previously safe root can now reach the new edge. Its cached walk ends are stale too.
1159
+ search = buildSearch();
1160
+ memo = nestingMemo();
1161
+ i = 0;
1162
+ }
1163
+ else
1164
+ search.remove(gone);
1165
+ }
1166
+ };
1167
+ check(componentEntries, [], order.map((id) => [id, undefined]));
1168
+ check(pageEntries, swapsOf(componentEntries), pageEntries.filter((entry) => entry.swaps.size > 0).map((entry) => [shownSymbol(entry.figma), ownerOf(entry)]));
1169
+ const document = { nodes: Object.fromEntries(nodesById), components: Object.fromEntries(components.map((definition) => [definition.id, definition])) };
1170
+ const cycle = findComponentCycle(componentNestingGraph(document));
1171
+ if (cycle !== null)
1172
+ throw new Error(`the nesting check left a component inside itself, through ${cycle.map((id) => nameOf(symbolOf.get(id) ?? id)).join(" > ")}`);
1173
+ }
1174
+ for (const { said } of finished)
1175
+ for (const say of said)
1176
+ say();
1177
+ // A host no instance links (its slot was not found, or an instance around it was left out) goes, with what it holds.
1178
+ {
1179
+ const linked = new Set();
1180
+ for (const { stub } of finished)
1181
+ for (const id of ownedChildIds(stub))
1182
+ linked.add(id);
1183
+ const unlinked = finished.flatMap(({ slotFills }) => slotFills.filter(({ host }) => !linked.has(host.id)));
1184
+ const byId = unlinked.length === 0 ? new Map() : new Map(nodes.map((node) => [node.id, node]));
1185
+ const gone = new Set();
1186
+ for (const { host } of unlinked) {
1187
+ for (const pending = [host.id]; pending.length > 0;) {
1188
+ const id = pending.pop();
1189
+ const node = gone.has(id) ? undefined : byId.get(id);
1190
+ gone.add(id);
1191
+ if (node !== undefined)
1192
+ pending.push(...ownedChildIds(node));
1193
+ }
1194
+ }
1195
+ if (gone.size > 0) {
1196
+ // In place, as the lists are read below; a loop, as a spread of a large file's nodes passes too many arguments.
1197
+ const keepOnly = (list, kept) => {
1198
+ let at = 0;
1199
+ for (const item of list)
1200
+ if (kept(item))
1201
+ list[at++] = item;
1202
+ list.length = at;
1203
+ };
1204
+ keepOnly(nodes, (node) => !gone.has(node.id));
1205
+ keepOnly(everyImported, (item) => !gone.has(item.node.id));
1206
+ keepOnly(stacks, (item) => !gone.has(item.node.id));
1207
+ keepOnly(finished, ({ stub }) => !gone.has(stub["id"]));
1208
+ for (const [figmaId, layerId] of Object.entries(layerIds))
1209
+ if (gone.has(layerId))
1210
+ delete layerIds[figmaId];
1211
+ }
1212
+ }
1213
+ // A group whose frame changes when fitted to its layers (`fitGroups`) would move its stack's other children.
1214
+ const fitted = stacks.length === 0 ? {} : fitAllGroups(Object.fromEntries(nodes.map((node) => [node.id, node])));
1215
+ settleStacks(stacks, add, (node) => node.type === "group" && entryOf(fitted, node.id) !== node);
1216
+ // Fill is decided here, after resolving instance paths. Discard candidate
1217
+ // allocations for paths whose rotation or stack prevented importing Fill.
1218
+ for (const [id, boxes] of instanceFillSizes) {
1219
+ for (const path of boxes.keys()) {
1220
+ const figma = nodeRecord[parseLayerPath(path).at(-1)]?.metadata?.["figma"];
1221
+ if (!isObject(figma) || !figma["fillSizing"])
1222
+ boxes.delete(path);
1223
+ }
1224
+ if (!boxes.size)
1225
+ instanceFillSizes.delete(id);
1226
+ }
1227
+ const componentRoots = new Set([...importedComponents.values()].map(({ root }) => root.id));
1228
+ for (const { stub, heldSizing } of finished) {
1229
+ dropUnheldSizing(stub["overrides"], heldSizing);
1230
+ dropSizingWhereFilled(stub["overrides"], nodeRecord, componentRoots);
1231
+ if (Object.keys(stub["overrides"] ?? {}).length === 0)
1232
+ delete stub["overrides"];
1233
+ }
1234
+ // After `settleStacks`, which gives a slot frame its Fill sizing.
1235
+ for (const { filledSlots, link } of finished) {
1236
+ for (const check of filledSlots) {
1237
+ const mismatch = slotSizeMismatch(check);
1238
+ if (mismatch !== undefined)
1239
+ addCounted(link, "approximated", mismatch);
1240
+ }
1241
+ }
1242
+ // After `settleStacks`, so that a frame whose auto layout is left off binds no gap or padding.
1243
+ // An instance binds on its own only what Taco instances keep of their own; the rest of its root is an override, below.
1244
+ const leftOutBindings = new Map();
1245
+ for (const { node, figma, link } of everyImported) {
1246
+ if (node.type === "instance")
1247
+ continue;
1248
+ bindLayerVariables(node, figma, variables, (kind, reason) => {
1249
+ if (kind === "property-left-out")
1250
+ leftOutBindings.set(node, reason);
1251
+ add(link, kind, reason);
1252
+ }, [], undefined, styleList);
1253
+ }
1254
+ for (const { stub, figma, self, link } of finished) {
1255
+ const component = importedComponents.get(shownSymbol(figma));
1256
+ if (component === undefined)
1257
+ continue;
1258
+ const { bindings, leftOut, layer: boundSelf } = bindingsOf(self, figma);
1259
+ if (leftOut !== undefined && leftOut !== leftOutBindings.get(component.root))
1260
+ add(link, "property-left-out", leftOut);
1261
+ const own = {};
1262
+ const rootBindings = {};
1263
+ const rootBound = (component.root.variableBindings ?? {});
1264
+ const rootKey = layerPathKey([component.root.id]);
1265
+ const overrides = stub["overrides"];
1266
+ const rootOverride = overrides?.[rootKey];
1267
+ // The instance's own bound fill or stroke had the variable's alpha folded from its opacity, as its component's root
1268
+ // had, so the override takes the folded paints, and none where they match the root's.
1269
+ if (rootOverride !== undefined && "style" in boundSelf) {
1270
+ for (const name of ["fills", "strokes"]) {
1271
+ const folded = boundSelf.style?.[name];
1272
+ if (rootOverride[name] === undefined || folded === undefined)
1273
+ continue;
1274
+ if (JSON.stringify(folded, withImageCrop) === JSON.stringify(component.root.style?.[name] ?? [], withImageCrop))
1275
+ delete rootOverride[name];
1276
+ else
1277
+ rootOverride[name] = folded;
1278
+ }
1279
+ if (Object.keys(rootOverride).length === 0)
1280
+ delete overrides[rootKey];
1281
+ }
1282
+ // The model drops a root binding of a field the root override sets, so each of those is written, kept or `null`.
1283
+ const dropped = bindingsDroppedBy(rootOverride ?? {});
1284
+ for (const property of new Set([...Object.keys(bindings), ...Object.keys(rootBound)])) {
1285
+ const bound = bindings[property];
1286
+ if (INSTANCE_OWN_BINDINGS.has(property)) {
1287
+ if (bound !== undefined)
1288
+ own[property] = bound;
1289
+ // The drawn instance takes its root's bindings under its own, so one it does not keep is unbound at the root.
1290
+ else if (rootBound[property] !== undefined)
1291
+ rootBindings[property] = null;
1292
+ }
1293
+ else if (dropped.has(property) || (bound !== undefined && bound !== rootBound[property])) {
1294
+ // Elsewhere a root binding goes only where the instance binds the field; the component's holds otherwise.
1295
+ rootBindings[property] = bound ?? null;
1296
+ }
1297
+ }
1298
+ if (Object.keys(own).length > 0)
1299
+ stub["variableBindings"] = own;
1300
+ const modes = figmaVariableModes(figma, variables, []);
1301
+ if (Object.keys(modes).length > 0)
1302
+ stub["variableModes"] = modes;
1303
+ if (Object.keys(rootBindings).length > 0) {
1304
+ const at = rootOverride ?? {};
1305
+ stub["overrides"] = { ...overrides, [rootKey]: { ...at, variableBindings: { ...at["variableBindings"], ...rootBindings } } };
1306
+ }
1307
+ }
1308
+ // After every instance has its overrides and root bindings, which an override of a layer inside a nested instance reads.
1309
+ for (const { stub, nested } of finished)
1310
+ unbindInnerBindings(stub["overrides"], nested);
1311
+ for (const [name, { link, count }] of leftOutFields) {
1312
+ add(link, "property-left-out", `override field "${name}" is not imported yet; left out of ${String(count)} override${count === 1 ? "" : "s"}, first in this instance`);
1313
+ }
1314
+ // The literal reader merges variant trees. The native file adapter needs the original member mains.
1315
+ const fittedNodes = fitAllGroups(Object.fromEntries(nodes.map((node) => [node.id, node])));
1316
+ if (instanceBoxes.size && nodes.some(node => node.type === "group")) {
1317
+ fitInstanceBoxes(instanceBoxes, nodeRecord, fittedNodes);
1318
+ }
1319
+ const fittedList = nodes.map((node) => entryOf(fittedNodes, node.id) ?? node);
1320
+ const distinct = distinctSources?.(tree);
1321
+ const sets = native ? { nodes: fittedList, components, layerOf: new Map(), componentOf: new Map() } : mergeComponentSets({
1322
+ theme: {
1323
+ defaultTextStyleId: "figma-import-default",
1324
+ defaultCodeStyleId: "",
1325
+ colors: {}, nodeStyles: {}, codeStyles: {}, variableCollections: variables?.collections ?? {},
1326
+ textStyles: { "figma-import-default": figmaTextStyle({}, "Default", () => undefined, "component sets"), ...textStyles },
1327
+ },
1328
+ nodes: fittedList, components, figmaNodes: tree.nodes, newId: () => options.idSource(), keyOf, nameOf: componentNameOf,
1329
+ ...(distinct?.size && { distinctLayers: new Set(everyImported.filter(({ figma }) => distinct.has(figma.id)).map(({ node }) => node.id)) }),
1330
+ variants: [...importedComponents.values()].map(({ symbol, componentId, root }) => ({ symbol, componentId, root })),
1331
+ report: (node, kind, reason) => addCounted(linkOf(node), kind, reason),
1332
+ });
1333
+ const variants = new Map();
1334
+ const styleLayers = new Map();
1335
+ if (native)
1336
+ for (const node of tree.nodes.values()) {
1337
+ if (node.change["isStateGroup"] === true) {
1338
+ const members = node.children.flatMap(child => importedComponents.get(child.id) ?? []);
1339
+ if (!members.length && !node.change["componentPropDefs"])
1340
+ continue;
1341
+ const plan = planSet(node, members);
1342
+ if (typeof plan === "string")
1343
+ add(variableLinkOf(node), "approximated", plan);
1344
+ else
1345
+ variants.set(node.id, { plan, properties: setProperties.get(node) ?? propertiesOf(node, tree.nodes, componentOf, componentsByKey, (kind, reason) => add(variableLinkOf(node), kind, reason), reportedDefs) });
1346
+ }
1347
+ const type = node.change["styleType"];
1348
+ if (type === "TEXT")
1349
+ textStyleFor(null)({ guid: node.change["guid"] });
1350
+ if (type === "FILL" || type === "EFFECT") {
1351
+ const walk = { newId: () => options.idSource(), convertChildren: () => [], blob, image, vectorCommands,
1352
+ report: (kind, reason) => add(variableLinkOf(node), kind, reason), ...trackPaints, ...variableNumberOf(node) };
1353
+ const size = field(node.change, "size", "object", node.id);
1354
+ const frame = { id: walk.newId(), type: "frame", name: node.name, visible: true, locked: false, opacity: 1, rotation: 0,
1355
+ frame: { x: 0, y: 0, width: Number(size?.["x"] ?? 1), height: Number(size?.["y"] ?? 1) },
1356
+ children: [], layout: { kind: "absolute" }, clipContent: false,
1357
+ style: type === "FILL" ? visualStyle(size ? node : { ...node, change: { ...node.change, size: { x: 1, y: 1 } } }, walk) : nodeEffects(node, walk, true) };
1358
+ carryMarks(frame);
1359
+ styleLayers.set(node.id, frame);
1360
+ }
1361
+ }
1362
+ for (const { link, kind, reason, count } of counted.values()) {
1363
+ add(link, kind, count === 1 ? reason : `${reason} (${String(count)} times, first here)`);
1364
+ }
1365
+ for (const orphan of tree.orphans) {
1366
+ if (skipStyle(orphan) || visited.has(orphan.id) || inComponents.has(orphan.id) || slotContents.has(orphan.id) || orphan.type === "VARIABLE" || orphan.type === "VARIABLE_SET")
1367
+ continue;
1368
+ const reason = orphan.parentId === undefined ? "the node has no parentIndex" : `its parent ${orphan.parentId} is not in the message`;
1369
+ add({ node: orphan, parent: null }, "node-left-out", `${reason}; it and ${layersText(countLayersInside(orphan, insideCache))} are not imported`, true);
1370
+ }
1371
+ for (const [figmaId, layerId] of Object.entries(layerIds))
1372
+ layerIds[figmaId] = sets.layerOf.get(layerId) ?? layerId;
1373
+ const mergedById = new Map(sets.nodes.map((node) => [node.id, node]));
1374
+ const componentGuids = {};
1375
+ for (const [symbolId, componentId] of componentIds)
1376
+ if (importedComponents.has(symbolId))
1377
+ componentGuids[symbolId] = sets.componentOf.get(symbolId) ?? componentId;
1378
+ for (const [figmaId, componentId] of sets.componentOf)
1379
+ componentGuids[figmaId] = componentId;
1380
+ const componentPlacements = Object.fromEntries([...placements].flatMap(([layer, symbol]) => sets.componentOf.has(symbol) ? [] : [[layer, componentGuids[symbol]]]));
1381
+ return {
1382
+ sources: { variables, variants, tree, styleLayers, styleNodeFor, textStyleUses, paintIndices, effectFields, occurrenceFields, instanceBoxes, instanceFillSizes, imported: everyImported, omittedSubtrees },
1383
+ result: {
1384
+ rootSource, roots: roots.map((root) => mergedById.get(root.id) ?? root), nodes: sets.nodes, pages, report, assets, layerIds, components: sets.components, componentIds: componentGuids, componentPlacements,
1385
+ variableCollections: variables?.collections ?? {}, textStyles,
1386
+ },
1387
+ };
1388
+ }
1389
+ /** Rebase Figma's boxes into the local coordinates of the fitted groups. */
1390
+ function fitInstanceBoxes(instanceBoxes, original, fitted) {
1391
+ const parents = buildParentMap(original);
1392
+ const origins = new Map();
1393
+ function groupOrigin(id) {
1394
+ if (id === undefined || original[id]?.type !== "group")
1395
+ return [0, 0];
1396
+ const found = origins.get(id);
1397
+ if (found)
1398
+ return found;
1399
+ const [a, b, c, d, x, y] = nodeLocalTransform(original[id]);
1400
+ const [, , , , fittedX, fittedY] = nodeLocalTransform(fitted[id]);
1401
+ const [px, py] = groupOrigin(parents.get(id));
1402
+ const dx = fittedX - x + px, dy = fittedY - y + py;
1403
+ const offset = [a * dx + b * dy, c * dx + d * dy];
1404
+ origins.set(id, offset);
1405
+ return offset;
1406
+ }
1407
+ for (const boxes of instanceBoxes.values())
1408
+ for (const [path, box] of boxes) {
1409
+ const id = parseLayerPath(path).at(-1);
1410
+ const [px, py] = groupOrigin(parents.get(id));
1411
+ const [dx, dy] = groupOrigin(id);
1412
+ if (px === 0 && py === 0 && dx === 0 && dy === 0)
1413
+ continue;
1414
+ const [a, b, c, d, x, y] = box.transform;
1415
+ boxes.set(path, { ...box, transform: [a, b, c, d, x + a * dx + c * dy - px, y + b * dx + d * dy - py] });
1416
+ }
1417
+ }
1418
+ /**
1419
+ * Keeps each imported stack only when every Figma child in its flow (all but
1420
+ * "Ignore auto layout" children) was imported into it: a left-out child would
1421
+ * close up its gap, so the next re-layout would move the children. Hidden
1422
+ * children are no reason to drop the stack, since Taco, like Figma, leaves
1423
+ * them out of a row's or column's flow. A visible flow child that `refits` (a
1424
+ * group whose frame changes when fitted to its layers, such as a mask group
1425
+ * with a layer outside its mask) would also move, so it drops the stack too.
1426
+ * Such a frame goes back to free layout and the report says why. A kept stack
1427
+ * gives its children their Fill and absolute fields.
1428
+ */
1429
+ function settleStacks(stacks, add, refits) {
1430
+ for (const stack of stacks) {
1431
+ const { imported } = stack;
1432
+ // A child imported elsewhere (a copied node listed before its ancestor) is not in this frame.
1433
+ const members = new Set("children" in stack.node ? stack.node.children : []);
1434
+ const member = (child) => {
1435
+ const entry = imported.get(child);
1436
+ return entry !== undefined && members.has(entry.node.id) ? entry : undefined;
1437
+ };
1438
+ const flow = stack.figma.children.filter((child) => child.change["stackPositioning"] !== "ABSOLUTE");
1439
+ const blocker = flow.find((child) => {
1440
+ const entry = member(child);
1441
+ return entry === undefined || (entry.node.visible && refits(entry.node));
1442
+ });
1443
+ const firstOnTop = stack.figma.change["stackReverseZIndex"] === true;
1444
+ if (blocker !== undefined) {
1445
+ const why = member(blocker) !== undefined ? "changes size or position when fitted to its layers, as a Taco group is"
1446
+ : imported.has(blocker) ? "was imported on its own, outside this frame" : "was not imported";
1447
+ add(stack.link, "property-left-out", `auto layout is left off, so children keep their positions: child ${blocker.type} ${JSON.stringify(blocker.name)} ${why}`);
1448
+ if (firstOnTop)
1449
+ add(stack.link, "property-left-out", "stackReverseZIndex (first child on top) requires auto layout");
1450
+ Object.assign(stack.node, { layout: { kind: "absolute" } });
1451
+ continue;
1452
+ }
1453
+ if (firstOnTop)
1454
+ carry(stack.node, { firstOnTop: true });
1455
+ const vertical = stack.node.type === "frame" && stack.node.layout.kind === "vertical";
1456
+ const wraps = stack.figma.change["stackWrap"] === "WRAP";
1457
+ for (const child of stack.figma.children) {
1458
+ const entry = member(child);
1459
+ if (entry === undefined)
1460
+ continue;
1461
+ Object.assign(entry.node, stackChildFields(entry.figma.change, vertical, wraps, entry.node, (kind, reason) => add(entry.link, kind, reason)));
1462
+ }
1463
+ }
1464
+ }