@moondraft/import 0.0.0-stage → 0.1.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 (323) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/LICENSE +34 -0
  3. package/README.md +36 -2
  4. package/SOURCE.md +169 -0
  5. package/dist/adapter/convert.d.ts +122 -0
  6. package/dist/adapter/convert.js +2302 -0
  7. package/dist/adapter/figma.d.ts +9 -0
  8. package/dist/adapter/figma.js +30 -0
  9. package/dist/adapter/file-components.d.ts +14 -0
  10. package/dist/adapter/file-components.js +262 -0
  11. package/dist/adapter/file-resources.d.ts +29 -0
  12. package/dist/adapter/file-resources.js +562 -0
  13. package/dist/adapter/index.d.ts +6 -0
  14. package/dist/adapter/index.js +9 -0
  15. package/dist/adapter/link.d.ts +45 -0
  16. package/dist/adapter/link.js +688 -0
  17. package/dist/adapter/payload.d.ts +31 -0
  18. package/dist/adapter/payload.js +78 -0
  19. package/dist/adapter/shapes.d.ts +31 -0
  20. package/dist/adapter/shapes.js +75 -0
  21. package/dist/adapter/variables.d.ts +44 -0
  22. package/dist/adapter/variables.js +103 -0
  23. package/dist/figma-file.d.ts +38 -0
  24. package/dist/figma-file.js +97 -0
  25. package/dist/figma-worker.d.ts +11 -0
  26. package/dist/figma-worker.js +12 -0
  27. package/dist/figma.d.ts +26 -0
  28. package/dist/figma.js +96 -0
  29. package/dist/index.d.ts +28 -0
  30. package/dist/index.js +49 -0
  31. package/dist/report.d.ts +15 -0
  32. package/dist/report.js +69 -0
  33. package/dist/svg.d.ts +33 -0
  34. package/dist/svg.js +44 -0
  35. package/dist/syntax.d.ts +8 -0
  36. package/dist/syntax.js +19 -0
  37. package/dist/taco/figma-import/clipboard.d.ts +25 -0
  38. package/dist/taco/figma-import/clipboard.js +87 -0
  39. package/dist/taco/figma-import/clipboardSize.d.ts +31 -0
  40. package/dist/taco/figma-import/clipboardSize.js +107 -0
  41. package/dist/taco/figma-import/container/compression.d.ts +9 -0
  42. package/dist/taco/figma-import/container/compression.js +174 -0
  43. package/dist/taco/figma-import/container/error.d.ts +15 -0
  44. package/dist/taco/figma-import/container/error.js +19 -0
  45. package/dist/taco/figma-import/container/kiwiContainer.d.ts +38 -0
  46. package/dist/taco/figma-import/container/kiwiContainer.js +61 -0
  47. package/dist/taco/figma-import/container/limits.d.ts +22 -0
  48. package/dist/taco/figma-import/container/limits.js +22 -0
  49. package/dist/taco/figma-import/container/zip.d.ts +14 -0
  50. package/dist/taco/figma-import/container/zip.js +154 -0
  51. package/dist/taco/figma-import/figFile.d.ts +34 -0
  52. package/dist/taco/figma-import/figFile.js +91 -0
  53. package/dist/taco/figma-import/figFileDocument.d.ts +25 -0
  54. package/dist/taco/figma-import/figFileDocument.js +100 -0
  55. package/dist/taco/figma-import/import/blobs.d.ts +10 -0
  56. package/dist/taco/figma-import/import/blobs.js +23 -0
  57. package/dist/taco/figma-import/import/carry.d.ts +11 -0
  58. package/dist/taco/figma-import/import/carry.js +33 -0
  59. package/dist/taco/figma-import/import/componentProps.d.ts +84 -0
  60. package/dist/taco/figma-import/import/componentProps.js +313 -0
  61. package/dist/taco/figma-import/import/componentSets.d.ts +83 -0
  62. package/dist/taco/figma-import/import/componentSets.js +647 -0
  63. package/dist/taco/figma-import/import/converters/effects.d.ts +31 -0
  64. package/dist/taco/figma-import/import/converters/effects.js +127 -0
  65. package/dist/taco/figma-import/import/converters/ellipse.d.ts +7 -0
  66. package/dist/taco/figma-import/import/converters/ellipse.js +54 -0
  67. package/dist/taco/figma-import/import/converters/frame.d.ts +21 -0
  68. package/dist/taco/figma-import/import/converters/frame.js +55 -0
  69. package/dist/taco/figma-import/import/converters/gradient.d.ts +72 -0
  70. package/dist/taco/figma-import/import/converters/gradient.js +106 -0
  71. package/dist/taco/figma-import/import/converters/group.d.ts +21 -0
  72. package/dist/taco/figma-import/import/converters/group.js +39 -0
  73. package/dist/taco/figma-import/import/converters/image.d.ts +13 -0
  74. package/dist/taco/figma-import/import/converters/image.js +83 -0
  75. package/dist/taco/figma-import/import/converters/layout.d.ts +34 -0
  76. package/dist/taco/figma-import/import/converters/layout.js +168 -0
  77. package/dist/taco/figma-import/import/converters/line.d.ts +11 -0
  78. package/dist/taco/figma-import/import/converters/line.js +40 -0
  79. package/dist/taco/figma-import/import/converters/rectangle.d.ts +3 -0
  80. package/dist/taco/figma-import/import/converters/rectangle.js +11 -0
  81. package/dist/taco/figma-import/import/converters/section.d.ts +9 -0
  82. package/dist/taco/figma-import/import/converters/section.js +35 -0
  83. package/dist/taco/figma-import/import/converters/shared.d.ts +68 -0
  84. package/dist/taco/figma-import/import/converters/shared.js +362 -0
  85. package/dist/taco/figma-import/import/converters/text.d.ts +41 -0
  86. package/dist/taco/figma-import/import/converters/text.js +576 -0
  87. package/dist/taco/figma-import/import/converters/vector.d.ts +84 -0
  88. package/dist/taco/figma-import/import/converters/vector.js +468 -0
  89. package/dist/taco/figma-import/import/converters/vectorNetwork.d.ts +98 -0
  90. package/dist/taco/figma-import/import/converters/vectorNetwork.js +385 -0
  91. package/dist/taco/figma-import/import/fields.d.ts +15 -0
  92. package/dist/taco/figma-import/import/fields.js +29 -0
  93. package/dist/taco/figma-import/import/instances.d.ts +163 -0
  94. package/dist/taco/figma-import/import/instances.js +1323 -0
  95. package/dist/taco/figma-import/import/nestingCycles.d.ts +86 -0
  96. package/dist/taco/figma-import/import/nestingCycles.js +488 -0
  97. package/dist/taco/figma-import/import/slots.d.ts +56 -0
  98. package/dist/taco/figma-import/import/slots.js +96 -0
  99. package/dist/taco/figma-import/import/styles.d.ts +46 -0
  100. package/dist/taco/figma-import/import/styles.js +42 -0
  101. package/dist/taco/figma-import/import/tree.d.ts +66 -0
  102. package/dist/taco/figma-import/import/tree.js +194 -0
  103. package/dist/taco/figma-import/import/types.d.ts +232 -0
  104. package/dist/taco/figma-import/import/types.js +33 -0
  105. package/dist/taco/figma-import/import/variables.d.ts +136 -0
  106. package/dist/taco/figma-import/import/variables.js +762 -0
  107. package/dist/taco/figma-import/import/variantTrees.d.ts +20 -0
  108. package/dist/taco/figma-import/import/variantTrees.js +480 -0
  109. package/dist/taco/figma-import/import/walk.d.ts +159 -0
  110. package/dist/taco/figma-import/import/walk.js +1297 -0
  111. package/dist/taco/figma-import/index.d.ts +22 -0
  112. package/dist/taco/figma-import/index.js +13 -0
  113. package/dist/taco/figma-import/kiwi/byteReader.d.ts +37 -0
  114. package/dist/taco/figma-import/kiwi/byteReader.js +151 -0
  115. package/dist/taco/figma-import/kiwi/error.d.ts +14 -0
  116. package/dist/taco/figma-import/kiwi/error.js +29 -0
  117. package/dist/taco/figma-import/kiwi/limits.d.ts +18 -0
  118. package/dist/taco/figma-import/kiwi/limits.js +18 -0
  119. package/dist/taco/figma-import/kiwi/message.d.ts +10 -0
  120. package/dist/taco/figma-import/kiwi/message.js +145 -0
  121. package/dist/taco/figma-import/kiwi/schema.d.ts +42 -0
  122. package/dist/taco/figma-import/kiwi/schema.js +206 -0
  123. package/dist/taco/figma-import/kiwi/types.d.ts +46 -0
  124. package/dist/taco/figma-import/kiwi/types.js +18 -0
  125. package/dist/taco/model/agent-hidden-fields.d.ts +20 -0
  126. package/dist/taco/model/agent-hidden-fields.js +29 -0
  127. package/dist/taco/model/asset-users.d.ts +23 -0
  128. package/dist/taco/model/asset-users.js +128 -0
  129. package/dist/taco/model/auto-layout-lines.d.ts +32 -0
  130. package/dist/taco/model/auto-layout-lines.js +70 -0
  131. package/dist/taco/model/codec.d.ts +444 -0
  132. package/dist/taco/model/codec.js +5635 -0
  133. package/dist/taco/model/color.d.ts +11 -0
  134. package/dist/taco/model/color.js +61 -0
  135. package/dist/taco/model/comment-operations.d.ts +102 -0
  136. package/dist/taco/model/comment-operations.js +227 -0
  137. package/dist/taco/model/component-evaluation.d.ts +94 -0
  138. package/dist/taco/model/component-evaluation.js +548 -0
  139. package/dist/taco/model/component-expressions.d.ts +242 -0
  140. package/dist/taco/model/component-expressions.js +1082 -0
  141. package/dist/taco/model/component-properties.d.ts +111 -0
  142. package/dist/taco/model/component-properties.js +339 -0
  143. package/dist/taco/model/component-samples.d.ts +83 -0
  144. package/dist/taco/model/component-samples.js +290 -0
  145. package/dist/taco/model/component-validity.d.ts +85 -0
  146. package/dist/taco/model/component-validity.js +397 -0
  147. package/dist/taco/model/components.d.ts +155 -0
  148. package/dist/taco/model/components.js +505 -0
  149. package/dist/taco/model/connector-ends.d.ts +20 -0
  150. package/dist/taco/model/connector-ends.js +188 -0
  151. package/dist/taco/model/connector-geometry.d.ts +74 -0
  152. package/dist/taco/model/connector-geometry.js +293 -0
  153. package/dist/taco/model/corner-radii.d.ts +26 -0
  154. package/dist/taco/model/corner-radii.js +47 -0
  155. package/dist/taco/model/derivations.d.ts +81 -0
  156. package/dist/taco/model/derivations.js +151 -0
  157. package/dist/taco/model/export-settings.d.ts +53 -0
  158. package/dist/taco/model/export-settings.js +156 -0
  159. package/dist/taco/model/expressions/ast.d.ts +153 -0
  160. package/dist/taco/model/expressions/ast.js +6 -0
  161. package/dist/taco/model/expressions/cache.d.ts +23 -0
  162. package/dist/taco/model/expressions/cache.js +43 -0
  163. package/dist/taco/model/expressions/check.d.ts +72 -0
  164. package/dist/taco/model/expressions/check.js +517 -0
  165. package/dist/taco/model/expressions/completion.d.ts +61 -0
  166. package/dist/taco/model/expressions/completion.js +421 -0
  167. package/dist/taco/model/expressions/evaluate.d.ts +32 -0
  168. package/dist/taco/model/expressions/evaluate.js +519 -0
  169. package/dist/taco/model/expressions/forms.d.ts +84 -0
  170. package/dist/taco/model/expressions/forms.js +200 -0
  171. package/dist/taco/model/expressions/index.d.ts +14 -0
  172. package/dist/taco/model/expressions/index.js +17 -0
  173. package/dist/taco/model/expressions/lexer.d.ts +42 -0
  174. package/dist/taco/model/expressions/lexer.js +213 -0
  175. package/dist/taco/model/expressions/library.d.ts +33 -0
  176. package/dist/taco/model/expressions/library.js +117 -0
  177. package/dist/taco/model/expressions/names.d.ts +43 -0
  178. package/dist/taco/model/expressions/names.js +99 -0
  179. package/dist/taco/model/expressions/parser.d.ts +15 -0
  180. package/dist/taco/model/expressions/parser.js +438 -0
  181. package/dist/taco/model/expressions/rename.d.ts +34 -0
  182. package/dist/taco/model/expressions/rename.js +46 -0
  183. package/dist/taco/model/expressions/source.d.ts +15 -0
  184. package/dist/taco/model/expressions/source.js +161 -0
  185. package/dist/taco/model/expressions/types.d.ts +119 -0
  186. package/dist/taco/model/expressions/types.js +102 -0
  187. package/dist/taco/model/expressions/values.d.ts +97 -0
  188. package/dist/taco/model/expressions/values.js +160 -0
  189. package/dist/taco/model/geometry-limits.d.ts +16 -0
  190. package/dist/taco/model/geometry-limits.js +67 -0
  191. package/dist/taco/model/geometry.d.ts +47 -0
  192. package/dist/taco/model/geometry.js +193 -0
  193. package/dist/taco/model/group-bounds.d.ts +38 -0
  194. package/dist/taco/model/group-bounds.js +144 -0
  195. package/dist/taco/model/id-table.d.ts +37 -0
  196. package/dist/taco/model/id-table.js +80 -0
  197. package/dist/taco/model/index.d.ts +25 -0
  198. package/dist/taco/model/index.js +27 -0
  199. package/dist/taco/model/instance-resolver.d.ts +372 -0
  200. package/dist/taco/model/instance-resolver.js +1748 -0
  201. package/dist/taco/model/layer-syntax.d.ts +340 -0
  202. package/dist/taco/model/layer-syntax.js +3506 -0
  203. package/dist/taco/model/layout/constraints.d.ts +84 -0
  204. package/dist/taco/model/layout/constraints.js +445 -0
  205. package/dist/taco/model/layout/frame-layout.d.ts +46 -0
  206. package/dist/taco/model/layout/frame-layout.js +618 -0
  207. package/dist/taco/model/layout/node-sizing.d.ts +163 -0
  208. package/dist/taco/model/layout/node-sizing.js +486 -0
  209. package/dist/taco/model/legacy-connector-caps.d.ts +15 -0
  210. package/dist/taco/model/legacy-connector-caps.js +70 -0
  211. package/dist/taco/model/linear-call.d.ts +48 -0
  212. package/dist/taco/model/linear-call.js +58 -0
  213. package/dist/taco/model/new-nodes.d.ts +145 -0
  214. package/dist/taco/model/new-nodes.js +277 -0
  215. package/dist/taco/model/node-builder.d.ts +449 -0
  216. package/dist/taco/model/node-builder.js +2294 -0
  217. package/dist/taco/model/node-table-watch.d.ts +36 -0
  218. package/dist/taco/model/node-table-watch.js +63 -0
  219. package/dist/taco/model/node-transform.d.ts +39 -0
  220. package/dist/taco/model/node-transform.js +79 -0
  221. package/dist/taco/model/node-users-index.d.ts +10 -0
  222. package/dist/taco/model/node-users-index.js +82 -0
  223. package/dist/taco/model/operation-references.d.ts +80 -0
  224. package/dist/taco/model/operation-references.js +399 -0
  225. package/dist/taco/model/operations.d.ts +610 -0
  226. package/dist/taco/model/operations.js +2882 -0
  227. package/dist/taco/model/overlay-table.d.ts +71 -0
  228. package/dist/taco/model/overlay-table.js +171 -0
  229. package/dist/taco/model/override-remap.d.ts +69 -0
  230. package/dist/taco/model/override-remap.js +230 -0
  231. package/dist/taco/model/parent-table.d.ts +53 -0
  232. package/dist/taco/model/parent-table.js +193 -0
  233. package/dist/taco/model/problem-collector.d.ts +27 -0
  234. package/dist/taco/model/problem-collector.js +101 -0
  235. package/dist/taco/model/sha256.d.ts +10 -0
  236. package/dist/taco/model/sha256.js +74 -0
  237. package/dist/taco/model/shape-geometry.d.ts +96 -0
  238. package/dist/taco/model/shape-geometry.js +368 -0
  239. package/dist/taco/model/shared-node-table.d.ts +97 -0
  240. package/dist/taco/model/shared-node-table.js +546 -0
  241. package/dist/taco/model/slots.d.ts +113 -0
  242. package/dist/taco/model/slots.js +281 -0
  243. package/dist/taco/model/stroke-settings.d.ts +37 -0
  244. package/dist/taco/model/stroke-settings.js +90 -0
  245. package/dist/taco/model/svg-path-import.d.ts +89 -0
  246. package/dist/taco/model/svg-path-import.js +219 -0
  247. package/dist/taco/model/text-measurement.d.ts +142 -0
  248. package/dist/taco/model/text-measurement.js +846 -0
  249. package/dist/taco/model/text-reads.d.ts +66 -0
  250. package/dist/taco/model/text-reads.js +128 -0
  251. package/dist/taco/model/text-sizer.d.ts +358 -0
  252. package/dist/taco/model/text-sizer.js +996 -0
  253. package/dist/taco/model/theme-users.d.ts +59 -0
  254. package/dist/taco/model/theme-users.js +312 -0
  255. package/dist/taco/model/thumbnail.d.ts +15 -0
  256. package/dist/taco/model/thumbnail.js +34 -0
  257. package/dist/taco/model/types.d.ts +2347 -0
  258. package/dist/taco/model/types.js +366 -0
  259. package/dist/taco/model/unknown-property.d.ts +5 -0
  260. package/dist/taco/model/unknown-property.js +7 -0
  261. package/dist/taco/model/validated-documents.d.ts +22 -0
  262. package/dist/taco/model/validated-documents.js +22 -0
  263. package/dist/taco/model/variable-modes.d.ts +61 -0
  264. package/dist/taco/model/variable-modes.js +438 -0
  265. package/dist/taco/model/variable-references.d.ts +54 -0
  266. package/dist/taco/model/variable-references.js +183 -0
  267. package/dist/taco/model/variables.d.ts +24 -0
  268. package/dist/taco/model/variables.js +151 -0
  269. package/dist/taco/model/vector-network.d.ts +34 -0
  270. package/dist/taco/model/vector-network.js +411 -0
  271. package/dist/taco/svg-import/import-svg.d.ts +36 -0
  272. package/dist/taco/svg-import/import-svg.js +729 -0
  273. package/dist/taco/svg-import/index.d.ts +3 -0
  274. package/dist/taco/svg-import/index.js +3 -0
  275. package/dist/taco/svg-import/limits/limits.d.ts +79 -0
  276. package/dist/taco/svg-import/limits/limits.js +160 -0
  277. package/dist/taco/svg-import/paint/gradients.d.ts +64 -0
  278. package/dist/taco/svg-import/paint/gradients.js +429 -0
  279. package/dist/taco/svg-import/paint/paint.d.ts +32 -0
  280. package/dist/taco/svg-import/paint/paint.js +162 -0
  281. package/dist/taco/svg-import/paths/paths.d.ts +58 -0
  282. package/dist/taco/svg-import/paths/paths.js +205 -0
  283. package/dist/taco/svg-import/public-types.d.ts +279 -0
  284. package/dist/taco/svg-import/public-types.js +56 -0
  285. package/dist/taco/svg-import/report/report.d.ts +44 -0
  286. package/dist/taco/svg-import/report/report.js +79 -0
  287. package/dist/taco/svg-import/reuse/reuse.d.ts +99 -0
  288. package/dist/taco/svg-import/reuse/reuse.js +840 -0
  289. package/dist/taco/svg-import/shapes/shapes.d.ts +35 -0
  290. package/dist/taco/svg-import/shapes/shapes.js +386 -0
  291. package/dist/taco/svg-import/structure/effects.d.ts +26 -0
  292. package/dist/taco/svg-import/structure/effects.js +618 -0
  293. package/dist/taco/svg-import/structure/image.d.ts +24 -0
  294. package/dist/taco/svg-import/structure/image.js +495 -0
  295. package/dist/taco/svg-import/structure/walk.d.ts +85 -0
  296. package/dist/taco/svg-import/structure/walk.js +544 -0
  297. package/dist/taco/svg-import/style/color.d.ts +40 -0
  298. package/dist/taco/svg-import/style/color.js +275 -0
  299. package/dist/taco/svg-import/style/computed.d.ts +214 -0
  300. package/dist/taco/svg-import/style/computed.js +1534 -0
  301. package/dist/taco/svg-import/style/css.d.ts +127 -0
  302. package/dist/taco/svg-import/style/css.js +541 -0
  303. package/dist/taco/svg-import/style/media.d.ts +25 -0
  304. package/dist/taco/svg-import/style/media.js +307 -0
  305. package/dist/taco/svg-import/style/properties.d.ts +43 -0
  306. package/dist/taco/svg-import/style/properties.js +135 -0
  307. package/dist/taco/svg-import/style/selector-reach.d.ts +30 -0
  308. package/dist/taco/svg-import/style/selector-reach.js +169 -0
  309. package/dist/taco/svg-import/style/selector-validity.d.ts +14 -0
  310. package/dist/taco/svg-import/style/selector-validity.js +307 -0
  311. package/dist/taco/svg-import/text/text.d.ts +29 -0
  312. package/dist/taco/svg-import/text/text.js +545 -0
  313. package/dist/taco/svg-import/transform/matrix.d.ts +111 -0
  314. package/dist/taco/svg-import/transform/matrix.js +229 -0
  315. package/dist/taco/svg-import/tree/element-data.d.ts +52 -0
  316. package/dist/taco/svg-import/tree/element-data.js +155 -0
  317. package/dist/taco/svg-import/tree/elements.d.ts +36 -0
  318. package/dist/taco/svg-import/tree/elements.js +121 -0
  319. package/dist/taco/svg-import/units/length.d.ts +43 -0
  320. package/dist/taco/svg-import/units/length.js +125 -0
  321. package/dist/taco/svg-import/units/viewbox.d.ts +35 -0
  322. package/dist/taco/svg-import/units/viewbox.js +77 -0
  323. package/package.json +54 -4
@@ -0,0 +1,2294 @@
1
+ import { linearCall, resolveLinearCalls } from "./linear-call.js";
2
+ import { sceneNodeFieldNames } from "./codec.js";
3
+ import { AGENT_HIDDEN_NODE_FIELDS } from "./agent-hidden-fields.js";
4
+ import { formatExpressionName, isBareExpressionName, normalizeExpressionName } from "./expressions/names.js";
5
+ import { getNodeBounds, getVectorNetworkBounds } from "./geometry.js";
6
+ import { entryOf } from "./id-table.js";
7
+ import { componentOwningNode, findComponentByRoot } from "./components.js";
8
+ import { ModelError } from "./codec.js";
9
+ import { putEntry } from "./id-table.js";
10
+ import { resolveInstance } from "./instance-resolver.js";
11
+ import { sharedTableDraft } from "./shared-node-table.js";
12
+ import { withAxisSizing } from "./layout/node-sizing.js";
13
+ import { layerOverrideFieldNames } from "./codec.js";
14
+ import { InstanceBuildError, newCodeNode, newConnectorNode, newFrameNode, newInstanceNode, newMediaNode, newShapeNode, newStackAutoLayout, newTextNode, newWrapperNode, nodeSequenceAllocator, SHAPE_LABELS, } from "./new-nodes.js";
15
+ import { scaleVectorNetwork, vectorNetworkFromSvgPathData } from "./vector-network.js";
16
+ import { VARIABLE_PROPERTY_TYPES } from "./variables.js";
17
+ import { holdsVariableReference, isVariableProperty, isVariableReference, readVariableArgument, variableReference, VariableReferenceError, withBoundVariables, } from "./variable-references.js";
18
+ import { codeStyleId, isContainerNode, nodeId, isValuedComponentProperty, } from "./types.js";
19
+ /**
20
+ * A source `buildNodes` cannot read (`syntax`) or a call it cannot make
21
+ * (`argument`: an unknown shorthand or argument, an argument given twice,
22
+ * an id given by two calls, children where the shorthand takes none, a
23
+ * value without a name, `fill` or `hug` where a size cannot take it, or `x`
24
+ * or `y` on a layer auto layout places), or a source with more calls than `maxCalls`
25
+ * allows (`size`). The message names the place, and the call when there is one.
26
+ */
27
+ export class NodeBuildError extends Error {
28
+ kind;
29
+ line;
30
+ column;
31
+ /** The call, as `vflex #1 > text #2`, for an `argument` error. */
32
+ call;
33
+ /** The names the call's shorthand accepts, for an unknown argument. */
34
+ accepted;
35
+ constructor(kind, message, line, column, call, accepted) {
36
+ super(message);
37
+ this.kind = kind;
38
+ this.line = line;
39
+ this.column = column;
40
+ this.call = call;
41
+ this.accepted = accepted;
42
+ this.name = "NodeBuildError";
43
+ }
44
+ }
45
+ /** The refusal of a backslash in the tool spelling, which never escapes anything. */
46
+ export const LAYER_SYNTAX_BACKSLASH_REFUSAL = "a backslash is not part of this syntax, so nothing is escaped: "
47
+ + "write a quote inside a string twice ('it''s') and a line break as it is";
48
+ /** The refusal of a backtick in the tool spelling. */
49
+ export const LAYER_SYNTAX_BACKTICK_REFUSAL = "expressions in backticks are not supported yet; write the value itself";
50
+ /** The slot lists read, by the value that stands for each: a value of the language holds no call. */
51
+ const SLOT_CONTENT = new WeakMap();
52
+ /** A value that stands for the slot content `content`, for `slotContentOf` to find again. */
53
+ export function slotContentValue(content) {
54
+ const value = Object.freeze([]);
55
+ SLOT_CONTENT.set(value, content);
56
+ return value;
57
+ }
58
+ /** The slot content a value stands for, or undefined for any other value. */
59
+ export const slotContentOf = (value) => value !== null && typeof value === "object" ? SLOT_CONTENT.get(value) : undefined;
60
+ /** The refusal of `(2 layers, #<host id>)` where layers are to be written: what it is, and how to build into that slot. */
61
+ export const slotSummaryRefusal = (count, hostId) => `(${count} ${count === 1 ? "layer" : "layers"}, #${hostId}) is how read shows a filled slot without its layers, so it builds nothing: `
62
+ + `write the slot's layers in ( ... ), or leave the slot out. To add layers to that slot, build in #${hostId}; read #${hostId} shows the layers it holds.`;
63
+ /** The argument of an instance call and the key of `over:{Path:{...}}` that fill its slots. */
64
+ export const INSTANCE_SLOTS_ARGUMENT = "slots";
65
+ /**
66
+ * `value` with each slot content inside it (at any depth of its objects) replaced by what `map` gives; `value` itself
67
+ * when it holds none.
68
+ */
69
+ export function mapSlotContents(value, map) {
70
+ const content = slotContentOf(value);
71
+ if (content !== undefined)
72
+ return slotContentValue(map(content));
73
+ if (value === null || typeof value !== "object" || Array.isArray(value))
74
+ return value;
75
+ let changed = false;
76
+ const mapped = {};
77
+ for (const [key, item] of Object.entries(value)) {
78
+ const next = mapSlotContents(item, map);
79
+ if (next !== item)
80
+ changed = true;
81
+ Object.defineProperty(mapped, key, { value: next, enumerable: true, writable: true, configurable: true });
82
+ }
83
+ return changed ? mapped : value;
84
+ }
85
+ /** The calls of every slot content in the arguments of `call`, in the order written. */
86
+ export function slotContentCalls(call) {
87
+ const calls = [];
88
+ for (const argument of call.arguments)
89
+ mapSlotContents(argument.value, (content) => { calls.push(...content.calls); return content; });
90
+ return calls;
91
+ }
92
+ const PLAIN_ID = /^[0-9A-Za-z_-]+$/;
93
+ const REFERENCE = /^#(?:([0-9A-Za-z_-]+)|'((?:[^']|'')*)')(?:\.([A-Za-z][A-Za-z0-9_-]*)(?:\(([^()]*)\))?)?$/;
94
+ const NUMBER = /^-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/;
95
+ /** Reads a layer reference (`#card.right`); undefined for a text that is not one. */
96
+ export function readLayerReference(text) {
97
+ const match = REFERENCE.exec(text);
98
+ if (match === null)
99
+ return undefined;
100
+ const id = match[1] ?? match[2].replaceAll("''", "'");
101
+ if (match[3] === undefined)
102
+ return { id };
103
+ return { id, place: match[3], ...(match[4] === undefined ? {} : { numbers: match[4].split(",").map((part) => part.trim()) }) };
104
+ }
105
+ /** A layer reference as the tool spelling writes it, numbers as `String(Number(part))` where they are numbers. */
106
+ export function layerReferenceText(reference) {
107
+ const id = PLAIN_ID.test(reference.id) ? reference.id : `'${reference.id.replaceAll("'", "''")}'`;
108
+ const numbers = reference.numbers?.map((part) => NUMBER.test(part) ? String(Number(part)) : part);
109
+ return `#${id}${reference.place === undefined ? "" : `.${reference.place}`}${numbers === undefined ? "" : `(${numbers.join(", ")})`}`;
110
+ }
111
+ const isWordStart = (character) => /[A-Za-z_]/.test(character);
112
+ const isWordPart = (character) => /[A-Za-z0-9_-]/.test(character);
113
+ const isDigit = (character) => /[0-9]/.test(character);
114
+ const isSpace = (character) => /\s/.test(character);
115
+ const PUNCTUATION = "()[]{}:,";
116
+ /**
117
+ * Punctuation of the tool spelling only: `;` between rules or calls, `-` before a field to remove, `*` for any kind and
118
+ * `>` between two steps of a matcher, the second directly inside the first.
119
+ */
120
+ const TOOL_PUNCTUATION = ";-*>";
121
+ function tokenize(source, spelling) {
122
+ const toolSpelling = spelling === "tool";
123
+ const tokens = [];
124
+ let index = 0, line = 1, column = 1;
125
+ const advance = (count) => {
126
+ for (let step = 0; step < count; step += 1) {
127
+ if (source[index] === "\n") {
128
+ line += 1;
129
+ column = 1;
130
+ }
131
+ else
132
+ column += 1;
133
+ index += 1;
134
+ }
135
+ };
136
+ const syntax = (message, at = { line, column }) => new NodeBuildError("syntax", `Line ${at.line}, column ${at.column}: ${message}`, at.line, at.column);
137
+ while (index < source.length) {
138
+ const character = source[index];
139
+ const at = { line, column, start: index };
140
+ if (isSpace(character)) {
141
+ advance(1);
142
+ continue;
143
+ }
144
+ if (PUNCTUATION.includes(character)) {
145
+ tokens.push({ kind: "punctuation", text: character, ...at, end: index + 1 });
146
+ advance(1);
147
+ continue;
148
+ }
149
+ if (toolSpelling && character === "\\")
150
+ throw syntax(LAYER_SYNTAX_BACKSLASH_REFUSAL, at);
151
+ if (toolSpelling && character === "`")
152
+ throw syntax(LAYER_SYNTAX_BACKTICK_REFUSAL, at);
153
+ if (toolSpelling && (character === "'" || character === "\"")) {
154
+ // A quote inside is written twice; nothing else is special, a line break included.
155
+ let end = index + 1, value = "";
156
+ for (;;) {
157
+ if (end >= source.length)
158
+ throw syntax(`expected the closing ${character} of this string`, at);
159
+ const inside = source[end];
160
+ if (inside === "\\") {
161
+ const before = source.slice(index, end);
162
+ const lines = before.split("\n");
163
+ throw syntax(LAYER_SYNTAX_BACKSLASH_REFUSAL, { line: at.line + lines.length - 1, column: lines.length === 1 ? at.column + before.length : lines[lines.length - 1].length + 1 });
164
+ }
165
+ if (inside === character) {
166
+ if (source[end + 1] === character) {
167
+ value += character;
168
+ end += 2;
169
+ continue;
170
+ }
171
+ break;
172
+ }
173
+ value += inside;
174
+ end += 1;
175
+ }
176
+ tokens.push({ kind: "string", text: source.slice(index, end + 1), value, ...at, end: end + 1 });
177
+ advance(end + 1 - index);
178
+ continue;
179
+ }
180
+ if (character === "\"") {
181
+ let end = index + 1;
182
+ while (end < source.length && source[end] !== "\"" && source[end] !== "\n")
183
+ end += source[end] === "\\" ? 2 : 1;
184
+ if (source[end] !== "\"")
185
+ throw syntax("expected the closing \" of this string", at);
186
+ const text = source.slice(index, end + 1);
187
+ let value;
188
+ try {
189
+ value = JSON.parse(text);
190
+ }
191
+ catch {
192
+ throw syntax(`expected a string with JSON escapes, found ${text}`, at);
193
+ }
194
+ tokens.push({ kind: "string", text, value, ...at, end: end + 1 });
195
+ advance(end + 1 - index);
196
+ continue;
197
+ }
198
+ if (character === "#" && toolSpelling) {
199
+ // A layer id with a place after it, #card.right or #'1:2'.vertex(2): one token, so that a connector end is one value.
200
+ let end = index + 1, id;
201
+ while (end < source.length && /[0-9A-Za-z_-]/.test(source[end]))
202
+ end += 1;
203
+ if (end > index + 1)
204
+ id = source.slice(index + 1, end);
205
+ else if (source[end] === "'") {
206
+ let close = end + 1, inner = "";
207
+ for (; close < source.length; close += 1) {
208
+ if (source[close] !== "'") {
209
+ inner += source[close];
210
+ continue;
211
+ }
212
+ if (source[close + 1] !== "'")
213
+ break;
214
+ inner += "'";
215
+ close += 1;
216
+ }
217
+ if (close < source.length) {
218
+ id = inner;
219
+ end = close + 1;
220
+ }
221
+ }
222
+ if (id !== undefined && source[end] === "." && end + 1 < source.length && isWordStart(source[end + 1])) {
223
+ let place = end + 1;
224
+ while (place < source.length && isWordPart(source[place]))
225
+ place += 1;
226
+ const word = source.slice(end + 1, place);
227
+ let numbers;
228
+ end = place;
229
+ if (source[end] === "(") {
230
+ const close = source.indexOf(")", end);
231
+ const open = source.indexOf("(", end + 1);
232
+ if (close === -1 || (open !== -1 && open < close))
233
+ throw syntax(`expected the closing ) after #${id}.${word}(`, at);
234
+ numbers = source.slice(end + 1, close).split(",").map((part) => part.trim());
235
+ end = close + 1;
236
+ }
237
+ const text = source.slice(index, end);
238
+ tokens.push({ kind: "reference", text, value: layerReferenceText({ id, place: word, ...(numbers === undefined ? {} : { numbers }) }), ...at, end });
239
+ advance(end - index);
240
+ continue;
241
+ }
242
+ }
243
+ if (character === "#") {
244
+ let end = index + 1;
245
+ // In the tool spelling `#` also starts a layer id, which may hold "-" and "_".
246
+ const part = toolSpelling ? /[0-9A-Za-z_-]/ : /[0-9A-Za-z]/;
247
+ while (end < source.length && part.test(source[end]))
248
+ end += 1;
249
+ const text = source.slice(index, end);
250
+ tokens.push({ kind: "colour", text, value: text, ...at, end });
251
+ advance(end - index);
252
+ continue;
253
+ }
254
+ if (isDigit(character) || ((character === "-" || character === ".") && index + 1 < source.length && /[0-9.]/.test(source[index + 1]))) {
255
+ const match = /^-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/.exec(source.slice(index));
256
+ if (match === null)
257
+ throw syntax(`expected a number, found ${JSON.stringify(character)}`, at);
258
+ tokens.push({ kind: "number", text: match[0], value: Number(match[0]), ...at, end: index + match[0].length });
259
+ advance(match[0].length);
260
+ continue;
261
+ }
262
+ if (toolSpelling && TOOL_PUNCTUATION.includes(character)) {
263
+ tokens.push({ kind: "punctuation", text: character, ...at, end: index + 1 });
264
+ advance(1);
265
+ continue;
266
+ }
267
+ if (isWordStart(character)) {
268
+ let end = index + 1;
269
+ // In the tool spelling a word may hold dots between its parts, for a call in a scope: std.text, forms.text.
270
+ while (end < source.length && (isWordPart(source[end])
271
+ || (toolSpelling && source[end] === "." && end + 1 < source.length && isWordStart(source[end + 1]))))
272
+ end += 1;
273
+ const text = source.slice(index, end);
274
+ tokens.push({ kind: "word", text, value: text === "true" ? true : text === "false" ? false : text, ...at, end });
275
+ advance(end - index);
276
+ continue;
277
+ }
278
+ // The build tool's text separates layers with ";" and quotes strings with "'"; a node.build source, in the default spelling, does neither.
279
+ if (character === ";" || character === "'") {
280
+ throw syntax(`found ${JSON.stringify(character)}: a node.build source separates its layers with "," and writes strings in double quotes, as JSON does, `
281
+ + "as in rect(w:10), text(text:\"Hi\"). \";\" between layers and single-quoted strings belong to the build tool's text.", at);
282
+ }
283
+ if (/\p{L}/u.test(String.fromCodePoint(source.codePointAt(index)))) {
284
+ // A word is ASCII; a name in other letters, such as a prop's or an option's, is a string.
285
+ let end = index;
286
+ for (let point = String.fromCodePoint(source.codePointAt(end)); /[\p{L}\p{M}\p{N}_]/u.test(point);) {
287
+ end += point.length;
288
+ if (end >= source.length)
289
+ break;
290
+ point = String.fromCodePoint(source.codePointAt(end));
291
+ }
292
+ const name = source.slice(index, end);
293
+ throw syntax(`found ${JSON.stringify(name)}: a word is ASCII letters, digits, _ and -; write any other name in quotes, as '${name}'`, at);
294
+ }
295
+ throw syntax(`expected a call, a value or one of ${PUNCTUATION.split("").join(" ")}, found ${JSON.stringify(character)}`, at);
296
+ }
297
+ tokens.push({ kind: "end", text: "the end of the source", line, column, start: index, end: index });
298
+ return tokens;
299
+ }
300
+ /** The gradients the tool spelling writes as a call in a value: `fill:linear(90, #fff, #000)`. */
301
+ const GRADIENT_CALLS = new Set(["linear", "radial"]);
302
+ const GRADIENT_COLOUR = /^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
303
+ /** A reader of `source` in `spelling`; `maxCalls` limits the calls it reads (a `size` NodeBuildError past it). */
304
+ export function layerSyntaxReader(source, spelling = "layer", maxCalls = Infinity) {
305
+ const tokens = tokenize(source, spelling);
306
+ let position = 0, callCount = 0;
307
+ const peek = (offset = 0) => tokens[Math.min(position + offset, tokens.length - 1)];
308
+ const next = () => tokens[Math.min(position++, tokens.length - 1)];
309
+ const shown = (token) => token.kind === "end" ? token.text : JSON.stringify(token.text);
310
+ const expected = (what, token = peek()) => new NodeBuildError("syntax", `Line ${token.line}, column ${token.column}: expected ${what}, found ${shown(token)}`, token.line, token.column);
311
+ const isPunctuation = (token, text) => token.kind === "punctuation" && token.text === text;
312
+ const expect = (text, what = JSON.stringify(text)) => {
313
+ if (!isPunctuation(peek(), text))
314
+ throw expected(what);
315
+ return next();
316
+ };
317
+ function value() {
318
+ const token = peek();
319
+ // var('name') names a variable of the document (variable-references.ts).
320
+ if (token.kind === "word" && token.text === "var" && isPunctuation(peek(1), "(")) {
321
+ next();
322
+ next();
323
+ const name = peek();
324
+ if (name.kind !== "string")
325
+ throw expected("the name of a variable in quotes, as var('brand/primary')");
326
+ next();
327
+ expect(")", "\")\" after the name of the variable");
328
+ return variableReference(name.value);
329
+ }
330
+ if (spelling === "tool" && token.kind === "word" && GRADIENT_CALLS.has(String(token.value)) && isPunctuation(peek(1), "(")) {
331
+ next();
332
+ return gradient(String(token.value), token);
333
+ }
334
+ if (spelling === "tool" && token.kind === "colour" && token.text === "#" && peek(1).kind === "string") {
335
+ // #'1:2', a layer id with other characters, as a value: a connector end.
336
+ next();
337
+ return layerReferenceText({ id: next().value });
338
+ }
339
+ if (token.kind === "number" || token.kind === "string" || token.kind === "colour" || token.kind === "reference" || token.kind === "word") {
340
+ next();
341
+ return token.value;
342
+ }
343
+ if (isPunctuation(token, "(")) {
344
+ next();
345
+ const items = [];
346
+ while (!isPunctuation(peek(), ")")) {
347
+ items.push(value());
348
+ if (isPunctuation(peek(), ","))
349
+ next();
350
+ else if (!isPunctuation(peek(), ")"))
351
+ throw expected("\",\" or \")\"");
352
+ }
353
+ next();
354
+ return items;
355
+ }
356
+ if (isPunctuation(token, "{")) {
357
+ next();
358
+ const object = {};
359
+ while (!isPunctuation(peek(), "}")) {
360
+ const key = peek();
361
+ if (key.kind !== "word" && key.kind !== "string")
362
+ throw expected("a field name or \"}\"");
363
+ next();
364
+ expect(":");
365
+ Object.defineProperty(object, String(key.value), { value: value(), enumerable: true, writable: true, configurable: true });
366
+ if (isPunctuation(peek(), ","))
367
+ next();
368
+ else if (!isPunctuation(peek(), "}"))
369
+ throw expected("\",\" or \"}\"");
370
+ }
371
+ next();
372
+ return object;
373
+ }
374
+ throw expected("a value (a number, a \"string\", a #colour, true, false, a word, a list or an object)");
375
+ }
376
+ function argumentValue(name) {
377
+ return name === INSTANCE_SLOTS_ARGUMENT ? slots() : name === INSTANCE_OVER_ARGUMENT ? over() : value();
378
+ }
379
+ /**
380
+ * The value of `over:`: `{Layer:{field:value, ..., slots:{...}}}`, where `slots` in a layer's changes is read by `slots`
381
+ * (the slots of a nested instance); any other value as `value` reads it.
382
+ */
383
+ function over() {
384
+ if (!isPunctuation(peek(), "{"))
385
+ return value();
386
+ next();
387
+ const object = {};
388
+ while (!isPunctuation(peek(), "}")) {
389
+ const key = peek();
390
+ if (key.kind !== "word" && key.kind !== "string")
391
+ throw expected("a field name or \"}\"");
392
+ next();
393
+ expect(":");
394
+ let item;
395
+ if (isPunctuation(peek(), "{")) {
396
+ next();
397
+ const changes = {};
398
+ while (!isPunctuation(peek(), "}")) {
399
+ const field = peek();
400
+ if (field.kind !== "word" && field.kind !== "string")
401
+ throw expected("a field name or \"}\"");
402
+ next();
403
+ expect(":");
404
+ const read = field.value === INSTANCE_SLOTS_ARGUMENT ? slots() : value();
405
+ Object.defineProperty(changes, String(field.value), { value: read, enumerable: true, writable: true, configurable: true });
406
+ if (isPunctuation(peek(), ","))
407
+ next();
408
+ else if (!isPunctuation(peek(), "}"))
409
+ throw expected("\",\" or \"}\"");
410
+ }
411
+ next();
412
+ item = changes;
413
+ }
414
+ else
415
+ item = value();
416
+ Object.defineProperty(object, String(key.value), { value: item, enumerable: true, writable: true, configurable: true });
417
+ if (isPunctuation(peek(), ","))
418
+ next();
419
+ else if (!isPunctuation(peek(), "}"))
420
+ throw expected("\",\" or \"}\"");
421
+ }
422
+ next();
423
+ return object;
424
+ }
425
+ /**
426
+ * The value of `slots:` (an instance call's argument, or a key of a layer's changes in `over:{...}`): `{Name:( ... ), Name:default, ...}`, each `( ... )` a
427
+ * slot list (`slotList`), and an object inside read the same way; any other value as `value` reads it.
428
+ */
429
+ function slots() {
430
+ if (!isPunctuation(peek(), "{"))
431
+ return value();
432
+ next();
433
+ const object = {};
434
+ while (!isPunctuation(peek(), "}")) {
435
+ const key = peek();
436
+ if (key.kind !== "word" && key.kind !== "string")
437
+ throw expected("a slot name or \"}\"");
438
+ next();
439
+ expect(":");
440
+ const item = isPunctuation(peek(), "(") ? slotList() : slots();
441
+ Object.defineProperty(object, String(key.value), { value: item, enumerable: true, writable: true, configurable: true });
442
+ if (isPunctuation(peek(), ","))
443
+ next();
444
+ else if (!isPunctuation(peek(), "}"))
445
+ throw expected("\",\" or \"}\"");
446
+ }
447
+ next();
448
+ return object;
449
+ }
450
+ /**
451
+ * A slot list from its `(`: the calls of the slot's layers, then optionally `#<host id>` (in the default spelling the
452
+ * host id as a string); or `(2 layers, #<host id>)`, the form read prints for a filled slot without its layers.
453
+ */
454
+ function slotList() {
455
+ const open = next();
456
+ const calls = [];
457
+ let hostId, summary;
458
+ const form = "a layer call, or #<host id> last";
459
+ while (!isPunctuation(peek(), ")")) {
460
+ const token = peek();
461
+ if (hostId !== undefined)
462
+ throw expected(`")" after the slot host's id #${hostId}`);
463
+ if (token.kind === "word" && isPunctuation(peek(1), "(")) {
464
+ if (summary !== undefined)
465
+ throw expected(`#<host id> after ${summary} layers`);
466
+ calls.push(call());
467
+ }
468
+ else if (token.kind === "number" && peek(1).kind === "word" && (peek(1).text === "layers" || peek(1).text === "layer")) {
469
+ if (calls.length > 0 || summary !== undefined)
470
+ throw expected(form);
471
+ next();
472
+ next();
473
+ summary = token.value;
474
+ }
475
+ else if (spelling === "tool" && token.kind === "colour" && token.text === "#" && peek(1).kind === "string") {
476
+ next();
477
+ hostId = next().value;
478
+ }
479
+ else if (spelling === "tool" && token.kind === "colour" && token.text.length > 1) {
480
+ next();
481
+ hostId = token.text.slice(1);
482
+ }
483
+ else if (spelling !== "tool" && token.kind === "string") {
484
+ next();
485
+ hostId = token.value;
486
+ }
487
+ else
488
+ throw expected(form);
489
+ if (isPunctuation(peek(), ",") || (spelling === "tool" && isPunctuation(peek(), ";")))
490
+ next();
491
+ else if (!isPunctuation(peek(), ")"))
492
+ throw expected("\",\" or \")\"");
493
+ }
494
+ next();
495
+ if (summary !== undefined && hostId === undefined)
496
+ throw expected(`#<host id> after ${summary} layers`);
497
+ return slotContentValue({ calls, ...(hostId === undefined ? {} : { hostId }), ...(summary === undefined ? {} : { summary }),
498
+ line: open.line, column: open.column });
499
+ }
500
+ /**
501
+ * The paint of `linear(angle, stops...)` or `radial(stops...)`, from its `(`: each stop a colour, the stops spread
502
+ * evenly from 0 to 1, or `(colour, offset)` with the offset written.
503
+ */
504
+ function gradient(name, start) {
505
+ const form = name === "linear" ? "linear(<angle>, #colour, #colour, ...)" : "radial(#colour, #colour, ...)";
506
+ const items = value();
507
+ const fail = (what) => new NodeBuildError("syntax", `Line ${start.line}, column ${start.column}: ${name}(...) ${what}; write ${form}, `
508
+ + "each stop a colour spread evenly, or (#colour, <offset from 0 to 1>).", start.line, start.column);
509
+ const angle = name === "linear" ? items[0] : undefined;
510
+ if (name === "linear" && (typeof angle !== "number" || !Number.isFinite(angle)))
511
+ throw fail("starts with its angle in degrees, a number");
512
+ const written = name === "linear" ? items.slice(1) : items;
513
+ if (written.length < 2)
514
+ throw fail("takes two stops or more");
515
+ const stops = written.map((stop, index) => {
516
+ if (typeof stop === "string" && GRADIENT_COLOUR.test(stop))
517
+ return { offset: index / (written.length - 1), color: stop };
518
+ if (Array.isArray(stop) && stop.length === 2 && typeof stop[0] === "string" && GRADIENT_COLOUR.test(stop[0])
519
+ && typeof stop[1] === "number" && stop[1] >= 0 && stop[1] <= 1)
520
+ return { offset: stop[1], color: stop[0] };
521
+ throw fail(`has a stop ${index + 1} that is neither a #colour nor (#colour, offset)`);
522
+ });
523
+ if (typeof angle !== "number")
524
+ return { kind: "radial-gradient", stops };
525
+ return linearCall(angle, stops);
526
+ }
527
+ function call() {
528
+ const head = peek();
529
+ if (head.kind !== "word")
530
+ throw expected("a call such as rect(...)");
531
+ callCount += 1;
532
+ if (callCount > maxCalls) {
533
+ throw new NodeBuildError("size", `Line ${head.line}, column ${head.column}: the source has more than ${maxCalls} calls.`, head.line, head.column);
534
+ }
535
+ next();
536
+ expect("(", `"(" after ${head.text}`);
537
+ const args = [];
538
+ while (!isPunctuation(peek(), ")")) {
539
+ const start = peek();
540
+ if (spelling === "tool" && isPunctuation(start, "-")) {
541
+ next();
542
+ const key = peek();
543
+ if (key.kind !== "word")
544
+ throw expected("a field name after -");
545
+ next();
546
+ args.push({ name: key.text, value: true, text: `-${key.text}`, remove: true, line: start.line, column: start.column });
547
+ if (isPunctuation(peek(), ","))
548
+ next();
549
+ else if (!isPunctuation(peek(), ")"))
550
+ throw expected("\",\" or \")\"");
551
+ continue;
552
+ }
553
+ const named = start.kind === "word" && isPunctuation(peek(1), ":");
554
+ if (named) {
555
+ next();
556
+ next();
557
+ }
558
+ const first = peek();
559
+ const read = named ? argumentValue(start.text) : value();
560
+ const text = source.slice(first.start, tokens[position - 1].end);
561
+ args.push({ name: named ? start.text : undefined, value: read, text, line: start.line, column: start.column });
562
+ if (isPunctuation(peek(), ","))
563
+ next();
564
+ else if (!isPunctuation(peek(), ")"))
565
+ throw expected("\",\" or \")\"");
566
+ }
567
+ next();
568
+ let children;
569
+ if (isPunctuation(peek(), "[")) {
570
+ next();
571
+ children = [];
572
+ while (!isPunctuation(peek(), "]")) {
573
+ children.push(call());
574
+ if (isPunctuation(peek(), ",") || (spelling === "tool" && isPunctuation(peek(), ";")))
575
+ next();
576
+ else if (!isPunctuation(peek(), "]"))
577
+ throw expected("\",\" or \"]\"");
578
+ }
579
+ next();
580
+ }
581
+ return { name: head.text, arguments: args, children, line: head.line, column: head.column };
582
+ }
583
+ return { source, toolSpelling: spelling === "tool", peek, next, isPunctuation, expect, expected, value, argumentValue, call };
584
+ }
585
+ /** Reads a source into calls; throws a `syntax` NodeBuildError naming the line, the column and what was expected. */
586
+ function parse(source, maxCalls = Infinity, spelling = "layer") {
587
+ const reader = layerSyntaxReader(source, spelling, maxCalls);
588
+ const calls = [];
589
+ while (reader.peek().kind !== "end") {
590
+ calls.push(reader.call());
591
+ if (reader.isPunctuation(reader.peek(), ",") || (reader.toolSpelling && reader.isPunctuation(reader.peek(), ";")))
592
+ reader.next();
593
+ }
594
+ if (calls.length === 0)
595
+ throw reader.expected("a call such as rect(...)");
596
+ return calls;
597
+ }
598
+ const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
599
+ /** Sets `node[path[0]][path[1]]...` to `value`, copying each object on the way. */
600
+ function setIn(node, path, value) {
601
+ const [first, ...rest] = path;
602
+ if (first === undefined)
603
+ return;
604
+ if (rest.length === 0) {
605
+ node[first] = value;
606
+ return;
607
+ }
608
+ const inner = record(node[first]);
609
+ setIn(inner, rest, value);
610
+ node[first] = inner;
611
+ }
612
+ /** A paint for a colour; any other value is the paint as written. */
613
+ const paintOf = (value) => typeof value === "string" ? { kind: "solid", color: value } : value;
614
+ /** Fills: one paint for a colour or an object, a paint for each item of a list. */
615
+ const fillsOf = (value) => Array.isArray(value) ? value.map(paintOf) : [paintOf(value)];
616
+ /**
617
+ * A stroke from `stroke:`, over `current`: a colour sets its paint, `(colour, width)` its paint and width,
618
+ * an object is the stroke as written.
619
+ */
620
+ function strokeOf(value, current) {
621
+ const base = { width: 1, ...record(current) };
622
+ if (Array.isArray(value)) {
623
+ const [colour, width] = value;
624
+ return { ...base, paint: paintOf(colour), ...(width === undefined ? {} : { width }) };
625
+ }
626
+ return typeof value === "string" ? { ...base, paint: paintOf(value) } : value;
627
+ }
628
+ /** Padding: one number for every side, `(vertical, horizontal)`, `(top, right, bottom, left)`, or as written. */
629
+ function paddingOf(value) {
630
+ if (!Array.isArray(value)) {
631
+ return typeof value === "number" ? { top: value, right: value, bottom: value, left: value } : value;
632
+ }
633
+ const sides = value;
634
+ if (sides.length === 2)
635
+ return { top: sides[0], right: sides[1], bottom: sides[0], left: sides[1] };
636
+ if (sides.length === 4)
637
+ return { top: sides[0], right: sides[1], bottom: sides[2], left: sides[3] };
638
+ return value;
639
+ }
640
+ /**
641
+ * A value a short argument cannot write, with what to write instead; `buildNodes` refuses the call with it, naming the
642
+ * argument's place, and the `edit` tool refuses the rule.
643
+ */
644
+ export class ShortArgumentError extends Error {
645
+ /** Names the argument whose place a refusal from a shorthand's `make` gives, when it is not the call's. */
646
+ argument;
647
+ constructor(message, argument) {
648
+ super(message);
649
+ this.argument = argument;
650
+ this.name = "ShortArgumentError";
651
+ }
652
+ }
653
+ /** The forms of a connector end, for refusals and help. */
654
+ export const CONNECTOR_END_FORMS = "#<id> (where the layer's outline faces the other end), #<id>.top, #<id>.right, #<id>.bottom or #<id>.left "
655
+ + "(the middle of that side), #<id>.vertex(<n>) or #<id>.edge(<n>) (corner n, or the middle of edge n, of a polygon, star or arc), "
656
+ + "#<id>.point(<x>, <y>) (a point on the layer, as fractions of its width and height), or (<x>, <y>) for a free end in the parent's coordinates";
657
+ /**
658
+ * Reads the value of `from:` or `to:` into the end the model stores; throws a ShortArgumentError naming the forms for a
659
+ * value of another shape. The words and numbers of a place go to the model as written, which judges them: a side
660
+ * that is not one, a fraction past 1, an index that is not a whole number.
661
+ */
662
+ function connectorEndOf(value, argument) {
663
+ const refuse = (what) => {
664
+ throw new ShortArgumentError(`${argument}:${what} is not a connector end; write ${CONNECTOR_END_FORMS}.`);
665
+ };
666
+ if (Array.isArray(value)) {
667
+ const [x, y] = value;
668
+ if (value.length !== 2 || typeof x !== "number" || typeof y !== "number")
669
+ return refuse(`(${value.map((item) => JSON.stringify(item)).join(", ")})`);
670
+ return { x, y };
671
+ }
672
+ const reference = typeof value === "string" ? readLayerReference(value) : undefined;
673
+ if (reference === undefined)
674
+ return refuse(typeof value === "string" ? value : JSON.stringify(value));
675
+ const nodeId = reference.id;
676
+ const { place } = reference;
677
+ const numbers = reference.numbers?.map((part) => NUMBER.test(part) ? Number(part) : undefined);
678
+ const count = (wanted, example) => {
679
+ if (numbers?.length !== wanted || numbers.some((number) => number === undefined)) {
680
+ throw new ShortArgumentError(`${argument}:${layerReferenceText(reference)}: ${place} takes ${wanted === 1 ? "one number" : `${wanted} numbers`}, as ${example}; `
681
+ + `write ${CONNECTOR_END_FORMS}.`);
682
+ }
683
+ return numbers;
684
+ };
685
+ if (place === undefined)
686
+ return { nodeId };
687
+ if (place === "vertex" || place === "edge")
688
+ return { nodeId, anchor: { kind: place, index: count(1, `#${reference.id}.${place}(2)`)[0] } };
689
+ if (place === "point") {
690
+ const [x, y] = count(2, `#${reference.id}.point(1, 0.5)`);
691
+ return { nodeId, point: { x: x, y: y } };
692
+ }
693
+ if (numbers !== undefined)
694
+ return refuse(layerReferenceText(reference));
695
+ return { nodeId, side: place };
696
+ }
697
+ /** A number of a record, or 0. */
698
+ const numberIn = (holder, key) => typeof holder[key] === "number" ? holder[key] : 0;
699
+ /**
700
+ * `from:` or `to:` of a connector: writes its `start` or `end`. A free end is placed at the point in the parent's
701
+ * coordinates; an attached end keeps the `x` and `y` it had, as the editor places it from its layer each time. With
702
+ * two free ends, the frame becomes the box around them, as `newConnectorNode` makes it.
703
+ */
704
+ const connectorEnd = (which, argument) => (node, value) => {
705
+ const end = connectorEndOf(value, argument);
706
+ const frame = record(node.frame);
707
+ const current = record(node[which]);
708
+ node[which] = end.nodeId === undefined
709
+ ? { x: end.x - numberIn(frame, "x"), y: end.y - numberIn(frame, "y") }
710
+ : { ...end, x: numberIn(current, "x"), y: numberIn(current, "y") };
711
+ const start = record(node.start), finish = record(node.end);
712
+ if (start.nodeId !== undefined || finish.nodeId !== undefined || node.frame === undefined)
713
+ return;
714
+ const points = [start, finish].map((point) => ({ x: numberIn(frame, "x") + numberIn(point, "x"), y: numberIn(frame, "y") + numberIn(point, "y") }));
715
+ const x = Math.min(points[0].x, points[1].x), y = Math.min(points[0].y, points[1].y);
716
+ node.frame = { ...frame, x, y, width: Math.abs(points[1].x - points[0].x), height: Math.abs(points[1].y - points[0].y) };
717
+ node.start = { ...start, x: points[0].x - x, y: points[0].y - y };
718
+ node.end = { ...finish, x: points[1].x - x, y: points[1].y - y };
719
+ };
720
+ const fill = (node, value) => setIn(node, ["style", "fills"], fillsOf(resolveLinearCalls(value, node)));
721
+ const stroke = (node, value) => {
722
+ const strokes = record(node.style).strokes;
723
+ setIn(node, ["style", "strokes"], [strokeOf(resolveLinearCalls(value, node), Array.isArray(strokes) ? strokes[0] : undefined)]);
724
+ };
725
+ /** One shadow from `(x, y, blur, spread, #colour)`, a drop shadow, or with `inner` after the colour; an object is the shadow as written. */
726
+ function shadowOf(value) {
727
+ if (!Array.isArray(value))
728
+ return value;
729
+ const [x, y, blur, spread, color, kind] = value;
730
+ return { kind: kind === "inner" ? "inner" : kind === undefined || kind === "drop" ? "drop" : kind, x, y, blur, spread, color };
731
+ }
732
+ /** Shadows: one for `(x, y, blur, spread, #colour)` or an object, one for each item of a list of them. */
733
+ const shadow = (node, value) => {
734
+ const many = Array.isArray(value) && value.length > 0 && (Array.isArray(value[0]) || isRecordValue(value[0]));
735
+ setIn(node, ["style", "shadows"], many ? value.map(shadowOf) : [shadowOf(value)]);
736
+ };
737
+ const isRecordValue = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
738
+ const radius = (node, value) => setIn(node, ["style", "cornerRadius"], value);
739
+ const layoutField = (field) => (node, value) => setIn(node, ["layout", field], value);
740
+ /** Writes into the first run's `overrides` of a text. */
741
+ const runOverride = (field) => (node, value) => {
742
+ const paragraphs = Array.isArray(node.paragraphs) ? [...node.paragraphs] : [];
743
+ const paragraph = record(paragraphs[0]);
744
+ const runs = Array.isArray(paragraph.runs) ? [...paragraph.runs] : [];
745
+ const run = record(runs[0]);
746
+ run.overrides = { ...record(run.overrides), [field]: value };
747
+ runs[0] = run;
748
+ paragraphs[0] = { ...paragraph, runs };
749
+ node.paragraphs = paragraphs;
750
+ };
751
+ const paragraphAlign = (node, value) => {
752
+ const paragraphs = Array.isArray(node.paragraphs) ? [...node.paragraphs] : [];
753
+ paragraphs[0] = { ...record(paragraphs[0]), align: value };
754
+ node.paragraphs = paragraphs;
755
+ };
756
+ const field = (name) => (node, value) => { node[name] = value; };
757
+ const shapeShorthand = (name, shape, summary) => ({
758
+ name, kind: { type: "shape", shape }, summary, takesChildren: false, defaultSize: { width: 100, height: 100 },
759
+ sizes: { fill: true, hug: false },
760
+ naming: { label: SHAPE_LABELS[shape] },
761
+ make: ({ id, name: layerName, box }) => newShapeNode(id, layerName, { kind: shape, frame: box }),
762
+ short: shape === "rectangle" ? { fill, stroke, radius, shadow } : { fill, stroke, shadow },
763
+ });
764
+ const flexShorthand = (name, kind) => ({
765
+ name, kind: { type: "frame" }, takesChildren: true, defaultSize: { width: 0, height: 0 }, sizes: { fill: true, hug: true },
766
+ summary: `A frame with ${kind} auto layout, hugging its content both ways, with no fill, as Add auto layout makes it. `
767
+ + "A number for `w` or `h` fixes that size. The layout places its children, so they take no x or y.",
768
+ naming: { label: "Frame", counts: (node) => node.type === "frame" },
769
+ make: ({ id, name: layerName, box, sizing }) => newWrapperNode("frame", id, layerName, box, {
770
+ ...newStackAutoLayout(kind),
771
+ ...(sizing.w === "fixed" || sizing.w === "fill" ? { widthSizing: "fixed" } : {}),
772
+ ...(sizing.h === "fixed" || sizing.h === "fill" ? { heightSizing: "fixed" } : {}),
773
+ }),
774
+ short: { fill, stroke, radius, shadow, gap: layoutField("gap"), pad: (node, value) => setIn(node, ["layout", "padding"], paddingOf(value)),
775
+ align: layoutField("align"), justify: layoutField("justify") },
776
+ });
777
+ // ---------------------------------------------------------------------------
778
+ // A path: d, SVG path data, and x, y, w and h as its bounds
779
+ /** The numbers each command of SVG path data takes, by its lower case letter, as refusals name them. */
780
+ const PATH_COMMANDS = {
781
+ m: "x y", l: "x y", h: "x", v: "y", c: "x1 y1 x2 y2 x y", s: "x2 y2 x y", q: "x1 y1 x y", t: "x y",
782
+ a: "rx ry rotation large-arc sweep x y", z: "",
783
+ };
784
+ const PATH_FORMS = `Write M x y first, then ${Object.entries(PATH_COMMANDS).filter(([letter]) => letter !== "m" && letter !== "z")
785
+ .map(([letter, numbers]) => `${letter.toUpperCase()} ${numbers}`).join(", ")} or Z; lower case is relative, as l6 6.`;
786
+ const PATH_NUMBER = /[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y;
787
+ /**
788
+ * The points of a path from `d`, SVG path data, as an SVG file draws them (`vectorNetworkFromSvgPathData`, as an imported
789
+ * SVG path). Throws a ShortArgumentError naming the command, its place in `d` (counting characters from 1) and the forms
790
+ * for data that does not start with M, a letter that is no command, a command with too few or too many numbers, an arc
791
+ * flag other than 0 or 1, a number too large, or data that draws nothing.
792
+ */
793
+ export function pathNetworkOf(value) {
794
+ if (typeof value !== "string")
795
+ throw new ShortArgumentError("d is SVG path data in a string, as d:'M0 0 L6 6 L12 0'.", "d");
796
+ const refuse = (message) => {
797
+ throw new ShortArgumentError(`d: ${message} ${PATH_FORMS}`, "d");
798
+ };
799
+ let index = 0;
800
+ let first = true;
801
+ const skip = () => { while (index < value.length && /[\s,]/.test(value[index]))
802
+ index += 1; };
803
+ skip();
804
+ if (index === value.length)
805
+ refuse("is empty.");
806
+ while (index < value.length) {
807
+ const letter = value[index];
808
+ const at = index + 1;
809
+ const lower = letter.toLowerCase();
810
+ const numbers = Object.hasOwn(PATH_COMMANDS, lower) ? PATH_COMMANDS[lower] : undefined;
811
+ if (numbers === undefined) {
812
+ refuse(first && /[-+.\d]/.test(letter) ? `starts with the number at character ${at}; it starts with M x y, the point to start from.`
813
+ : `${JSON.stringify(letter)} at character ${at} is not a command.`);
814
+ }
815
+ if (first && lower !== "m")
816
+ refuse(`starts with ${letter} at character ${at}; it starts with M x y, the point to start from.`);
817
+ first = false;
818
+ const end = value.slice(index + 1).search(/[a-df-zA-DF-Z]/);
819
+ const shown = value.slice(index, end === -1 ? value.length : index + 1 + end).trim().slice(0, 30);
820
+ const arity = numbers === "" ? 0 : numbers.split(" ").length;
821
+ index += 1;
822
+ let count = 0;
823
+ for (skip(); index < value.length && !/[a-df-zA-DF-Z]/.test(value[index]); skip()) {
824
+ if (lower === "a" && (count % 7 === 3 || count % 7 === 4)) {
825
+ // An arc's flags are one digit each and may be written without a space between them, as A5 5 0 0110 10.
826
+ if (value[index] !== "0" && value[index] !== "1") {
827
+ refuse(`${shown} at character ${at}: its ${count % 7 === 3 ? "large-arc" : "sweep"} flag at character ${index + 1} is 0 or 1.`);
828
+ }
829
+ index += 1;
830
+ count += 1;
831
+ continue;
832
+ }
833
+ PATH_NUMBER.lastIndex = index;
834
+ const number = PATH_NUMBER.exec(value)?.[0];
835
+ if (number === undefined)
836
+ refuse(`${JSON.stringify(value[index])} at character ${index + 1} is not a number or a command.`);
837
+ if (!Number.isFinite(Number(number)))
838
+ refuse(`${number} at character ${index + 1} is too large a number.`);
839
+ index += number.length;
840
+ count += 1;
841
+ }
842
+ if (arity === 0 ? count > 0 : count === 0 || count % arity !== 0) {
843
+ refuse(arity === 0 ? `${shown} at character ${at}: Z takes no numbers.`
844
+ : `${shown} at character ${at} takes ${arity === 1 ? "1 number" : `${arity} numbers`}, ${numbers}, and has ${count}.`);
845
+ }
846
+ }
847
+ let network;
848
+ try {
849
+ network = vectorNetworkFromSvgPathData(value);
850
+ }
851
+ catch (error) {
852
+ return refuse(error instanceof Error ? `${error.message}.` : String(error));
853
+ }
854
+ // Only segments draw: a path of moves alone, or of arcs that end where they start (which SVG skips), has none.
855
+ if (network.segments.length === 0)
856
+ refuse("draws nothing: write a line or a curve after M, as M0 0 L6 6.");
857
+ return network;
858
+ }
859
+ /**
860
+ * A path's points and transform with its bounds moved to `x` and `y` and sized to `w` and `h`, those given: `w` and `h` scale
861
+ * its points from the top-left corner of their bounds, as resizing a vector does, and `x` and `y` move its transform, so
862
+ * that the box around its points (`getVectorNetworkBounds`) has that corner and that size. The model judges the values:
863
+ * one that is not a number goes into the transform where it would have scaled or moved the path, for the model to refuse
864
+ * there. Throws a ShortArgumentError for a size of a path that has none that way (a straight line), and for `w` or `h` of a
865
+ * path whose transform turns or scales it.
866
+ */
867
+ export function placedPath(vectorNetwork, transform, place) {
868
+ const isNumber = (value) => typeof value === "number" && Number.isFinite(value);
869
+ let network = vectorNetwork;
870
+ let [a, b, c, d, tx, ty] = transform;
871
+ if (place.w !== undefined || place.h !== undefined) {
872
+ const key = place.w !== undefined ? "w" : "h";
873
+ if (a !== 1 || b !== 0 || c !== 0 || d !== 1) {
874
+ throw new ShortArgumentError(`${key} scales the path's points, and its transform turns or scales them; write its vectorNetwork and transform instead.`, key);
875
+ }
876
+ const bounds = getVectorNetworkBounds(network) ?? { x: 0, y: 0, width: 0, height: 0 };
877
+ const factor = { x: 1, y: 1 };
878
+ for (const [which, size] of [["w", bounds.width], ["h", bounds.height]]) {
879
+ const wanted = place[which];
880
+ if (wanted === undefined)
881
+ continue;
882
+ if (!isNumber(wanted)) {
883
+ if (which === "w")
884
+ a = wanted;
885
+ else
886
+ d = wanted;
887
+ continue;
888
+ }
889
+ if (size === 0) {
890
+ throw new ShortArgumentError(`${which} scales the path to that ${which === "w" ? "width" : "height"}, and it has none: it is a straight line. Leave out ${which}.`, which);
891
+ }
892
+ factor[which === "w" ? "x" : "y"] = wanted / size;
893
+ }
894
+ if (factor.x !== 1 || factor.y !== 1)
895
+ network = scaleVectorNetwork(network, factor, { x: bounds.x, y: bounds.y });
896
+ }
897
+ if (place.x !== undefined || place.y !== undefined) {
898
+ const numbers = [a, b, c, d, tx, ty];
899
+ const bounds = numbers.every(isNumber) ? getVectorNetworkBounds(network, numbers) ?? { x: tx, y: ty } : undefined;
900
+ if (place.x !== undefined)
901
+ tx = isNumber(place.x) && bounds !== undefined ? tx + place.x - bounds.x : place.x;
902
+ if (place.y !== undefined)
903
+ ty = isNumber(place.y) && bounds !== undefined ? ty + place.y - bounds.y : place.y;
904
+ }
905
+ return { vectorNetwork: network, transform: [a, b, c, d, tx, ty] };
906
+ }
907
+ /**
908
+ * A path from the syntax: drawn by `d` and placed by `x`, `y`, `w` and `h` (`placedPath`), and stroked 1 black, as a new
909
+ * line is, unless `fill` is given without `stroke` or `join`. Without `d`, its points are its model fields, and `x`, `y`,
910
+ * `w` and `h` are refused.
911
+ */
912
+ function newPathFromSyntax(id, name, given) {
913
+ const stroked = given.has("stroke") || given.has("join") || !given.has("fill");
914
+ const style = stroked ? { strokes: [{ paint: { kind: "solid", color: "#000000" }, width: 1 }] } : {};
915
+ const node = { id, name, visible: true, locked: false, opacity: 1, type: "shape", shape: "path", style };
916
+ const place = Object.fromEntries(["x", "y", "w", "h"].filter((key) => given.has(key)).map((key) => [key, given.get(key)]));
917
+ if (!given.has("d")) {
918
+ const key = Object.keys(place)[0];
919
+ if (key !== undefined)
920
+ throw new ShortArgumentError(`${key} places the points d draws; write d as well, or place the path by its transform.`, key);
921
+ return node;
922
+ }
923
+ return { ...node, ...placedPath(pathNetworkOf(given.get("d")), [1, 0, 0, 1, 0, 0], place) };
924
+ }
925
+ /** `cap` of a path: the end at both of its open ends, which the model judges. */
926
+ const pathCap = (node, value) => {
927
+ node.startCap = value;
928
+ node.endCap = value;
929
+ };
930
+ /** `winding` of a path: the rule that tells which parts of its loops are inside, nonzero (the default of `d`) or evenodd, which the model judges. */
931
+ const pathWinding = (node, value) => {
932
+ const network = record(node.vectorNetwork);
933
+ if (!Array.isArray(network.regions))
934
+ throw new ShortArgumentError("winding sets the rule of the loops d draws; give d as well.", "winding");
935
+ node.vectorNetwork = { ...network, regions: network.regions.map((region) => ({ ...record(region), windingRule: value })) };
936
+ };
937
+ /** `join` of a path: how each of its strokes turns a corner, which the model judges. */
938
+ const strokeJoin = (node, value) => {
939
+ const strokes = record(node.style).strokes;
940
+ if (!Array.isArray(strokes) || strokes.length === 0) {
941
+ throw new ShortArgumentError("join is how the stroke turns a corner, and this path has no stroke; give it stroke:<colour> as well.");
942
+ }
943
+ setIn(node, ["style", "strokes"], strokes.map((item) => ({ ...record(item), join: value })));
944
+ };
945
+ const SHORTHANDS = [
946
+ shapeShorthand("rect", "rectangle", "A rectangle, as the Rectangle tool draws it in the box."),
947
+ shapeShorthand("ellipse", "ellipse", "An ellipse, as the Ellipse tool draws it in the box."),
948
+ shapeShorthand("polygon", "polygon", "A polygon, as the Polygon tool draws it in the box."),
949
+ shapeShorthand("star", "star", "A star, as the Star tool draws it in the box."),
950
+ {
951
+ name: "line", kind: { type: "shape", shape: "line" }, takesChildren: false, defaultSize: { width: 100, height: 0 },
952
+ sizes: { fill: false, hug: false, points: "its w and h are how far its end is from its start" },
953
+ summary: "A line from (x, y) to (x + w, y + h), as the Line tool draws it; w and h may be negative (h:-7 ends the line 7 above its start).",
954
+ naming: { label: SHAPE_LABELS.line },
955
+ make: ({ id, name, box }) => newShapeNode(id, name, { kind: "line", start: { x: box.x, y: box.y },
956
+ end: { x: box.x + box.width, y: box.y + box.height } }),
957
+ short: { stroke },
958
+ },
959
+ {
960
+ name: "path", kind: { type: "shape", shape: "path" }, content: "d", takesChildren: false, defaultSize: { width: 0, height: 0 },
961
+ sizes: { fill: false, hug: false },
962
+ summary: "A vector path drawn by `d`, SVG path data in the path's own coordinates (M, L, H, V, C, S, Q, T, A and Z; lower case "
963
+ + "is relative), stroked 1 black unless only `fill` is given. Its x, y, w and h are its bounds: given, they move the drawing "
964
+ + "and scale it to them. `cap` sets both ends (none, round, square or an arrow), `join` how its stroke turns a corner "
965
+ + "(miter, bevel or round), `winding` which parts of its loops it fills (nonzero, or evenodd). Without `d` its points are its model fields vectorNetwork and transform.",
966
+ naming: { label: "Vector" },
967
+ make: ({ id, name, given }) => newPathFromSyntax(id, name, given),
968
+ short: { fill, stroke, shadow, cap: pathCap, join: strokeJoin, winding: pathWinding },
969
+ },
970
+ {
971
+ name: "text", kind: { type: "text" }, content: "text", takesChildren: false, defaultSize: { width: 0, height: 0 },
972
+ sizes: { fill: true, hug: true, hugsByDefault: true },
973
+ summary: "One paragraph of one run in the default text style, sized to its content, as the Text tool makes it; `text` is its characters. "
974
+ + "Without `w` it hugs its content both ways. A number or fill for `w` fixes the width and wraps words, and the height follows the text "
975
+ + "unless `h` is a number or fill too. "
976
+ + "`size`, `weight`, `color` and `font` go to the run's `overrides`; `align` to the paragraph. "
977
+ + "`font` and `weight` name a face, which must be one document.inspect lists in `fonts`; the editor adds that face's font asset in the same step. "
978
+ + "A family marked `needsRead` is installed on the person's computer and may be named at once: the editor reads its file before the step lands.",
979
+ naming: { label: "Text", counts: (node) => node.type === "text" },
980
+ make: ({ document, id, name, box, given, sizing }) => {
981
+ const fixedWidth = sizing.w === "fixed" || sizing.w === "fill";
982
+ const node = newTextNode(document, id, name, box, fixedWidth ? "fixed" : "auto");
983
+ const text = given.get("text") ?? "";
984
+ return { ...node, paragraphs: [{ runs: [{ text: text }] }],
985
+ ...(fixedWidth && (sizing.h === undefined || sizing.h === "hug") ? { autoResize: "height" } : {}) };
986
+ },
987
+ short: { size: runOverride("fontSize"), weight: runOverride("fontWeight"), color: runOverride("color"), font: runOverride("fontFamily"),
988
+ align: paragraphAlign },
989
+ },
990
+ {
991
+ name: "frame", kind: { type: "frame" }, takesChildren: true, defaultSize: { width: 100, height: 100 }, sizes: { fill: true, hug: false },
992
+ summary: "A frame with free layout and a white fill, as the Frame tool draws it. Its children keep their x and y.",
993
+ naming: { label: "Frame", counts: (node) => node.type === "frame" },
994
+ make: ({ id, name, box }) => newFrameNode(id, name, box),
995
+ short: { fill, stroke, radius, shadow },
996
+ },
997
+ flexShorthand("hflex", "horizontal"),
998
+ flexShorthand("vflex", "vertical"),
999
+ {
1000
+ name: "group", kind: { type: "group" }, takesChildren: true, defaultSize: { width: 0, height: 0 }, sizes: { fill: false, hug: false },
1001
+ summary: "A group of its children, as the Group command makes it: its box is the box around them, at x and y.",
1002
+ naming: { label: "Group", counts: (node) => node.type === "group" && node.name.startsWith("Group ") },
1003
+ make: ({ id, name, box }) => newWrapperNode("group", id, name, box),
1004
+ short: {},
1005
+ // Its size is the box around its children.
1006
+ without: ["w", "h"],
1007
+ },
1008
+ {
1009
+ name: "image", kind: { type: "image" }, takesChildren: false, defaultSize: { width: 100, height: 100 }, sizes: { fill: true, hug: false },
1010
+ summary: "An image of the asset `asset` (an image asset the document holds, or one image.add answered, which the step adds), filling its box, as a dropped image makes it.",
1011
+ naming: { label: "Image", counts: () => false },
1012
+ make: ({ id, name, box, given }) => newMediaNode("image", id, name, box, (given.get("asset") ?? ""), name),
1013
+ short: { asset: field("assetId") },
1014
+ },
1015
+ {
1016
+ name: "code", kind: { type: "code" }, content: "source", takesChildren: false, defaultSize: { width: 640, height: 360 },
1017
+ sizes: { fill: true, hug: true },
1018
+ summary: "A TypeScript code block in the document's default code style, as the Code tool draws it; `source` is its code. "
1019
+ + "`w:hug` fits it to its code both ways, `h:hug` its height only. `size` and `font` set its font size and family.",
1020
+ naming: { label: "Code", counts: (node) => node.type === "code" },
1021
+ make: ({ id, name, box, given, codeStyle, sizing }) => ({ ...newCodeNode(id, name, box, codeStyle), source: (given.get("source") ?? ""),
1022
+ ...(sizing.w === "hug" ? { autoResize: "width-and-height" } : sizing.h === "hug" ? { autoResize: "height" } : {}) }),
1023
+ short: { size: field("fontSize"), font: field("fontFamily") },
1024
+ },
1025
+ {
1026
+ name: "connector", kind: { type: "connector" }, takesChildren: false, defaultSize: { width: 100, height: 100 },
1027
+ sizes: { fill: false, hug: false, points: "its w and h are how far its end is from its start" },
1028
+ summary: "A connector from (x, y) to (x + w, y + h), as the Connector tool draws it. `from` and `to` place its start and end instead: "
1029
+ + "a layer's id in a string attaches the end to that layer, as from:\"#a.right\" (side top, right, bottom or left), \"#a.vertex(2)\", "
1030
+ + "\"#a.edge(0)\", \"#a.point(0.5, 1)\" (fractions of its size) or \"#a\" (the outline facing the other end); (x, y) is a free end.",
1031
+ naming: { label: "Connector", counts: (node) => node.type === "connector" },
1032
+ make: ({ id, name, box }) => newConnectorNode({ start: { x: box.x, y: box.y }, end: { x: box.x + box.width, y: box.y + box.height } }, id, name),
1033
+ short: { from: connectorEnd("start", "from"), to: connectorEnd("end", "to"), stroke: (node, value) => { node.stroke = strokeOf(resolveLinearCalls(value, node), node.stroke); } },
1034
+ },
1035
+ {
1036
+ name: "instance", kind: { type: "instance" }, takesChildren: false, defaultSize: { width: 100, height: 100 }, sizes: { fill: true, hug: false },
1037
+ summary: "An instance of the component `componentId` (an id of the document's components), as the Assets panel places it: named "
1038
+ + "as the component and as large as its root, unless `name`, `w` or `h` is given. Its prop values and overrides are its model fields "
1039
+ + "`propertyValues` (by property id) and `overrides` (by layer path). Its filled slots are `slots`, by nested instance path "
1040
+ + "(\"\" for its own) and then slot property id, each given as a list of the calls of the slot's layers, as "
1041
+ + "slots:{\"\":{\"<slot id>\":(rect(w:40, h:40))}}; the build makes a slot host for each list. "
1042
+ + "`slot` on a frame inside a component binds it to the slot property with that id, or with that name, which the build adds to the component when it has none.",
1043
+ naming: { label: "Instance", counts: () => false },
1044
+ make: ({ document, id, name, box, sizing, fields }) => {
1045
+ const componentId = fields.get("componentId");
1046
+ if (typeof componentId !== "string" || entryOf(document.components ?? {}, componentId) === undefined) {
1047
+ // An instance of no component the document holds: the model refuses it, naming the component.
1048
+ return { id, name, visible: true, locked: false, opacity: 1, type: "instance", frame: box, rotation: 0 };
1049
+ }
1050
+ const placed = newInstanceNode(document, { componentId: componentId, x: box.x, y: box.y }, () => id);
1051
+ // A size written as a number is kept as Fixed: `buildNodes` adds that override after the call's own overrides.
1052
+ return { ...placed, name, frame: { ...placed.frame, ...(sizing.w === "fixed" ? { width: box.width } : {}),
1053
+ ...(sizing.h === "fixed" ? { height: box.height } : {}) } };
1054
+ },
1055
+ short: {},
1056
+ },
1057
+ ];
1058
+ /**
1059
+ * Shorthands of the tool spelling only, for the kinds of layer the shorthands above do not make, so that
1060
+ * the printer of `layer-syntax.ts` can print every layer: each makes the fields every layer has, and its other
1061
+ * fields are written by their model names. `buildNodes` in the default spelling does not take them.
1062
+ */
1063
+ const TOOL_SHORTHANDS = [
1064
+ {
1065
+ name: "video", kind: { type: "video" }, takesChildren: false, defaultSize: { width: 100, height: 100 }, sizes: { fill: true, hug: false },
1066
+ summary: "A video of the asset `asset`, filling its box.",
1067
+ naming: { label: "Video", counts: () => false },
1068
+ make: ({ id, name, box, given }) => newMediaNode("video", id, name, box, (given.get("asset") ?? ""), name),
1069
+ short: { asset: field("assetId") },
1070
+ },
1071
+ ];
1072
+ const toolShorthandsByName = new Map(TOOL_SHORTHANDS.map((shorthand) => [shorthand.name, shorthand]));
1073
+ /** The shorthand named `name` in the tool spelling (every shorthand of `buildNodes`, and video). */
1074
+ export function toolShorthand(name) {
1075
+ return shorthandsByName.get(name) ?? toolShorthandsByName.get(name);
1076
+ }
1077
+ /** The short arguments every shorthand takes. */
1078
+ const COMMON_SHORT_NAMES = ["x", "y", "w", "h", "id", "name", "opacity"];
1079
+ /**
1080
+ * Model fields a shorthand does not pass through: its call name gives `type` and `shape`, its `[...]` the `children`;
1081
+ * the `AGENT_HIDDEN_NODE_FIELDS` are the person's, never written by an agent.
1082
+ */
1083
+ const NOT_PASSED = new Set(["type", "shape", "children", ...AGENT_HIDDEN_NODE_FIELDS]);
1084
+ const shorthandsByName = new Map(SHORTHANDS.map((shorthand) => [shorthand.name, shorthand]));
1085
+ /** The short names a shorthand accepts, in the order the table shows them. */
1086
+ export function shortNamesOf(shorthand) {
1087
+ const common = COMMON_SHORT_NAMES.filter((name) => !(shorthand.without ?? []).includes(name));
1088
+ return [...(shorthand.content === undefined ? [] : [shorthand.content]), ...common, ...Object.keys(shorthand.short)];
1089
+ }
1090
+ /**
1091
+ * The names the old form of the language gave values without a name, in order: the content (when the value
1092
+ * is a string), then x, y, w, h, or those of them the shorthand takes. Only to show such a call rewritten.
1093
+ */
1094
+ function oldPositionNamesOf(shorthand) {
1095
+ return [...(shorthand.content === undefined ? [] : [shorthand.content]),
1096
+ ...["x", "y", "w", "h"].filter((name) => !(shorthand.without ?? []).includes(name))];
1097
+ }
1098
+ /** What `w` and `h` of a shorthand take, in words: `a number`, `a number or fill`, `a number, fill or hug`. */
1099
+ function sizeWordsOf(shorthand) {
1100
+ const words = ["a number", ...(shorthand.sizes.fill ? ["fill"] : []), ...(shorthand.sizes.hug ? ["hug"] : [])];
1101
+ return words.length === 1 ? words[0] : `${words.slice(0, -1).join(", ")} or ${words[words.length - 1]}`;
1102
+ }
1103
+ /** The model fields a shorthand passes through unchanged. */
1104
+ export function modelFieldsOf(shorthand) {
1105
+ return sceneNodeFieldNames(shorthand.kind).filter((name) => !NOT_PASSED.has(name));
1106
+ }
1107
+ /** Every shorthand of `buildNodes`, with its arguments. */
1108
+ export function nodeShorthands() {
1109
+ return SHORTHANDS.map((shorthand) => ({
1110
+ name: shorthand.name, kind: shorthand.kind, summary: shorthand.summary,
1111
+ ...(shorthand.content === undefined ? {} : { content: shorthand.content }),
1112
+ takesChildren: shorthand.takesChildren, arguments: shortNamesOf(shorthand),
1113
+ ...((shorthand.without ?? []).includes("w") ? {} : { sizes: sizeWordsOf(shorthand) }),
1114
+ modelFields: modelFieldsOf(shorthand),
1115
+ }));
1116
+ }
1117
+ /**
1118
+ * The shorthands as lines of text, one each: its call form, what it makes, and its arguments. Help texts
1119
+ * show this table, so that it always lists the shorthands `buildNodes` has.
1120
+ */
1121
+ export function nodeShorthandTable() {
1122
+ return nodeShorthands().map((shorthand) => {
1123
+ const form = `${shorthand.name}(${shorthand.arguments.join(", ")})`;
1124
+ const sizes = shorthand.sizes === undefined ? "" : ` w and h: ${shorthand.sizes}.`;
1125
+ return `${form}${shorthand.takesChildren ? "[...]" : ""}: ${shorthand.summary}${sizes}`;
1126
+ });
1127
+ }
1128
+ /** A component call the syntax cannot make, from the helpers below; `buildNodes` adds the place, `layer-syntax.ts` the layer. */
1129
+ export class ComponentCallError extends Error {
1130
+ at;
1131
+ constructor(message, at) {
1132
+ super(message);
1133
+ this.at = at;
1134
+ this.name = "ComponentCallError";
1135
+ }
1136
+ }
1137
+ /**
1138
+ * The call name of a component in the tool spelling, from its model name: split at `/` (the folders of the Assets
1139
+ * panel), each part in lower case with every run of characters other than a to z and 0 to 9 written as one `-`, a `-` at
1140
+ * either end left out and a part that starts with a digit given a `c` in front, the parts joined by `.`: "Button" is
1141
+ * `button`, "Forms/Text" is `forms.text`, "Icon / Arrow Left" is `icon.arrow-left`. Undefined for a name with no letter or
1142
+ * digit, which no call name can write.
1143
+ */
1144
+ export function componentCallName(name) {
1145
+ const parts = name.split("/").map((part) => part.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, ""))
1146
+ .filter((part) => part !== "").map((part) => /^[0-9]/.test(part) ? `c${part}` : part);
1147
+ return parts.length === 0 ? undefined : parts.join(".");
1148
+ }
1149
+ /** A call name as written, in the form `componentCallName` gives: lower case, `_` read as `-` and a run of `-` as one. */
1150
+ export function normalisedCallName(written) {
1151
+ return written.toLowerCase().replace(/_/g, "-").replace(/-{2,}/g, "-");
1152
+ }
1153
+ const LIST_LIMIT = 20;
1154
+ const listed = (items) => items.length <= LIST_LIMIT ? items.join(", ") : `${items.slice(0, LIST_LIMIT).join(", ")} and ${items.length - LIST_LIMIT} more`;
1155
+ const componentNamesByDocument = new WeakMap();
1156
+ /** The components of `document` by their call names (see `componentCallName`). */
1157
+ export function componentNames(document) {
1158
+ const cached = componentNamesByDocument.get(document);
1159
+ if (cached !== undefined)
1160
+ return cached;
1161
+ const components = Object.values(document.components ?? {});
1162
+ const whole = new Map(), last = new Map();
1163
+ const callNames = new Map();
1164
+ const add = (map, key, component) => map.set(key, [...(map.get(key) ?? []), component]);
1165
+ for (const component of components) {
1166
+ const name = componentCallName(component.name);
1167
+ if (name === undefined)
1168
+ continue;
1169
+ callNames.set(component.id, name);
1170
+ add(whole, name, component);
1171
+ add(last, name.slice(name.lastIndexOf(".") + 1), component);
1172
+ }
1173
+ const callNameOf = (component) => {
1174
+ const name = callNames.get(component.id);
1175
+ if (name === undefined || whole.get(name).length > 1)
1176
+ return undefined;
1177
+ const first = name.split(".")[0];
1178
+ const plain = name.includes(".") ? first !== "std" && first !== "doc" : toolShorthand(name) === undefined && last.get(name).length === 1;
1179
+ return plain ? name : `doc.${name}`;
1180
+ };
1181
+ const shownAll = () => listed(components.flatMap((component) => {
1182
+ const name = callNameOf(component);
1183
+ return name === undefined ? [] : [name];
1184
+ }));
1185
+ const byWholeName = (name, written) => {
1186
+ const found = whole.get(name) ?? [];
1187
+ if (found.length === 1)
1188
+ return { kind: "component", component: found[0] };
1189
+ if (found.length > 1) {
1190
+ throw new ComponentCallError(`${written} is the call name of ${found.length} components (${found.map((component) => `${JSON.stringify(component.name)}, id ${component.id}`).join("; ")}), `
1191
+ + `so none of them can be called by name: write instance(componentId:'${found[0].id}', ...) with the id of the one you mean.`);
1192
+ }
1193
+ const sameLast = last.get(name.slice(name.lastIndexOf(".") + 1)) ?? [];
1194
+ throw new ComponentCallError(`there is no component ${name}. `
1195
+ + (sameLast.length > 0 ? `Components with that last part: ${listed(sameLast.map((component) => callNameOf(component) ?? callNames.get(component.id)))}.`
1196
+ : components.length === 0 ? "The document has no components." : `The components are ${shownAll()}.`));
1197
+ };
1198
+ const names = {
1199
+ components,
1200
+ byId: (id) => components.find((component) => component.id === id),
1201
+ callNameOf,
1202
+ named(written) {
1203
+ const name = normalisedCallName(written);
1204
+ if (name.startsWith("std."))
1205
+ return [];
1206
+ if (name.startsWith("doc."))
1207
+ return whole.get(name.slice(4)) ?? [];
1208
+ return (name.includes(".") ? whole : last).get(name) ?? [];
1209
+ },
1210
+ resolve(written) {
1211
+ const name = normalisedCallName(written);
1212
+ if (name.startsWith("std.")) {
1213
+ const shorthand = toolShorthand(name.slice(4));
1214
+ if (shorthand !== undefined)
1215
+ return { kind: "shorthand", shorthand };
1216
+ throw new ComponentCallError(`there is no shorthand ${name.slice(4)} in std; the shorthands are ${[...SHORTHANDS, ...TOOL_SHORTHANDS].map((entry) => entry.name).join(", ")}.`);
1217
+ }
1218
+ if (name.startsWith("doc."))
1219
+ return byWholeName(name.slice(4), written);
1220
+ if (name.includes("."))
1221
+ return byWholeName(name, written);
1222
+ const shorthand = toolShorthand(name);
1223
+ if (shorthand !== undefined)
1224
+ return { kind: "shorthand", shorthand };
1225
+ const found = last.get(name) ?? [];
1226
+ if (found.length === 1)
1227
+ return { kind: "component", component: found[0] };
1228
+ if (found.length > 1) {
1229
+ throw new ComponentCallError(`${written} is the last part of the call names of ${found.length} components: `
1230
+ + `${found.map((component) => callNameOf(component) ?? callNames.get(component.id)).join(", ")}; write one of them.`);
1231
+ }
1232
+ return undefined;
1233
+ },
1234
+ };
1235
+ componentNamesByDocument.set(document, names);
1236
+ return names;
1237
+ }
1238
+ /** The call names of the document's components, for a refusal; empty without components. */
1239
+ export function componentCallNames(document) {
1240
+ const names = componentNames(document);
1241
+ return names.components.flatMap((component) => {
1242
+ const name = names.callNameOf(component);
1243
+ return name === undefined ? [] : [name];
1244
+ });
1245
+ }
1246
+ /**
1247
+ * The components of `document` that `component.list` lists, in document order: those after the component `after`, when
1248
+ * given, that are among `ids` and that one of `callNames` may name (`ComponentNames.named`), when given. Undefined when
1249
+ * `after` is no component of the document.
1250
+ */
1251
+ export function listedComponents(document, query) {
1252
+ const names = componentNames(document);
1253
+ let components = names.components;
1254
+ if (query.after !== undefined) {
1255
+ const at = components.findIndex((component) => component.id === query.after);
1256
+ if (at < 0)
1257
+ return undefined;
1258
+ components = components.slice(at + 1);
1259
+ }
1260
+ if (query.ids !== undefined) {
1261
+ const ids = new Set(query.ids);
1262
+ components = components.filter((component) => ids.has(component.id));
1263
+ }
1264
+ if (query.callNames !== undefined) {
1265
+ const named = new Set(query.callNames.flatMap((written) => names.named(written)));
1266
+ components = components.filter((component) => named.has(component));
1267
+ }
1268
+ return components;
1269
+ }
1270
+ /** Where an instance call writes props in `props:{...}`, and the inner layers' overrides in `over:{...}`. */
1271
+ export const INSTANCE_PROPS_ARGUMENT = "props";
1272
+ export const INSTANCE_OVER_ARGUMENT = "over";
1273
+ let instanceArguments;
1274
+ /** The arguments of an instance call other than its component's props: its layer's short arguments and model fields, `over` and `props`. */
1275
+ export function instanceCallArguments() {
1276
+ const instance = shorthandsByName.get("instance");
1277
+ instanceArguments ??= new Set([...shortNamesOf(instance), ...modelFieldsOf(instance), INSTANCE_OVER_ARGUMENT, INSTANCE_PROPS_ARGUMENT]);
1278
+ return instanceArguments;
1279
+ }
1280
+ /** Whether a prop is written in `props:{...}`: its name is another argument of an instance call (a person may call a prop `name`). */
1281
+ export const propertyInProps = (property) => instanceCallArguments().has(property.name);
1282
+ /**
1283
+ * A key of `over:{...}` that the tool spelling reads bare, as one word: names joined by `.`, each a letter or `_` and then
1284
+ * letters, digits, `_` and `-`.
1285
+ */
1286
+ export const BARE_OVER_KEY = /^[A-Za-z_][A-Za-z0-9_-]*(?:\.[A-Za-z_][A-Za-z0-9_-]*)*$/;
1287
+ /** A layer name, or names joined by `.`, as a key of `over:{...}` writes it: bare when it can be, else in single quotes. */
1288
+ const shownKey = (name) => BARE_OVER_KEY.test(name) ? name : `'${name.replaceAll("'", "''")}'`;
1289
+ /** A value as a refusal shows it, in the tool spelling. */
1290
+ function shownValue(value) {
1291
+ if (typeof value === "string")
1292
+ return /^#|^[a-z][a-z0-9_-]*$/.test(value) ? value : `'${value.replaceAll("'", "''")}'`;
1293
+ return typeof value === "number" || typeof value === "boolean" ? String(value) : JSON.stringify(value);
1294
+ }
1295
+ /** What a prop takes, in words, for a refusal. */
1296
+ function propertyKindWords(property, names, option = (name) => name) {
1297
+ switch (property.kind) {
1298
+ case "boolean": return "true or false";
1299
+ case "number": return "a number";
1300
+ case "text": return "a text";
1301
+ case "color": return "a colour";
1302
+ case "enum": return `one of ${property.options.map((candidate) => option(candidate.name)).join(", ")}`;
1303
+ case "instance": return `a component, as ${shownComponent(property.defaultValue, names)}`;
1304
+ }
1305
+ }
1306
+ const shownComponent = (id, names) => {
1307
+ const component = names.byId(id);
1308
+ return (component === undefined ? undefined : names.callNameOf(component)) ?? `the component ${id}`;
1309
+ };
1310
+ /**
1311
+ * The props of a component as a refusal lists them: each with what it takes and its default. In the `expression` form,
1312
+ * for a refusal of an expression, each prop and option name is written as an expression reads it: in backticks when
1313
+ * it is not a plain word, an option after a dot, as `` `Primary / Hover` `` and `` .`Extra large` ``.
1314
+ */
1315
+ export function componentPropertyList(component, names, form = "call") {
1316
+ const properties = (component.properties ?? []).filter(isValuedComponentProperty);
1317
+ if (properties.length === 0)
1318
+ return `${names.callNameOf(component) ?? component.name} has no props`;
1319
+ const inExpression = form === "expression";
1320
+ const name = inExpression ? formatExpressionName : (written) => written;
1321
+ const option = inExpression ? (written) => `.${formatExpressionName(written)}` : name;
1322
+ const default_ = (property) => {
1323
+ if (property.kind !== "enum")
1324
+ return property.kind === "instance" ? shownComponent(property.defaultValue, names) : shownValue(property.defaultValue);
1325
+ const chosen = property.options.find((candidate) => candidate.id === property.defaultValue);
1326
+ return chosen === undefined ? property.defaultValue : option(chosen.name);
1327
+ };
1328
+ return `its props are ${properties.map((property) => `${name(property.name)} (${propertyKindWords(property, names, option)}; default ${default_(property)}`
1329
+ + `${!inExpression && propertyInProps(property) ? `; written props:{${property.name}:...}` : ""})`).join(", ")}`;
1330
+ }
1331
+ /**
1332
+ * For a refusal of an expression: a sentence saying that a name that is not a plain word is written in backticks, with
1333
+ * the first prop name of `component` that needs them as the example, else the first such option; empty when every name
1334
+ * is a plain word.
1335
+ */
1336
+ export function expressionBacktickHint(component) {
1337
+ const properties = component.properties ?? [];
1338
+ const property = properties.find((candidate) => !isBareExpressionName(candidate.name));
1339
+ const option = properties.flatMap((candidate) => candidate.kind === "enum" ? candidate.options : []).find((candidate) => !isBareExpressionName(candidate.name));
1340
+ const example = property !== undefined ? formatExpressionName(property.name) : option !== undefined ? `.${formatExpressionName(option.name)}` : undefined;
1341
+ return example === undefined ? "" : ` In an expression a name that is not a plain word is written in backticks, as ${example}.`;
1342
+ }
1343
+ /**
1344
+ * The value an instance stores for `property` from a value written in the syntax: an option's name for an enum (its id is
1345
+ * stored), a component's call name for an instance swap (its id is stored), else the value itself when it has the prop's
1346
+ * kind. Throws a ComponentCallError that shows the right form.
1347
+ */
1348
+ export function propertyValueFromSyntax(component, property, value, names) {
1349
+ const shown = `${property.name} of ${names.callNameOf(component) ?? component.name}`;
1350
+ const write = (example) => property.kind === "enum" || property.kind === "instance" || !propertyInProps(property)
1351
+ ? `${property.name}:${example}` : `props:{${property.name}:${example}}`;
1352
+ switch (property.kind) {
1353
+ case "boolean":
1354
+ if (typeof value === "boolean")
1355
+ return value;
1356
+ throw new ComponentCallError(`${shown} is true or false; write ${write(String(!property.defaultValue))}.`);
1357
+ case "number":
1358
+ if (typeof value === "number" && Number.isFinite(value))
1359
+ return value;
1360
+ throw new ComponentCallError(`${shown} is a number; write ${write(String(property.defaultValue))}.`);
1361
+ case "text":
1362
+ if (typeof value === "string")
1363
+ return value;
1364
+ throw new ComponentCallError(`${shown} is a text; write ${write(shownValue(typeof value === "number" ? String(value) : property.defaultValue))}.`);
1365
+ case "color":
1366
+ if (typeof value === "string")
1367
+ return value;
1368
+ throw new ComponentCallError(`${shown} is a colour; write ${write(property.defaultValue)}.`);
1369
+ case "enum": {
1370
+ // Option names are stored in NFC; a value typed decomposed names the same option.
1371
+ const option = typeof value === "string" ? property.options.find((candidate) => candidate.name === normalizeExpressionName(value)) : undefined;
1372
+ if (option !== undefined)
1373
+ return option.id;
1374
+ const near = typeof value === "string" ? property.options.find((candidate) => candidate.name.toLowerCase() === value.toLowerCase()) : undefined;
1375
+ throw new ComponentCallError(`${shown} is one of ${property.options.map((candidate) => candidate.name).join(", ")}; `
1376
+ + `write ${write((near ?? property.options[0]).name)}.`);
1377
+ }
1378
+ case "instance": {
1379
+ let resolved;
1380
+ try {
1381
+ resolved = typeof value === "string" ? names.resolve(value) : undefined;
1382
+ }
1383
+ catch (error) {
1384
+ if (error instanceof ComponentCallError)
1385
+ throw new ComponentCallError(`${shown}: ${error.message}`);
1386
+ throw error;
1387
+ }
1388
+ if (resolved?.kind === "component")
1389
+ return resolved.component.id;
1390
+ throw new ComponentCallError(`${shown} is a component, written by its call name; write ${write(shownComponent(property.defaultValue, names))}.`);
1391
+ }
1392
+ }
1393
+ }
1394
+ /** The fields of an override that a short name writes, as the shorthands write them on a layer. */
1395
+ export const OVERRIDE_SHORT_NAMES = ["text", "color", "size", "weight", "font", "fill", "stroke", "visible", "opacity"];
1396
+ /** The text style fields `color`, `size`, `weight` and `font` of an override write, as those of a text write its run's. */
1397
+ export const OVERRIDE_TEXT_STYLE_FIELDS = { color: "color", size: "fontSize", weight: "fontWeight", font: "fontFamily" };
1398
+ /** The layers of a component, root first, in tree order, as `document` holds them; a nested instance is one layer. */
1399
+ export function componentLayers(document, component) {
1400
+ const layers = [];
1401
+ const visit = (id, depth) => {
1402
+ if (depth > 1000)
1403
+ throw new ComponentCallError(`the layers of ${component.name} are nested more than 1000 deep.`);
1404
+ const node = entryOf(document.nodes, id);
1405
+ if (node === undefined)
1406
+ return;
1407
+ layers.push(node);
1408
+ if (isContainerNode(node))
1409
+ node.children.forEach((child) => visit(child, depth + 1));
1410
+ };
1411
+ visit(component.rootId, 0);
1412
+ return layers;
1413
+ }
1414
+ /** How many layers `overridePaths` lists at most, so that instances nested many times over cannot make the list explode. */
1415
+ const OVERRIDE_PATH_LIMIT = 10_000;
1416
+ /**
1417
+ * The layers of a component that `over:{...}` can name, root first, depth-first as the layers panel shows them: each
1418
+ * layer of the component, and right after a nested instance the layers of that instance's component, through as many
1419
+ * nested instances as `document` holds the layers of. A component inside itself is not entered again.
1420
+ */
1421
+ export function overridePaths(document, component) {
1422
+ const paths = [];
1423
+ const visit = (current, ids, names, entered) => {
1424
+ for (const layer of componentLayers(document, current)) {
1425
+ if (paths.length >= OVERRIDE_PATH_LIMIT)
1426
+ return;
1427
+ const layerIds = [...ids, layer.id], layerNames = [...names, layer.name];
1428
+ paths.push({ key: layerIds.join(";"), name: layerNames.join(".") });
1429
+ if (layer.type !== "instance" || layer.id === current.rootId)
1430
+ continue;
1431
+ const nested = entryOf(document.components ?? {}, layer.componentId);
1432
+ if (nested !== undefined && !entered.has(nested.id) && entryOf(document.nodes, nested.rootId) !== undefined) {
1433
+ visit(nested, layerIds, layerNames, new Set([...entered, nested.id]));
1434
+ }
1435
+ }
1436
+ };
1437
+ visit(component, [], [], new Set([component.id]));
1438
+ return paths;
1439
+ }
1440
+ /** One override, `{field:value, ...}` with the short names of `OVERRIDE_SHORT_NAMES` and the override's model fields. */
1441
+ function layerOverrideFromSyntax(value, shown) {
1442
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
1443
+ throw new ComponentCallError(`the override of ${shown} is an object of fields, as {color:#ffffff, text:'Go'}.`);
1444
+ }
1445
+ const fields = value;
1446
+ const override = {};
1447
+ for (const [key, item] of Object.entries(fields)) {
1448
+ if (layerOverrideFieldNames.includes(key))
1449
+ override[key] = item;
1450
+ else if (!OVERRIDE_SHORT_NAMES.includes(key)) {
1451
+ throw new ComponentCallError(`an instance cannot change ${key} of ${shown}: an override takes ${OVERRIDE_SHORT_NAMES.join(", ")}, `
1452
+ + `or ${layerOverrideFieldNames.filter((name) => name !== "visible" && name !== "opacity").join(", ")} by their model names. `
1453
+ + "To change anything else, change the component, or detach the instance.");
1454
+ }
1455
+ }
1456
+ // The short names write on top of the model fields, as a call's short arguments do.
1457
+ for (const [key, item] of Object.entries(fields)) {
1458
+ if (key === "text")
1459
+ override.characters = item;
1460
+ else if (Object.hasOwn(OVERRIDE_TEXT_STYLE_FIELDS, key))
1461
+ override.textStyle = { ...record(override.textStyle), [OVERRIDE_TEXT_STYLE_FIELDS[key]]: item };
1462
+ else if (key === "fill")
1463
+ override.fills = fillsOf(item);
1464
+ else if (key === "stroke")
1465
+ override.strokes = [strokeOf(item, Array.isArray(override.strokes) ? override.strokes[0] : undefined)];
1466
+ }
1467
+ return override;
1468
+ }
1469
+ /**
1470
+ * The overrides of `over:{...}` by layer path: each key names a layer of the component by its layer name, a layer inside
1471
+ * a nested instance by the names on the way joined by `.` (`Button.Label`: the layer Label of the nested instance
1472
+ * Button), or as `#<path>` (the stored key: the ids from the component down to the layer, joined by `;`). A key matches
1473
+ * the joined names exactly, so a name that holds a dot needs nothing escaped; a key that names two layers is refused
1474
+ * listing their `#<path>` forms. Throws a ComponentCallError that shows the right form.
1475
+ */
1476
+ export function overridesFromSyntax(document, component, value, names, slots) {
1477
+ const head = names.callNameOf(component) ?? component.name;
1478
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
1479
+ throw new ComponentCallError(`over takes the layers of ${head} by name, each with its changes: over:{Label:{color:#ffffff}}.`);
1480
+ }
1481
+ const layers = componentLayers(document, component);
1482
+ const paths = overridePaths(document, component);
1483
+ const shownLayers = () => listed(paths.map((path) => `${shownKey(path.name)}${path.key === component.rootId ? " (its root)" : ""}`));
1484
+ const overrides = {};
1485
+ const namedPaths = new Set();
1486
+ for (const [key, fields] of Object.entries(value)) {
1487
+ let path;
1488
+ if (key.startsWith("#")) {
1489
+ path = key.slice(1);
1490
+ const [first, ...rest] = path.split(";");
1491
+ const layer = layers.find((candidate) => candidate.id === first);
1492
+ if (layer === undefined)
1493
+ throw new ComponentCallError(`${key} is not a layer of ${head}; its layers are ${shownLayers()}.`);
1494
+ if (rest.length > 0 && layer.type !== "instance") {
1495
+ throw new ComponentCallError(`${key} goes on past #${first}, which is not an instance, so it names no layer; write over:{'#${first}':{...}}.`);
1496
+ }
1497
+ }
1498
+ else {
1499
+ const found = paths.filter((candidate) => candidate.name === key);
1500
+ if (found.length === 0) {
1501
+ // A layer of a nested instance written without the names on the way: say what to write.
1502
+ const inside = [...new Set(paths.filter((candidate) => candidate.name.endsWith(`.${key}`)).map((candidate) => shownKey(candidate.name)))];
1503
+ throw new ComponentCallError(inside.length > 0
1504
+ ? `${head} has no layer named ${shownKey(key)} of its own; inside its nested instances, write ${listed(inside)}, the names on the way joined by a dot: over:{${inside[0]}:{...}}.`
1505
+ : `${head} has no layer named ${shownKey(key)}; its layers are ${shownLayers()}.`);
1506
+ }
1507
+ if (found.length > 1) {
1508
+ throw new ComponentCallError(`${shownKey(key)} names ${found.length} layers of ${head}: ${listed(found.map((candidate) => `'#${candidate.key}'`))}; `
1509
+ + `write one of them as the key, as over:{'#${found[0].key}':{...}}.`);
1510
+ }
1511
+ path = found[0].key;
1512
+ }
1513
+ // A layer named twice (by its name and by its path, say) is refused even when one of them only fills its slots.
1514
+ if (namedPaths.has(path))
1515
+ throw new ComponentCallError(`over names the layer #${path} twice; write its changes once.`);
1516
+ namedPaths.add(path);
1517
+ let changes = fields;
1518
+ if (slots !== undefined && isRecordValue(fields) && slotContentOf(fields) === undefined && Object.hasOwn(fields, INSTANCE_SLOTS_ARGUMENT)) {
1519
+ // over:{Footer:{slots:{Actions:(...)}}} fills the slots of the nested instance Footer.
1520
+ const { [INSTANCE_SLOTS_ARGUMENT]: filled, ...rest } = fields;
1521
+ const nested = componentAtPath(document, component, path.split(";"));
1522
+ if (nested === undefined)
1523
+ throw new ComponentCallError(`${shownKey(key)} of ${head} is not an instance, so it has no slots to fill.`);
1524
+ const entries = slotEntriesFromSyntax(nested, filled, `${shownKey(key)} of ${head}`);
1525
+ if (Object.keys(entries).length > 0)
1526
+ Object.defineProperty(slots, path, { value: entries, enumerable: true, writable: true, configurable: true });
1527
+ if (Object.keys(rest).length === 0)
1528
+ continue;
1529
+ changes = rest;
1530
+ }
1531
+ Object.defineProperty(overrides, path, { value: layerOverrideFromSyntax(resolveLinearCalls(changes, document.nodes[path.split(";").at(-1)]), `${shownKey(key)} of ${head}`), enumerable: true, writable: true, configurable: true });
1532
+ }
1533
+ return overrides;
1534
+ }
1535
+ /** The slot properties of a component, in order. */
1536
+ export const slotPropertiesOf = (component) => (component.properties ?? []).filter((property) => property.kind === "slot");
1537
+ /**
1538
+ * The component of the nested instance that `path` (layer ids through nested instances, as an override key) names
1539
+ * inside `component`; undefined when a layer on the way is missing or the last is not an instance.
1540
+ */
1541
+ export function componentAtPath(document, component, path) {
1542
+ let current = component;
1543
+ for (const id of path) {
1544
+ const layer = current === undefined ? undefined : componentLayers(document, current).find((candidate) => candidate.id === id);
1545
+ if (layer?.type !== "instance")
1546
+ return undefined;
1547
+ current = entryOf(document.components ?? {}, layer.componentId);
1548
+ }
1549
+ return current;
1550
+ }
1551
+ /**
1552
+ * The slot entries `slots:{Name:( ... ), ...}` writes for a new instance of `component`, by slot property id: each slot
1553
+ * by its name, with its layers in `( ... )`, `()` for none, or `default` for the component's own layers (no entry).
1554
+ */
1555
+ function slotEntriesFromSyntax(component, value, shown) {
1556
+ const properties = slotPropertiesOf(component);
1557
+ const example = `slots:{${properties[0] === undefined ? "Content" : shownKey(properties[0].name)}:(text(text:'Hi'))}`;
1558
+ const form = `slots takes the slots of ${shown} by name, each with its layers in ( ... ), () for none, or default for the component's own: ${example}.`;
1559
+ if (!isRecordValue(value) || slotContentOf(value) !== undefined)
1560
+ throw new ComponentCallError(form);
1561
+ const entries = {};
1562
+ for (const [name, item] of Object.entries(value)) {
1563
+ const property = properties.find((candidate) => candidate.name === name);
1564
+ if (property === undefined) {
1565
+ throw new ComponentCallError(properties.length === 0 ? `${shown} has no slots, so slots:{...} has nothing to fill.`
1566
+ : `${shown} has no slot ${shownKey(name)}; its slots are ${listed(properties.map((candidate) => shownKey(candidate.name)))}.`);
1567
+ }
1568
+ // A new instance shows the component's own layers where it has no entry.
1569
+ if (item === "default")
1570
+ continue;
1571
+ if (slotContentOf(item) === undefined)
1572
+ throw new ComponentCallError(form);
1573
+ Object.defineProperty(entries, property.id, { value: item, enumerable: true, writable: true, configurable: true });
1574
+ }
1575
+ return entries;
1576
+ }
1577
+ /**
1578
+ * The `instance(componentId:..., ...)` call that a call of `component` stands for: its props by name (and in `props:{...}`)
1579
+ * as `propertyValues` by property id, `over:{...}` as `overrides` by layer path, and every other argument as written.
1580
+ * Throws a ComponentCallError, with the place of the argument, that shows the right form.
1581
+ */
1582
+ function instanceCallOf(call, component, document, names) {
1583
+ const head = names.callNameOf(component) ?? call.name;
1584
+ const arguments_ = instanceCallArguments();
1585
+ const properties = (component.properties ?? []).filter(isValuedComponentProperty);
1586
+ const takes = () => `${componentPropertyList(component, names)}; it also takes `
1587
+ + `${[...arguments_].filter((name) => name !== "componentId" && name !== "overrides" && name !== "propertyValues").join(", ")}`;
1588
+ if (call.children !== undefined) {
1589
+ throw new ComponentCallError(`${head} takes no layers in [...]: an instance shows the layers of its component. Change them in over:{...}.`, call);
1590
+ }
1591
+ const kept = [];
1592
+ const propertyValues = {};
1593
+ let overrides;
1594
+ let ownSlots;
1595
+ const slots = {};
1596
+ const writeProperty = (property, value, at) => {
1597
+ if (Object.hasOwn(propertyValues, property.id))
1598
+ throw new ComponentCallError(`${property.name} is given twice.`, at);
1599
+ try {
1600
+ propertyValues[property.id] = propertyValueFromSyntax(component, property, value, names);
1601
+ }
1602
+ catch (error) {
1603
+ if (error instanceof ComponentCallError)
1604
+ throw new ComponentCallError(error.message, at);
1605
+ throw error;
1606
+ }
1607
+ };
1608
+ for (const argument of call.arguments) {
1609
+ const name = argument.name;
1610
+ if (name === undefined) {
1611
+ kept.push(argument);
1612
+ continue;
1613
+ }
1614
+ const property = properties.find((candidate) => candidate.name === name);
1615
+ if (argument.remove === true) {
1616
+ if (property !== undefined || name === INSTANCE_OVER_ARGUMENT || name === INSTANCE_PROPS_ARGUMENT) {
1617
+ throw new ComponentCallError(`-${name}: a new instance has only the props and overrides you write, so there is nothing to leave out.`, argument);
1618
+ }
1619
+ kept.push(argument);
1620
+ continue;
1621
+ }
1622
+ if (name === "componentId" || name === "overrides" || name === "propertyValues") {
1623
+ throw new ComponentCallError(`${head}(...) names its component, so it takes no ${name}: write its props by name and its layers' changes in over:{...}, `
1624
+ + `or write instance(componentId:'${component.id}', ...) with the model fields.`, argument);
1625
+ }
1626
+ if (name === INSTANCE_OVER_ARGUMENT) {
1627
+ if (overrides !== undefined)
1628
+ throw new ComponentCallError("over is given twice.", argument);
1629
+ try {
1630
+ overrides = overridesFromSyntax(document, component, argument.value, names, slots);
1631
+ }
1632
+ catch (error) {
1633
+ if (error instanceof ComponentCallError)
1634
+ throw new ComponentCallError(error.message, argument);
1635
+ throw error;
1636
+ }
1637
+ continue;
1638
+ }
1639
+ if (name === INSTANCE_SLOTS_ARGUMENT) {
1640
+ if (ownSlots !== undefined)
1641
+ throw new ComponentCallError("slots is given twice.", argument);
1642
+ try {
1643
+ ownSlots = slotEntriesFromSyntax(component, argument.value, head);
1644
+ }
1645
+ catch (error) {
1646
+ if (error instanceof ComponentCallError)
1647
+ throw new ComponentCallError(error.message, argument);
1648
+ throw error;
1649
+ }
1650
+ continue;
1651
+ }
1652
+ if (name === INSTANCE_PROPS_ARGUMENT) {
1653
+ const value = argument.value;
1654
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
1655
+ throw new ComponentCallError(`props takes the props of ${head} by name, as props:{name:'Ada'}.`, argument);
1656
+ }
1657
+ for (const [key, item] of Object.entries(value)) {
1658
+ const named = properties.find((candidate) => candidate.name === key);
1659
+ if (named === undefined)
1660
+ throw new ComponentCallError(`${head} has no prop ${key}; ${componentPropertyList(component, names)}.`, argument);
1661
+ writeProperty(named, item, argument);
1662
+ }
1663
+ continue;
1664
+ }
1665
+ if (arguments_.has(name)) {
1666
+ kept.push(argument);
1667
+ continue;
1668
+ }
1669
+ if (property !== undefined) {
1670
+ writeProperty(property, argument.value, argument);
1671
+ continue;
1672
+ }
1673
+ const look = Object.hasOwn(shorthandsByName.get("frame").short, name);
1674
+ const root = entryOf(document.nodes, component.rootId);
1675
+ throw new ComponentCallError(look && root !== undefined
1676
+ ? `the ${name} of an instance is that of the root of its component, changed by an override: write over:{${shownKey(root.name)}:{${name === "stroke" ? "stroke" : "fill"}:...}}.`
1677
+ : `${head} has no argument or prop ${JSON.stringify(name)}; ${takes()}.`, argument);
1678
+ }
1679
+ const at = { line: call.line, column: call.column };
1680
+ const written = (name, value) => ({ name, value, text: JSON.stringify(value), ...at });
1681
+ // The model's form of slots: by nested instance path ("" for the instance's own), then by slot property id.
1682
+ if (ownSlots !== undefined && Object.keys(ownSlots).length > 0)
1683
+ Object.defineProperty(slots, "", { value: ownSlots, enumerable: true, writable: true, configurable: true });
1684
+ return {
1685
+ name: "instance", line: call.line, column: call.column, children: undefined,
1686
+ arguments: [
1687
+ written("componentId", component.id),
1688
+ ...kept,
1689
+ ...(Object.keys(propertyValues).length === 0 ? [] : [written("propertyValues", propertyValues)]),
1690
+ ...(overrides === undefined || Object.keys(overrides).length === 0 ? [] : [written("overrides", overrides)]),
1691
+ ...(Object.keys(slots).length === 0 ? [] : [written(INSTANCE_SLOTS_ARGUMENT, slots)]),
1692
+ ],
1693
+ };
1694
+ }
1695
+ /**
1696
+ * A call of the tool spelling in the terms of the shorthands (children as written): `std.x` and a call name in
1697
+ * another case as the shorthand's own name, and a component call as `instance(componentId:..., ...)` (see
1698
+ * `instanceCallOf`). A call that names nothing comes back as written, for `buildNodes` to refuse. Throws a
1699
+ * ComponentCallError for a call name that names several things, or for an argument of a component call it cannot write.
1700
+ */
1701
+ export function resolveLayerCall(document, call) {
1702
+ const resolved = componentNames(document).resolve(call.name);
1703
+ if (resolved === undefined)
1704
+ return call;
1705
+ if (resolved.kind === "shorthand")
1706
+ return resolved.shorthand.name === call.name ? call : { ...call, name: resolved.shorthand.name };
1707
+ return instanceCallOf(call, resolved.component, document, componentNames(document));
1708
+ }
1709
+ // ---------------------------------------------------------------------------
1710
+ // Building
1711
+ const has = (map, key) => Object.prototype.hasOwnProperty.call(map, key);
1712
+ /**
1713
+ * The first layer under `rootId` (its own layers, not the root) for which `matches` holds, in tree order, with its x and
1714
+ * y measured from the root: the x and y of the layers on the way added up.
1715
+ */
1716
+ function placeUnder(document, rootId, matches) {
1717
+ const visit = (id, x, y, depth) => {
1718
+ const node = entryOf(document.nodes, id);
1719
+ if (node === undefined || depth > 1000 || !isContainerNode(node))
1720
+ return undefined;
1721
+ for (const childId of node.children) {
1722
+ const child = entryOf(document.nodes, childId);
1723
+ if (child === undefined)
1724
+ continue;
1725
+ const box = "frame" in child ? child.frame : getNodeBounds(child);
1726
+ const at = { x: x + box.x, y: y + box.y };
1727
+ if (matches(child))
1728
+ return { node: child, ...at };
1729
+ const found = visit(childId, at.x, at.y, depth + 1);
1730
+ if (found !== undefined)
1731
+ return found;
1732
+ }
1733
+ return undefined;
1734
+ };
1735
+ return visit(rootId, 0, 0, 0);
1736
+ }
1737
+ /**
1738
+ * The frame bound to `propertyId` that the new instance `instance` shows, for its own slot (`path` empty) or that of the
1739
+ * nested instance `path` names, as the resolver picks it: the first frame bound to the slot in the layers the instance
1740
+ * shows after its props, conditions and overrides, with its x and y measured from the instance. Undefined when the
1741
+ * document does not hold the component's layers to resolve.
1742
+ */
1743
+ function shownSlotFramePlace(document, instance, path, propertyId) {
1744
+ let resolved;
1745
+ try {
1746
+ const nodes = sharedTableDraft(document.nodes);
1747
+ putEntry(nodes, instance.id, instance);
1748
+ // A stand-in document (a printer's or a planner's) may hold no pages.
1749
+ resolved = resolveInstance({ ...document, pages: document.pages ?? {}, nodes }, instance.id).root;
1750
+ }
1751
+ catch (error) {
1752
+ if (error instanceof ModelError)
1753
+ return undefined;
1754
+ throw error;
1755
+ }
1756
+ const matches = (layer) => layer.instance === undefined && layer.path.length === path.length + 1
1757
+ && path.every((id, index) => layer.path[index] === id) && layer.node.type === "frame"
1758
+ && entryOf(document.nodes, layer.sourceNodeId)?.type === "frame" && entryOf(document.nodes, layer.sourceNodeId).slot === propertyId;
1759
+ const visit = (layer, x, y, depth) => {
1760
+ if (depth > 1000)
1761
+ return undefined;
1762
+ for (const child of layer.children) {
1763
+ const box = "frame" in child.node ? child.node.frame : getNodeBounds(child.node);
1764
+ const at = { x: x + box.x, y: y + box.y };
1765
+ if (matches(child))
1766
+ return { frame: child.node, ...at };
1767
+ const found = visit(child, at.x, at.y, depth + 1);
1768
+ if (found !== undefined)
1769
+ return found;
1770
+ }
1771
+ return undefined;
1772
+ };
1773
+ return visit(resolved, 0, 0, 0);
1774
+ }
1775
+ /**
1776
+ * The frame bound to `propertyId` in the component `componentId`, or in the component of the nested instance `path`
1777
+ * names inside it, with its x and y measured from the outer component's root; undefined when the document does not hold it.
1778
+ */
1779
+ function slotFramePlace(document, componentId, path, propertyId) {
1780
+ let component = entryOf(document.components ?? {}, componentId);
1781
+ let x = 0, y = 0;
1782
+ for (const id of path) {
1783
+ if (component === undefined)
1784
+ return undefined;
1785
+ const nested = placeUnder(document, component.rootId, (node) => node.id === id);
1786
+ if (nested?.node.type !== "instance")
1787
+ return undefined;
1788
+ x += nested.x;
1789
+ y += nested.y;
1790
+ component = entryOf(document.components ?? {}, nested.node.componentId);
1791
+ }
1792
+ if (component === undefined)
1793
+ return undefined;
1794
+ const found = placeUnder(document, component.rootId, (node) => node.type === "frame" && node.slot === propertyId);
1795
+ return found === undefined ? undefined : { frame: found.node, x: x + found.x, y: y + found.y };
1796
+ }
1797
+ const AUTO_LAYOUT_SHORTHANDS = new Set(["hflex", "vflex"]);
1798
+ /** The parent `parentId` names in the document, for the top-level calls. */
1799
+ function documentParent(document, parentId) {
1800
+ const parent = parentId === undefined ? undefined : entryOf(document.nodes, parentId);
1801
+ if (parent === undefined)
1802
+ return { autoLayout: undefined, shown: "the parent" };
1803
+ const shown = `the layer ${JSON.stringify(parent.name)} (${parent.id})`;
1804
+ if (parent.type === "frame")
1805
+ return { autoLayout: parent.layout.kind !== "absolute", shown };
1806
+ return { autoLayout: parent.type === "group" ? false : undefined, shown };
1807
+ }
1808
+ /**
1809
+ * The sentence refusing a call with values written without a name. When the call reads in the old form
1810
+ * (the content as a string, then x, y, w, h in that order), it shows the same call with every name written.
1811
+ */
1812
+ function unnamedRefusal(shorthand, call, shortNames) {
1813
+ const order = oldPositionNamesOf(shorthand);
1814
+ const namedAlready = new Set(call.arguments.flatMap((argument) => argument.name === undefined ? [] : [argument.name]));
1815
+ let next = 0, rewritable = true;
1816
+ const written = call.arguments.map((argument) => {
1817
+ if (argument.name !== undefined)
1818
+ return `${argument.name}:${argument.text}`;
1819
+ if (next === 0 && shorthand.content !== undefined && typeof argument.value !== "string")
1820
+ next = 1;
1821
+ const name = order[next];
1822
+ next += 1;
1823
+ const isContent = name !== undefined && name === shorthand.content;
1824
+ if (name === undefined || namedAlready.has(name) || typeof argument.value !== (isContent ? "string" : "number"))
1825
+ rewritable = false;
1826
+ return `${name}:${argument.text}`;
1827
+ });
1828
+ const rule = "every argument needs a name, written name:value";
1829
+ return rewritable
1830
+ ? `${rule}. Write ${call.name}(${written.join(", ")})${call.children === undefined ? "" : "[...]"}.`
1831
+ : `${rule}. ${shorthand.name} takes ${shortNames.join(", ")}.`;
1832
+ }
1833
+ /** The longest name `textLayerName` gives a new text, in characters. */
1834
+ const TEXT_NAME_LIMIT = 30;
1835
+ /**
1836
+ * The characters of `text` as a person counts them: its graphemes (an emoji, even one joined from several, is one)
1837
+ * where `Intl.Segmenter` is there, else its code points; never half of a UTF-16 surrogate pair.
1838
+ */
1839
+ function charactersOf(text) {
1840
+ if (typeof Intl.Segmenter !== "function")
1841
+ return Array.from(text);
1842
+ return Array.from(new Intl.Segmenter(undefined, { granularity: "grapheme" }).segment(text), (part) => part.segment);
1843
+ }
1844
+ /**
1845
+ * The name of a new text: its first words, with runs of white space as one space, cut before the word that would make
1846
+ * it longer than 30 characters (a first word longer than that is cut at 30); undefined for a text with no words.
1847
+ * Characters are counted as `charactersOf` counts them.
1848
+ */
1849
+ function textLayerName(text) {
1850
+ if (typeof text !== "string")
1851
+ return undefined;
1852
+ const words = text.split(/\s+/).filter((word) => word !== "");
1853
+ if (words.length === 0)
1854
+ return undefined;
1855
+ const first = charactersOf(words[0]).slice(0, TEXT_NAME_LIMIT);
1856
+ let name = first.join(""), length = first.length;
1857
+ for (const word of words.slice(1)) {
1858
+ const wordLength = charactersOf(word).length;
1859
+ if (length + 1 + wordLength > TEXT_NAME_LIMIT)
1860
+ break;
1861
+ name += ` ${word}`;
1862
+ length += 1 + wordLength;
1863
+ }
1864
+ return name;
1865
+ }
1866
+ /**
1867
+ * The layers a source of shorthand calls describes, as subtrees ready for `node.insert`, one for each
1868
+ * top-level call, and each layer with the call that made it and its name. A layer named with `id:` keeps
1869
+ * that id; every other gets `options.newId`. A new text is named by its first words; other names count on from
1870
+ * the document's, as the panel's tools name layers.
1871
+ *
1872
+ * Throws `NodeBuildError` for a source it cannot read or a call it cannot make: a value without a name
1873
+ * (the message shows the call with names), `fill` or `hug` for a `w` or `h` that cannot take it, and
1874
+ * `x` or `y` on a layer its parent's auto layout places. It never judges a value: the nodes come back as
1875
+ * the arguments wrote them, for the document model to accept or refuse.
1876
+ */
1877
+ export function buildNodes(document, source, options = {}) {
1878
+ const calls = parse(source, options.maxCalls, options.syntax);
1879
+ const toolSpelling = options.syntax === "tool";
1880
+ refuseRepeatedIds(calls);
1881
+ const newId = options.newId ?? ((kind) => `${kind}-${globalThis.crypto.randomUUID()}`);
1882
+ const codeStyle = options.codeStyle ?? defaultCodeStyle(document);
1883
+ const allocators = new Map();
1884
+ const nextName = (shorthand) => {
1885
+ const { label, counts } = shorthand.naming;
1886
+ let allocate = allocators.get(label);
1887
+ if (allocate === undefined) {
1888
+ allocate = nodeSequenceAllocator(document, label, counts);
1889
+ allocators.set(label, allocate);
1890
+ }
1891
+ return `${label} ${allocate()}`;
1892
+ };
1893
+ const huggers = SHORTHANDS.filter((shorthand) => shorthand.sizes.hug).map((shorthand) => shorthand.name);
1894
+ const made = [];
1895
+ const createdSlots = [];
1896
+ /**
1897
+ * The slot property id `slot:Name` binds a frame of `component` to: the component's slot property named so (or with
1898
+ * that id), else a new one, made once for each name. Without a component the value is the model's to judge.
1899
+ */
1900
+ function slotPropertyIdOf(written, component) {
1901
+ if (component === undefined)
1902
+ return written;
1903
+ const known = [...slotPropertiesOf(component), ...createdSlots.filter((entry) => entry.componentId === component.id).map((entry) => entry.property)];
1904
+ const found = known.find((property) => property.name === written) ?? known.find((property) => property.id === written);
1905
+ if (found !== undefined)
1906
+ return found.id;
1907
+ const property = { id: newId("slot"), kind: "slot", name: written };
1908
+ createdSlots.push({ componentId: component.id, property });
1909
+ return property.id;
1910
+ }
1911
+ /**
1912
+ * The slot host for one filled slot of a new instance, with its content made from `calls` into `nodes`: the same
1913
+ * host and `slots` entry that `node.insert` with `slot` adds to an instance. Placed where the component's slot frame
1914
+ * is, with its size, rotation and layout; the cascade keeps it in step with the slot frame afterwards.
1915
+ */
1916
+ function fillSlot(instance, path, propertyId, hostId, calls, label, nodes, scope) {
1917
+ const place = shownSlotFramePlace(document, instance, path, propertyId)
1918
+ ?? slotFramePlace(document, instance.componentId ?? "", path, propertyId);
1919
+ const slotFrame = place?.frame;
1920
+ const hostPlace = { autoLayout: slotFrame === undefined ? undefined : slotFrame.layout.kind !== "absolute", shown: `the slot ${label}` };
1921
+ const children = calls.map((child, index) => make(child, `${label} > ${child.name} #${index + 1}`, hostPlace, nodes, scope));
1922
+ const id = (hostId ?? nodeId(newId("frame")));
1923
+ const host = {
1924
+ id, type: "frame", name: slotFrame?.name ?? "Slot", visible: true, locked: false, opacity: 1,
1925
+ frame: { x: place?.x ?? 0, y: place?.y ?? 0, width: slotFrame?.frame.width ?? 0, height: slotFrame?.frame.height ?? 0 },
1926
+ rotation: slotFrame?.rotation ?? 0, children, layout: slotFrame?.layout ?? { kind: "absolute" }, slotHost: true,
1927
+ };
1928
+ Object.defineProperty(nodes, id, { value: host, enumerable: true, writable: true, configurable: true });
1929
+ return id;
1930
+ }
1931
+ /** Makes the node of `call` and those of its children into `nodes`; answers its id. */
1932
+ function make(asWritten, label, parent, nodes, scope) {
1933
+ const refuse = (message, at, accepted) => new NodeBuildError("argument", `Line ${at.line}, column ${at.column}, in ${label}: ${message}`, at.line, at.column, label, accepted);
1934
+ // In the tool spelling a call may name a component, or a shorthand in its scope (std.text).
1935
+ let call = asWritten;
1936
+ if (toolSpelling) {
1937
+ try {
1938
+ call = resolveLayerCall(document, asWritten);
1939
+ }
1940
+ catch (error) {
1941
+ if (error instanceof ComponentCallError)
1942
+ throw refuse(error.message, error.at ?? asWritten);
1943
+ throw error;
1944
+ }
1945
+ }
1946
+ const shorthand = toolSpelling ? toolShorthand(call.name) : shorthandsByName.get(call.name);
1947
+ if (shorthand === undefined) {
1948
+ const names = [...SHORTHANDS, ...(toolSpelling ? TOOL_SHORTHANDS : [])].map((entry) => entry.name);
1949
+ const components = toolSpelling ? componentCallNames(document) : [];
1950
+ throw refuse(`there is no shorthand ${components.length === 0 ? "" : "or component "}${JSON.stringify(call.name)}; the shorthands are ${names.join(", ")}`
1951
+ + `${components.length === 0 ? "" : `, and the components ${listed([...components])}`}.`
1952
+ // component(name:'Card', props:{...}) is how some write an instance; here an instance is its component's call name.
1953
+ + (call.name === "component" && components.length > 0 ? ` An instance is written by its component's call name with its props, as ${components[0]}(...).` : ""), call, names);
1954
+ }
1955
+ const shortNames = shortNamesOf(shorthand);
1956
+ const modelFields = modelFieldsOf(shorthand);
1957
+ const accepted = [...shortNames, ...modelFields.filter((name) => !shortNames.includes(name))];
1958
+ const unnamed = call.arguments.find((argument) => argument.name === undefined);
1959
+ if (unnamed !== undefined)
1960
+ throw refuse(unnamedRefusal(shorthand, call, shortNames), unnamed, accepted);
1961
+ const given = new Map();
1962
+ const passed = [];
1963
+ const bound = new Map();
1964
+ const removed = [];
1965
+ const written = new Map();
1966
+ for (const argument of call.arguments) {
1967
+ const name = argument.name;
1968
+ if (written.has(name))
1969
+ throw refuse(`${name} is given twice.`, argument, accepted);
1970
+ written.set(name, argument);
1971
+ if (argument.remove === true) {
1972
+ // -fill leaves a new layer with no fills, as fill:() does: a new layer holds no binding for it to drop.
1973
+ if (name === "fill" && shortNames.includes(name)) {
1974
+ given.set(name, []);
1975
+ continue;
1976
+ }
1977
+ if (!modelFields.includes(name) || shortNames.includes(name)) {
1978
+ throw refuse(`-${name} leaves a model field out of the layer, and ${shorthand.name} has no model field ${JSON.stringify(name)} to leave out.`, argument, accepted);
1979
+ }
1980
+ removed.push(name);
1981
+ continue;
1982
+ }
1983
+ if (!shortNames.includes(name) && !modelFields.includes(name)) {
1984
+ throw refuse(`${shorthand.name} has no argument ${JSON.stringify(name)}. It accepts: ${accepted.join(", ")}.`, argument, accepted);
1985
+ }
1986
+ // var('name') writes the variable's value and binds the property it drives.
1987
+ let value = argument.value;
1988
+ try {
1989
+ value = readVariables(document.theme, name, value, shorthand.kind.type, bound);
1990
+ }
1991
+ catch (error) {
1992
+ if (error instanceof VariableReferenceError)
1993
+ throw refuse(error.message, argument, accepted);
1994
+ throw error;
1995
+ }
1996
+ if (shortNames.includes(name))
1997
+ given.set(name, value);
1998
+ else
1999
+ passed.push([name, value]);
2000
+ }
2001
+ if (call.children !== undefined && !shorthand.takesChildren) {
2002
+ throw refuse(`${shorthand.name} takes no children in [...].`, call);
2003
+ }
2004
+ // A polygon has no number of corners to assume: the Polygon tool's three would make a triangle the call never asked for.
2005
+ // -pointCount leaves the count out, so it does not give one.
2006
+ const pointCount = written.get("pointCount");
2007
+ if (shorthand.kind.type === "shape" && shorthand.kind.shape === "polygon" && (pointCount === undefined || pointCount.remove === true)) {
2008
+ throw refuse(`${shorthand.name} needs pointCount, the number of its corners: a diamond is pointCount:4, a triangle pointCount:3.`, call, accepted);
2009
+ }
2010
+ // The words fill and hug size the layer as Figma's resizing does; any other value is a fixed size, as written.
2011
+ const sizingOf = (axis) => {
2012
+ if (!given.has(axis))
2013
+ return undefined;
2014
+ const value = given.get(axis);
2015
+ return value === "fill" ? "fill" : value === "hug" ? "hug" : "fixed";
2016
+ };
2017
+ const sizing = { w: sizingOf("w"), h: sizingOf("h") };
2018
+ for (const axis of ["w", "h"]) {
2019
+ const size = sizing[axis];
2020
+ if (size === undefined || size === "fixed")
2021
+ continue;
2022
+ const at = written.get(axis);
2023
+ if (shorthand.sizes.points !== undefined)
2024
+ throw refuse(`${axis} of a ${shorthand.name} is a number, not ${size}: ${shorthand.sizes.points}.`, at, accepted);
2025
+ if (size === "hug" && !shorthand.sizes.hug) {
2026
+ throw refuse(`a ${shorthand.name} cannot hug its content, so ${axis} takes ${sizeWordsOf(shorthand)}. Only ${huggers.join(", ")} hug their content.`, at, accepted);
2027
+ }
2028
+ if (size === "fill" && parent.autoLayout === false) {
2029
+ throw refuse(`${axis}:fill makes a layer fill the space its auto layout parent gives it, and ${parent.shown} has no auto layout. `
2030
+ + `Give ${axis} a number, or put this layer in an hflex or vflex.`, at, accepted);
2031
+ }
2032
+ }
2033
+ const fitsContent = shorthand.kind.type === "text" || shorthand.kind.type === "code";
2034
+ const hugsWidth = sizing.w === "hug" || (sizing.w === undefined && shorthand.sizes.hugsByDefault === true);
2035
+ if (fitsContent && hugsWidth && (sizing.h === "fixed" || sizing.h === "fill")) {
2036
+ throw refuse(`a ${shorthand.name} that hugs its width also hugs its height, so h needs w as well: a number or fill.`, written.get("h"), accepted);
2037
+ }
2038
+ // A child of an auto layout frame is placed by the layout, unless it is taken out of the flow.
2039
+ const positioning = passed.find(([name]) => name === "layoutPositioning")?.[1];
2040
+ if (parent.autoLayout === true && positioning !== "absolute") {
2041
+ for (const axis of ["x", "y"]) {
2042
+ const at = written.get(axis);
2043
+ if (at === undefined)
2044
+ continue;
2045
+ throw refuse(`${parent.shown} places this layer with its auto layout, so it takes no ${axis}: leave out x and y. `
2046
+ + `To move it, change gap, pad, align or justify of ${parent.shown}; to place it yourself on top of the layout, add layoutPositioning:absolute.`, at, accepted);
2047
+ }
2048
+ }
2049
+ const layoutGiven = passed.find(([name]) => name === "layout")?.[1];
2050
+ const layoutKind = layoutGiven === undefined ? undefined : record(layoutGiven).kind;
2051
+ const childPlace = {
2052
+ autoLayout: layoutGiven === undefined ? AUTO_LAYOUT_SHORTHANDS.has(shorthand.name) : typeof layoutKind === "string" ? layoutKind !== "absolute" : undefined,
2053
+ shown: label,
2054
+ };
2055
+ // An instance of a component the document holds is named and sized from it; any other is the model's to refuse.
2056
+ const componentId = shorthand.kind.type === "instance" ? passed.find(([name]) => name === "componentId")?.[1] : undefined;
2057
+ const component = typeof componentId === "string" ? entryOf(document.components ?? {}, componentId) : undefined;
2058
+ const explicitId = given.get("id");
2059
+ // An id as written: the model judges it with the node.
2060
+ const id = (explicitId === undefined ? nodeId(newId(shorthand.kind.type === "shape" ? shorthand.kind.shape : shorthand.kind.type)) : explicitId);
2061
+ // An explicit name takes no generated one, so the next unnamed layer gets that number, and an image's alt is this name.
2062
+ const words = shorthand.kind.type === "text" ? textLayerName(given.get("text")) : undefined;
2063
+ const layerName = (given.has("name") ? given.get("name") : component !== undefined ? component.name : words ?? nextName(shorthand));
2064
+ made.push({ id, name: layerName, call: label, line: call.line, column: call.column });
2065
+ // A call whose id is a component's root makes that component's layers, for slot:Name on its frames.
2066
+ let rootOf = null;
2067
+ const childScope = () => {
2068
+ if (rootOf === null)
2069
+ rootOf = typeof explicitId === "string" ? findComponentByRoot(document, explicitId) : undefined;
2070
+ return rootOf ?? scope();
2071
+ };
2072
+ const children = (call.children ?? []).map((child, index) => make(child, `${label} > ${child.name} #${index + 1}`, childPlace, nodes, childScope));
2073
+ const number = (key, otherwise) => (given.has(key) ? given.get(key) : otherwise);
2074
+ const size = (axis, otherwise) => (sizing[axis] === "fixed" ? given.get(axis) : otherwise);
2075
+ const box = { x: number("x", 0), y: number("y", 0),
2076
+ width: size("w", shorthand.defaultSize.width), height: size("h", shorthand.defaultSize.height) };
2077
+ const groupBox = shorthand.kind.type === "group" ? boxAround(children.map((child) => nodes[child])) : undefined;
2078
+ let base;
2079
+ try {
2080
+ base = shorthand.make({ document, id, name: layerName, codeStyle, given, sizing, fields: new Map(passed),
2081
+ box: groupBox === undefined ? box : { x: box.x + groupBox.x, y: box.y + groupBox.y, width: groupBox.width, height: groupBox.height } });
2082
+ }
2083
+ catch (error) {
2084
+ if (error instanceof InstanceBuildError)
2085
+ throw refuse(`${error.message}`, call, accepted);
2086
+ if (error instanceof ShortArgumentError)
2087
+ throw refuse(error.message, written.get(error.argument ?? "") ?? call, accepted);
2088
+ throw error;
2089
+ }
2090
+ const node = { ...base };
2091
+ if (groupBox !== undefined) {
2092
+ // As the Group command does: the layers inside keep their place on the page, measured from the group's corner.
2093
+ for (const child of children) {
2094
+ const inside = nodes[child];
2095
+ const frame = record(inside.frame);
2096
+ if (typeof frame.x === "number" && typeof frame.y === "number") {
2097
+ nodes[child] = { ...inside, frame: { ...frame, x: frame.x - groupBox.x, y: frame.y - groupBox.y } };
2098
+ }
2099
+ }
2100
+ }
2101
+ for (const [name, value] of passed)
2102
+ node[name] = value;
2103
+ if (node.style && passed.some(([name]) => name === "style")) {
2104
+ node.style = resolveLinearCalls(node.style, node);
2105
+ }
2106
+ if (base.type === "instance") {
2107
+ // After the call's overrides, which replace the base's: a number for w or h is the Fixed override of a hugging component root's sizing.
2108
+ if (sizing.w === "fixed")
2109
+ Object.assign(node, withAxisSizing(document, node, "width", "fixed"));
2110
+ if (sizing.h === "fixed")
2111
+ Object.assign(node, withAxisSizing(document, node, "height", "fixed"));
2112
+ }
2113
+ for (const [name, value] of given) {
2114
+ if (name === "name" || name === "opacity")
2115
+ node[name] = value;
2116
+ else if (has(shorthand.short, name)) {
2117
+ try {
2118
+ shorthand.short[name](node, value);
2119
+ }
2120
+ catch (error) {
2121
+ if (error instanceof ShortArgumentError)
2122
+ throw refuse(error.message, written.get(name), accepted);
2123
+ throw error;
2124
+ }
2125
+ }
2126
+ }
2127
+ if (sizing.w === "fill")
2128
+ setIn(node, ["resizing", "width"], "fill");
2129
+ if (sizing.h === "fill")
2130
+ setIn(node, ["resizing", "height"], "fill");
2131
+ for (const name of removed)
2132
+ delete node[name];
2133
+ if (base.type === "frame" && typeof node.slot === "string")
2134
+ node.slot = slotPropertyIdOf(node.slot, childScope());
2135
+ if (base.type === "instance" && isRecordValue(node.slots)) {
2136
+ const filled = {};
2137
+ for (const [pathKey, byProperty] of Object.entries(node.slots)) {
2138
+ if (!isRecordValue(byProperty)) {
2139
+ Object.defineProperty(filled, pathKey, { value: byProperty, enumerable: true, writable: true, configurable: true });
2140
+ continue;
2141
+ }
2142
+ const entries = {};
2143
+ for (const [propertyId, item] of Object.entries(byProperty)) {
2144
+ const content = slotContentOf(item);
2145
+ let entry = item;
2146
+ if (content?.summary !== undefined) {
2147
+ if (options.keepSlotSummaries !== true) {
2148
+ throw refuse(slotSummaryRefusal(content.summary, content.hostId), content, accepted);
2149
+ }
2150
+ entry = content.hostId;
2151
+ }
2152
+ else if (content !== undefined) {
2153
+ const { slots: _slots, ...shown } = node;
2154
+ entry = fillSlot(shown, pathKey === "" ? [] : pathKey.split(";"), propertyId, content.hostId, content.calls, `${label} slot ${propertyId}`, nodes, scope);
2155
+ }
2156
+ Object.defineProperty(entries, propertyId, { value: entry, enumerable: true, writable: true, configurable: true });
2157
+ }
2158
+ Object.defineProperty(filled, pathKey, { value: entries, enumerable: true, writable: true, configurable: true });
2159
+ }
2160
+ node.slots = filled;
2161
+ }
2162
+ if (shorthand.takesChildren)
2163
+ node.children = children;
2164
+ if (bound.size !== 0) {
2165
+ try {
2166
+ Object.assign(node, withBoundVariables(document.theme, node, bound));
2167
+ }
2168
+ catch (error) {
2169
+ if (error instanceof VariableReferenceError)
2170
+ throw refuse(error.message, call, accepted);
2171
+ throw error;
2172
+ }
2173
+ }
2174
+ Object.defineProperty(nodes, String(node.id), { value: node, enumerable: true, writable: true, configurable: true });
2175
+ return node.id;
2176
+ }
2177
+ const topParent = documentParent(document, options.parentId);
2178
+ // The component the top-level layers go into, found only when a frame names a slot.
2179
+ let topScope = null;
2180
+ const scope = () => {
2181
+ if (topScope === null) {
2182
+ topScope = options.component !== undefined ? entryOf(document.components ?? {}, options.component)
2183
+ : options.parentId !== undefined ? componentOwningNode(document, options.parentId) : undefined;
2184
+ }
2185
+ return topScope;
2186
+ };
2187
+ const subtrees = calls.map((call, index) => {
2188
+ const nodes = {};
2189
+ const rootId = make(call, `${call.name} #${index + 1}`, topParent, nodes, scope);
2190
+ return { rootId, nodes };
2191
+ });
2192
+ return { subtrees, calls: made, ...(createdSlots.length === 0 ? {} : { slotProperties: createdSlots }) };
2193
+ }
2194
+ /**
2195
+ * The value of the argument `name` of a layer of `kind` with each `var('…')` read (variable-references.ts): an argument
2196
+ * written as one takes the variable's value in its active mode, and the properties it binds go into `bound`; in
2197
+ * `variableBindings` each key written as one is bound to the variable and stays as its id. A `var('…')` anywhere else
2198
+ * is refused.
2199
+ */
2200
+ export function readVariables(theme, name, value, kind, bound) {
2201
+ if (isVariableReference(value)) {
2202
+ const read = readVariableArgument(theme, kind, name, value.var);
2203
+ for (const property of read.properties)
2204
+ bound.set(property, read);
2205
+ return read.value;
2206
+ }
2207
+ if (name === "variableBindings" && typeof value === "object" && value !== null && !Array.isArray(value)) {
2208
+ const ids = {};
2209
+ for (const [key, item] of Object.entries(value)) {
2210
+ let written = item;
2211
+ if (isVariableReference(item)) {
2212
+ if (!isVariableProperty(key)) {
2213
+ throw new VariableReferenceError(`variableBindings has no property ${JSON.stringify(key)}; the properties are ${Object.keys(VARIABLE_PROPERTY_TYPES).join(", ")}.`);
2214
+ }
2215
+ const read = readVariableArgument(theme, kind, key, item.var, [key]);
2216
+ bound.set(key, read);
2217
+ written = read.variableId;
2218
+ }
2219
+ else if (holdsVariableReference(item)) {
2220
+ throw new VariableReferenceError(`a variable binding is written variableBindings:{${key}:var('<name>')}.`);
2221
+ }
2222
+ Object.defineProperty(ids, key, { value: written, enumerable: true, writable: true, configurable: true });
2223
+ }
2224
+ return ids;
2225
+ }
2226
+ if (holdsVariableReference(value)) {
2227
+ throw new VariableReferenceError(`var('<name>') is a whole value: write ${name}:var('<name>') where ${name} takes a variable, `
2228
+ + "or bind a property in variableBindings:{<property>:var('<name>')}.");
2229
+ }
2230
+ return value;
2231
+ }
2232
+ /**
2233
+ * Refuses a source in which two calls give the same id, naming the later call and the earlier one. A
2234
+ * subtree holds its layers by id, so two calls with one id cannot both become layers: this is the shape
2235
+ * of the source, not a rule about a value. An id already in the document is the model's to judge.
2236
+ */
2237
+ function refuseRepeatedIds(calls) {
2238
+ const earlier = new Map();
2239
+ const visit = (call, label) => {
2240
+ // The id a slot list ends with is the slot host's, one more layer of the subtree.
2241
+ for (const argument of call.arguments) {
2242
+ mapSlotContents(argument.value, (content) => {
2243
+ if (content.hostId === undefined)
2244
+ return content;
2245
+ const first = earlier.get(content.hostId);
2246
+ if (first !== undefined) {
2247
+ throw new NodeBuildError("argument", `Line ${content.line}, column ${content.column}, in ${label}: the slot host id ${JSON.stringify(content.hostId)} `
2248
+ + `is also given by ${first.label} at line ${first.line}, column ${first.column}; give each layer and each slot host its own id.`, content.line, content.column, label);
2249
+ }
2250
+ earlier.set(content.hostId, { label: `the slot host of ${label}`, line: content.line, column: content.column });
2251
+ return content;
2252
+ });
2253
+ }
2254
+ const given = call.arguments.find((argument) => argument.name === "id");
2255
+ if (given !== undefined) {
2256
+ // The key a subtree's nodes would hold: a non-string id (the model refuses it) by its JSON.
2257
+ const key = typeof given.value === "string" ? given.value : JSON.stringify(given.value);
2258
+ const first = earlier.get(key);
2259
+ if (first !== undefined) {
2260
+ throw new NodeBuildError("argument", `Line ${call.line}, column ${call.column}, in ${label}: the id ${JSON.stringify(given.value)} `
2261
+ + `is also given by ${first.label} at line ${first.line}, column ${first.column}; give each call its own id.`, call.line, call.column, label);
2262
+ }
2263
+ earlier.set(key, { label, line: call.line, column: call.column });
2264
+ }
2265
+ [...call.children ?? [], ...slotContentCalls(call)].forEach((child, index) => visit(child, `${label} > ${child.name} #${index + 1}`));
2266
+ };
2267
+ calls.forEach((call, index) => visit(call, `${call.name} #${index + 1}`));
2268
+ }
2269
+ /**
2270
+ * The box around nodes with a box, in their parent's coordinates, as the Group command measures it: each
2271
+ * node's turned box from `getNodeBounds`. A zero box at (0, 0) when none has one. A rotation that is not a
2272
+ * number counts as none, so the model, not this box, refuses it.
2273
+ */
2274
+ function boxAround(nodes) {
2275
+ const boxes = nodes.flatMap((node) => {
2276
+ const fields = node;
2277
+ const frame = record(fields.frame);
2278
+ return [frame.x, frame.y, frame.width, frame.height].every((value) => typeof value === "number")
2279
+ ? [getNodeBounds({ ...fields, rotation: typeof fields.rotation === "number" ? fields.rotation : 0 })] : [];
2280
+ });
2281
+ if (boxes.length === 0)
2282
+ return { x: 0, y: 0, width: 0, height: 0 };
2283
+ const left = Math.min(...boxes.map((box) => box.x));
2284
+ const top = Math.min(...boxes.map((box) => box.y));
2285
+ const right = Math.max(...boxes.map((box) => box.x + box.width));
2286
+ const bottom = Math.max(...boxes.map((box) => box.y + box.height));
2287
+ return { x: left, y: top, width: right - left, height: bottom - top };
2288
+ }
2289
+ /** The document's default code style, as a new code block would name it. */
2290
+ function defaultCodeStyle(document) {
2291
+ const id = document.theme.defaultCodeStyleId;
2292
+ const style = entryOf(document.theme.codeStyles, id);
2293
+ return { codeStyleId: codeStyleId(id), fontFamily: style?.fontFamily ?? "", fontSize: style?.fontSize ?? 0 };
2294
+ }