swf2js 0.1.2 → 0.4.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 (416) hide show
  1. package/README.md +81 -14
  2. package/package.json +11 -7
  3. package/studio/actionscript-roundtrip.test.js +54 -0
  4. package/studio/actionscript-scripts.test.js +169 -0
  5. package/studio/animated-image.test.js +137 -0
  6. package/studio/arithmetic.test.js +16 -0
  7. package/studio/as3-import.test.js +110 -0
  8. package/studio/audio-info.test.js +44 -0
  9. package/studio/components.test.js +152 -0
  10. package/studio/document-editing.test.js +92 -0
  11. package/studio/examples/01-space-mission.json +1628 -0
  12. package/studio/examples/02-clockwork-vault.json +1079 -0
  13. package/studio/examples/03-neon-synth.json +1364 -0
  14. package/studio/examples/04-kinetic-poster.json +923 -0
  15. package/studio/examples/05-signal-relay.json +1131 -0
  16. package/studio/examples/06-calculator.json +564 -0
  17. package/studio/frame-editing.test.js +129 -0
  18. package/studio/frame-events.test.js +117 -0
  19. package/studio/groups.test.js +88 -0
  20. package/studio/index.html +962 -0
  21. package/studio/interaction-triggers.test.js +37 -0
  22. package/studio/linked-actions.test.js +48 -0
  23. package/studio/lottie.test.js +208 -0
  24. package/studio/masks.test.js +43 -0
  25. package/studio/media-assets.test.js +62 -0
  26. package/studio/paint-tools.test.js +60 -0
  27. package/studio/playback.test.js +17 -0
  28. package/studio/project-io.test.js +405 -0
  29. package/studio/project-preview.test.js +475 -0
  30. package/studio/scene-transition.test.js +32 -0
  31. package/studio/server/archive-companions.js +27 -0
  32. package/studio/server/as3-library.js +91 -0
  33. package/studio/server/assets.js +162 -0
  34. package/studio/server/audio-info.js +82 -0
  35. package/studio/server/font-files.js +332 -0
  36. package/studio/server/http.js +135 -0
  37. package/studio/server/linked-actions.js +93 -0
  38. package/studio/server/png-decode.js +1 -0
  39. package/studio/server/project-movie.js +1164 -0
  40. package/studio/server/project-preview.js +152 -0
  41. package/studio/server/projects.js +370 -0
  42. package/studio/server/report.js +29 -0
  43. package/studio/server/routes.js +93 -0
  44. package/studio/server/swf-authoring.js +90 -0
  45. package/studio/server/swf-control-runtime.as +513 -0
  46. package/studio/server/swf-controls.js +119 -0
  47. package/studio/server/swf-export.js +293 -0
  48. package/studio/server/swf-import.js +1675 -0
  49. package/studio/server/swf-morphs.js +64 -0
  50. package/studio/server/swf-routes.js +42 -0
  51. package/studio/server/swf-streams.js +80 -0
  52. package/studio/server/swf-transition-runtime.as +52 -0
  53. package/studio/server/tween-recovery.js +106 -0
  54. package/studio/server-api.test.js +283 -0
  55. package/studio/server.js +320 -0
  56. package/studio/src/animated-image.js +423 -0
  57. package/studio/src/appearance-inspector.js +63 -0
  58. package/studio/src/arithmetic.js +50 -0
  59. package/studio/src/authored-controls.js +42 -0
  60. package/studio/src/busy.js +41 -0
  61. package/studio/src/canvas.js +430 -0
  62. package/studio/src/clipper-browser.js +2 -0
  63. package/studio/src/color-transform.js +38 -0
  64. package/studio/src/component-inspector.js +126 -0
  65. package/studio/src/components.js +268 -0
  66. package/studio/src/display-frame.js +262 -0
  67. package/studio/src/document-editing.js +69 -0
  68. package/studio/src/event-editor.js +150 -0
  69. package/studio/src/frame-editing.js +150 -0
  70. package/studio/src/frame-events.js +128 -0
  71. package/studio/src/frame-image.js +28 -0
  72. package/studio/src/groups.js +125 -0
  73. package/studio/src/handler-editor.js +122 -0
  74. package/studio/src/history.js +83 -0
  75. package/studio/src/imported-paths.js +99 -0
  76. package/studio/src/index.js +3582 -0
  77. package/studio/src/interaction-triggers.js +42 -0
  78. package/studio/src/json-patch.js +77 -0
  79. package/studio/src/layer-icons.js +25 -0
  80. package/studio/src/lottie-export.js +948 -0
  81. package/studio/src/lottie-import.js +1138 -0
  82. package/studio/src/masks.js +69 -0
  83. package/studio/src/media-assets.js +188 -0
  84. package/studio/src/media-library.js +193 -0
  85. package/studio/src/model.js +431 -0
  86. package/studio/src/numeric-fields.js +46 -0
  87. package/studio/src/object-list.js +57 -0
  88. package/studio/src/paint-tools.js +76 -0
  89. package/studio/src/placement-effects.js +74 -0
  90. package/studio/src/playback.js +10 -0
  91. package/studio/src/preview-audio.js +64 -0
  92. package/studio/src/preview-interactions.js +106 -0
  93. package/studio/src/preview-recorder.js +335 -0
  94. package/studio/src/preview-surface.js +338 -0
  95. package/studio/src/project-io.js +905 -0
  96. package/studio/src/project-session.js +375 -0
  97. package/studio/src/projects-dialog.js +319 -0
  98. package/studio/src/scene-transition.js +129 -0
  99. package/studio/src/script-editor.js +175 -0
  100. package/studio/src/script-references.js +74 -0
  101. package/studio/src/scripted-controls.js +146 -0
  102. package/studio/src/scripts.js +185 -0
  103. package/studio/src/stage-guides.js +101 -0
  104. package/studio/src/svg-animation.js +416 -0
  105. package/studio/src/svg-context.js +522 -0
  106. package/studio/src/svg-frame.js +413 -0
  107. package/studio/src/svg-import.js +1208 -0
  108. package/studio/src/swf-recording.js +104 -0
  109. package/studio/src/symbol-library.js +39 -0
  110. package/studio/src/symbols.js +62 -0
  111. package/studio/src/text-fields.js +58 -0
  112. package/studio/src/theme.js +43 -0
  113. package/studio/src/timeline.js +321 -0
  114. package/studio/src/vector-cut.js +103 -0
  115. package/studio/src/vector-geometry.js +254 -0
  116. package/studio/src/vector-style.js +146 -0
  117. package/studio/src/video-encode.js +84 -0
  118. package/studio/src/video-export.js +331 -0
  119. package/studio/src/video-mux.js +339 -0
  120. package/studio/src/video-playback.js +281 -0
  121. package/studio/src/workspace.js +344 -0
  122. package/studio/stroke-style.test.js +119 -0
  123. package/studio/styles.css +1547 -0
  124. package/studio/svg-export.test.js +162 -0
  125. package/studio/svg-import.test.js +318 -0
  126. package/studio/swf-authoring.test.js +140 -0
  127. package/studio/swf-export.test.js +324 -0
  128. package/studio/swf-import.test.js +489 -0
  129. package/studio/symbols.test.js +68 -0
  130. package/studio/tests/accessibility-interactions.mjs +138 -0
  131. package/studio/tests/appearance-interactions.mjs +103 -0
  132. package/studio/tests/control-interactions.mjs +60 -0
  133. package/studio/tests/event-interactions.mjs +117 -0
  134. package/studio/tests/external-resources.mjs +174 -0
  135. package/studio/tests/frame-image.mjs +71 -0
  136. package/studio/tests/html-export.mjs +68 -0
  137. package/studio/tests/import-files.mjs +131 -0
  138. package/studio/tests/lottie.mjs +125 -0
  139. package/studio/tests/mask-interactions.mjs +148 -0
  140. package/studio/tests/media-interactions.mjs +109 -0
  141. package/studio/tests/paint-interactions.mjs +64 -0
  142. package/studio/tests/project-interactions.mjs +244 -0
  143. package/studio/tests/script-interactions.mjs +178 -0
  144. package/studio/tests/scripted-control-interactions.mjs +107 -0
  145. package/studio/tests/svg-export.mjs +149 -0
  146. package/studio/tests/text-field-interactions.mjs +64 -0
  147. package/studio/tests/theme-interactions.mjs +53 -0
  148. package/studio/tests/timeline-browser.mjs +507 -0
  149. package/studio/tests/transition-interactions.mjs +94 -0
  150. package/studio/tests/trigger-interactions.mjs +93 -0
  151. package/studio/tests/video-export.mjs +243 -0
  152. package/studio/tests/workspace-interactions.mjs +226 -0
  153. package/studio/tween-recovery.test.js +31 -0
  154. package/studio/vector-style.test.js +56 -0
  155. package/studio/video-export.test.js +326 -0
  156. package/studiospec/actionscript.md +88 -0
  157. package/studiospec/architecture.md +378 -0
  158. package/studiospec/controls.md +100 -0
  159. package/studiospec/file-support.md +268 -0
  160. package/studiospec/lottie.md +69 -0
  161. package/studiospec/requirements.md +135 -0
  162. package/studiospec/stroke-style.md +95 -0
  163. package/studiospec/svg-export.md +83 -0
  164. package/studiospec/svg-import.md +139 -0
  165. package/studiospec/swooflib-integration.md +115 -0
  166. package/studiospec/tasks.md +573 -0
  167. package/studiospec/video-export.md +127 -0
  168. package/swf2js/__tests__/actionscript.test.js +1609 -0
  169. package/swf2js/__tests__/adpcm-audio.test.js +43 -0
  170. package/swf2js/__tests__/as2-compiler.test.js +153 -0
  171. package/swf2js/__tests__/as3-mixed-depth.test.js +498 -0
  172. package/swf2js/__tests__/authored-sprite-hit.test.js +118 -0
  173. package/swf2js/__tests__/authored-sprite-sizing.test.js +164 -0
  174. package/swf2js/__tests__/avm1-action-prefix.test.js +134 -0
  175. package/swf2js/__tests__/avm1-attach-movie.test.js +1151 -0
  176. package/swf2js/__tests__/avm1-boxhead-budget.test.js +73 -0
  177. package/swf2js/__tests__/avm1-cfg-bubble-tanks.test.js +101 -0
  178. package/swf2js/__tests__/avm1-cfg-mario-kart.test.js +184 -0
  179. package/swf2js/__tests__/avm1-cfg-mario.test.js +31 -0
  180. package/swf2js/__tests__/avm1-cfg-pacman.test.js +49 -0
  181. package/swf2js/__tests__/avm1-checkers-gameplay.test.js +122 -0
  182. package/swf2js/__tests__/avm1-clip-actions.test.js +2002 -0
  183. package/swf2js/__tests__/avm1-clone-drag.test.js +626 -0
  184. package/swf2js/__tests__/avm1-decompiler.test.js +102 -0
  185. package/swf2js/__tests__/avm1-dynamic-locals.test.js +159 -0
  186. package/swf2js/__tests__/avm1-formal-parameters.test.js +71 -0
  187. package/swf2js/__tests__/avm1-key-events.test.js +52 -0
  188. package/swf2js/__tests__/avm1-load-bitmap.test.js +75 -0
  189. package/swf2js/__tests__/avm1-loading-host-actions.test.js +764 -0
  190. package/swf2js/__tests__/avm1-multibyte-strings.test.js +63 -0
  191. package/swf2js/__tests__/avm1-pacman-gameplay.test.js +115 -0
  192. package/swf2js/__tests__/avm1-shape-hittest.test.js +311 -0
  193. package/swf2js/__tests__/avm1-shared-bodies.test.js +57 -0
  194. package/swf2js/__tests__/avm1-shared-runtime.test.js +1364 -0
  195. package/swf2js/__tests__/avm1-snake-gameplay.test.js +139 -0
  196. package/swf2js/__tests__/avm1-super.test.js +70 -0
  197. package/swf2js/__tests__/avm1-target-path.test.js +325 -0
  198. package/swf2js/__tests__/avm1-try.test.js +229 -0
  199. package/swf2js/__tests__/avm2-activation-closures.test.js +65 -0
  200. package/swf2js/__tests__/avm2-applytype.test.js +180 -0
  201. package/swf2js/__tests__/avm2-call-ops.test.js +232 -0
  202. package/swf2js/__tests__/avm2-callsuperid.test.js +231 -0
  203. package/swf2js/__tests__/avm2-class-initializer.test.js +219 -0
  204. package/swf2js/__tests__/avm2-custom-namespace.test.js +139 -0
  205. package/swf2js/__tests__/avm2-describe-type.test.js +96 -0
  206. package/swf2js/__tests__/avm2-dictionary.test.js +96 -0
  207. package/swf2js/__tests__/avm2-domain-memory.test.js +332 -0
  208. package/swf2js/__tests__/avm2-e4x.test.js +326 -0
  209. package/swf2js/__tests__/avm2-exceptions.test.js +81 -0
  210. package/swf2js/__tests__/avm2-findprop.test.js +110 -0
  211. package/swf2js/__tests__/avm2-getlex.test.js +166 -0
  212. package/swf2js/__tests__/avm2-global-slot.test.js +106 -0
  213. package/swf2js/__tests__/avm2-interface.test.js +95 -0
  214. package/swf2js/__tests__/avm2-multiname-precedence.test.js +148 -0
  215. package/swf2js/__tests__/avm2-named-namespace-types.test.js +106 -0
  216. package/swf2js/__tests__/avm2-optional-args.test.js +100 -0
  217. package/swf2js/__tests__/avm2-outer-scopes.test.js +101 -0
  218. package/swf2js/__tests__/avm2-package-internal-class.test.js +106 -0
  219. package/swf2js/__tests__/avm2-protected-namespace.test.js +105 -0
  220. package/swf2js/__tests__/avm2-protected.test.js +214 -0
  221. package/swf2js/__tests__/avm2-qwop-gameplay.test.js +116 -0
  222. package/swf2js/__tests__/avm2-runtime-namespaces.test.js +159 -0
  223. package/swf2js/__tests__/avm2-script-traits.test.js +89 -0
  224. package/swf2js/__tests__/avm2-shared-runtime.test.js +52 -0
  225. package/swf2js/__tests__/avm2-slot-ops.test.js +117 -0
  226. package/swf2js/__tests__/avm2-type-ops.test.js +224 -0
  227. package/swf2js/__tests__/bevel-filter.test.js +116 -0
  228. package/swf2js/__tests__/bitmap-button-mask.test.js +106 -0
  229. package/swf2js/__tests__/bitmap-data-draw.test.js +388 -0
  230. package/swf2js/__tests__/bitmap-decoder.test.js +108 -0
  231. package/swf2js/__tests__/bitmapdata-color-bounds.test.js +70 -0
  232. package/swf2js/__tests__/bitmapdata-copy-channel.test.js +91 -0
  233. package/swf2js/__tests__/bitmapdata-copy-pixels.test.js +136 -0
  234. package/swf2js/__tests__/bitmapdata-fill-compare.test.js +241 -0
  235. package/swf2js/__tests__/bitmapdata-filter.test.js +232 -0
  236. package/swf2js/__tests__/bitmapdata-hit-test.test.js +71 -0
  237. package/swf2js/__tests__/bitmapdata-merge.test.js +84 -0
  238. package/swf2js/__tests__/bitmapdata-palette-map.test.js +92 -0
  239. package/swf2js/__tests__/bitmapdata-pixels-io.test.js +198 -0
  240. package/swf2js/__tests__/bitmapdata-threshold.test.js +97 -0
  241. package/swf2js/__tests__/bitmapdata-vector.test.js +82 -0
  242. package/swf2js/__tests__/blur-filter.test.js +48 -0
  243. package/swf2js/__tests__/bundle-emitter.test.js +394 -0
  244. package/swf2js/__tests__/button-actions.test.js +370 -0
  245. package/swf2js/__tests__/button-color-transform.test.js +48 -0
  246. package/swf2js/__tests__/button-decoder.test.js +106 -0
  247. package/swf2js/__tests__/button-hit-test.test.js +825 -0
  248. package/swf2js/__tests__/button-scaling-grid.test.js +124 -0
  249. package/swf2js/__tests__/button-sound.test.js +105 -0
  250. package/swf2js/__tests__/bytearray-coercion.test.js +23 -0
  251. package/swf2js/__tests__/bytearray-object-serialization.test.js +380 -0
  252. package/swf2js/__tests__/cfg-switch-loop.test.js +103 -0
  253. package/swf2js/__tests__/clip-depth-mask.test.js +119 -0
  254. package/swf2js/__tests__/clipped-bitmap-fill.test.js +118 -0
  255. package/swf2js/__tests__/companion-swf.test.js +638 -0
  256. package/swf2js/__tests__/context-menu.test.js +149 -0
  257. package/swf2js/__tests__/convolution-filter.test.js +74 -0
  258. package/swf2js/__tests__/definefont4.test.js +280 -0
  259. package/swf2js/__tests__/display-displacement.test.js +161 -0
  260. package/swf2js/__tests__/display-list.test.js +80 -0
  261. package/swf2js/__tests__/display-mask-render.test.js +656 -0
  262. package/swf2js/__tests__/displayobject-stage.test.js +320 -0
  263. package/swf2js/__tests__/embedded-script-audio.test.js +131 -0
  264. package/swf2js/__tests__/embedded-swf.test.js +202 -0
  265. package/swf2js/__tests__/embedded-textfield.test.js +107 -0
  266. package/swf2js/__tests__/embedded-timeline-audio.test.js +182 -0
  267. package/swf2js/__tests__/embedded-timeline-input.test.js +420 -0
  268. package/swf2js/__tests__/embedded-timer-lifecycle.test.js +145 -0
  269. package/swf2js/__tests__/event-priority-order.test.js +125 -0
  270. package/swf2js/__tests__/event-weak-listeners.test.js +53 -0
  271. package/swf2js/__tests__/event-will-trigger.test.js +43 -0
  272. package/swf2js/__tests__/flash-text-engine-content.test.js +115 -0
  273. package/swf2js/__tests__/flash-text-engine-format.test.js +95 -0
  274. package/swf2js/__tests__/flash-text-engine-line.test.js +314 -0
  275. package/swf2js/__tests__/font-encoder.test.js +95 -0
  276. package/swf2js/__tests__/font-outline-text.test.js +659 -0
  277. package/swf2js/__tests__/glow-shadow-filter.test.js +68 -0
  278. package/swf2js/__tests__/graphics-bitmap-smoothing.test.js +32 -0
  279. package/swf2js/__tests__/graphics-fill-lifetime.test.js +36 -0
  280. package/swf2js/__tests__/graphics-gradient-matrix.test.js +53 -0
  281. package/swf2js/__tests__/graphics-stroke-hit-test.test.js +457 -0
  282. package/swf2js/__tests__/hit-test-primitives.test.js +414 -0
  283. package/swf2js/__tests__/input-events.test.js +714 -0
  284. package/swf2js/__tests__/integration/corpus.test.js +41 -0
  285. package/swf2js/__tests__/loader-embedded-swf.test.js +210 -0
  286. package/swf2js/__tests__/loader-info.test.js +81 -0
  287. package/swf2js/__tests__/local-connection.test.js +122 -0
  288. package/swf2js/__tests__/morph-focal-gradient.test.js +51 -0
  289. package/swf2js/__tests__/morph-topology.test.js +267 -0
  290. package/swf2js/__tests__/movie-data-codec.test.js +128 -0
  291. package/swf2js/__tests__/nellymoser-audio.test.js +84 -0
  292. package/swf2js/__tests__/opaque-background-cache.test.js +352 -0
  293. package/swf2js/__tests__/path-stream.test.js +81 -0
  294. package/swf2js/__tests__/place-object-filters.test.js +88 -0
  295. package/swf2js/__tests__/place-object3-decoder.test.js +116 -0
  296. package/swf2js/__tests__/place-object3-image.test.js +85 -0
  297. package/swf2js/__tests__/player-version.test.js +46 -0
  298. package/swf2js/__tests__/root-textfield.test.js +287 -0
  299. package/swf2js/__tests__/scaling-grid.test.js +183 -0
  300. package/swf2js/__tests__/shape-decoder.test.js +361 -0
  301. package/swf2js/__tests__/shape-line-style2.test.js +138 -0
  302. package/swf2js/__tests__/shape-nonscaling-stroke.test.js +131 -0
  303. package/swf2js/__tests__/shape-pixel-hint.test.js +101 -0
  304. package/swf2js/__tests__/simplebutton-pointer.test.js +1477 -0
  305. package/swf2js/__tests__/socket-offline.test.js +67 -0
  306. package/swf2js/__tests__/sound-avm1-stop.test.js +99 -0
  307. package/swf2js/__tests__/sound-envelope.test.js +110 -0
  308. package/swf2js/__tests__/sound-extract.test.js +168 -0
  309. package/swf2js/__tests__/sound-id3.test.js +283 -0
  310. package/swf2js/__tests__/sound-load.test.js +259 -0
  311. package/swf2js/__tests__/sound-mixer-spectrum.test.js +261 -0
  312. package/swf2js/__tests__/sound-stream-sprite.test.js +624 -0
  313. package/swf2js/__tests__/sound-transform.test.js +104 -0
  314. package/swf2js/__tests__/speex-audio.test.js +77 -0
  315. package/swf2js/__tests__/stage-noscale.test.js +45 -0
  316. package/swf2js/__tests__/swf-encoder.test.js +134 -0
  317. package/swf2js/__tests__/swflib-assemble.test.js +20 -0
  318. package/swf2js/__tests__/textfield-html-text.test.js +368 -0
  319. package/swf2js/__tests__/textfield-line-layout.test.js +339 -0
  320. package/swf2js/__tests__/textfield-programmatic-overlay.test.js +2506 -0
  321. package/swf2js/__tests__/textfield-scroll.test.js +79 -0
  322. package/swf2js/__tests__/textfield-selection.test.js +383 -0
  323. package/swf2js/__tests__/timeline-effect-surfaces.test.js +295 -0
  324. package/swf2js/__tests__/timeline-named-anchor.test.js +139 -0
  325. package/swf2js/__tests__/timeline-scenes.test.js +1723 -0
  326. package/swf2js/__tests__/urlloader-http-status.test.js +236 -0
  327. package/{src → swf2js}/cli.js +43 -11
  328. package/swf2js/compiler/as2-classes.js +156 -0
  329. package/swf2js/compiler/as2-parser.js +598 -0
  330. package/swf2js/compiler/avm1-codegen.js +897 -0
  331. package/swf2js/compiler/index.js +28 -0
  332. package/{src → swf2js}/decoder/button-decoder.js +3 -1
  333. package/swf2js/decoder/png.js +114 -0
  334. package/{src → swf2js}/decoder/shape-decoder.js +20 -10
  335. package/{src → swf2js}/decoder/tag-decoder.js +5 -3
  336. package/{src → swf2js}/decoder/tag-types.js +4 -0
  337. package/swf2js/decompiler/avm1-decompiler.js +1138 -0
  338. package/{src → swf2js}/emitter/asset-encoder.js +66 -113
  339. package/{src → swf2js}/emitter/bundle-emitter.js +209 -78
  340. package/swf2js/emitter/external-resources.js +39 -0
  341. package/swf2js/emitter/movie-data-codec.js +91 -0
  342. package/swf2js/encoder/bit-writer.js +182 -0
  343. package/swf2js/encoder/shape-encoder.js +310 -0
  344. package/swf2js/encoder/swf-builder.js +639 -0
  345. package/swf2js/encoder/swf-writer.js +55 -0
  346. package/{src/runtime/swflib/assemble.js → swf2js/runtime/assemble-swooflib.js} +4 -3
  347. package/{src → swf2js}/runtime/avm1-runtime.js +102 -63
  348. package/{src → swf2js}/runtime/index.js +1 -1
  349. package/{src → swf2js}/runtime/movie-runtime.js +28 -2
  350. package/{src → swf2js}/transpiler/actionscript.js +82 -19
  351. package/{src → swf2js}/transpiler/avm1/avm1-opcodes.js +5 -3
  352. package/{src → swf2js}/transpiler/avm1/avm1-transpiler.js +69 -6
  353. package/{src → swf2js}/transpiler/avm2/avm2-transpiler.js +1 -1
  354. package/{src → swf2js}/transpiler/timeline/display-list.js +41 -22
  355. package/{src → swf2js}/transpiler/timeline/timeline-codegen.js +97 -36
  356. package/swooflib/README.md +569 -0
  357. package/swooflib/adpcm.js +147 -0
  358. package/{src/runtime/swflib → swooflib}/builtins.js +6 -0
  359. package/{src/runtime/swflib → swooflib}/context-menu.js +7 -1
  360. package/swooflib/control-definitions.js +42 -0
  361. package/swooflib/control-widget.js +763 -0
  362. package/swooflib/controls.js +300 -0
  363. package/{src/runtime/swflib → swooflib}/display.js +16 -10
  364. package/{src/runtime/swflib → swooflib}/events.js +11 -0
  365. package/{src/runtime/swflib → swooflib}/flash.js +6 -5
  366. package/{src/runtime/swflib → swooflib}/graphics.js +81 -19
  367. package/{src/runtime/swflib → swooflib}/input.js +12 -14
  368. package/{src/runtime/swflib → swooflib}/loader.js +52 -22
  369. package/swooflib/movie-network.js +86 -0
  370. package/swooflib/path-stream.js +169 -0
  371. package/{src/runtime/swflib → swooflib}/render.js +3 -13
  372. package/{src/runtime/swflib → swooflib}/sound.js +25 -2
  373. package/{src/runtime/swflib → swooflib}/stage.js +3 -3
  374. package/swooflib/stream-time.js +21 -0
  375. package/{src/runtime/swflib → swooflib}/system.js +88 -37
  376. package/{src/runtime/swflib → swooflib}/text-paint.js +14 -3
  377. package/{src/runtime/swflib → swooflib}/text.js +8 -0
  378. package/swooflib/xml-node.js +53 -0
  379. package/src/emitter/timeline-data-codec.js +0 -58
  380. /package/{src → swf2js}/decoder/symbol-table.js +0 -0
  381. /package/{src → swf2js}/emitter/embedded-swf.js +0 -0
  382. /package/{src → swf2js}/emitter/font-encoder.js +0 -0
  383. /package/{src → swf2js}/model/swf-document.js +0 -0
  384. /package/{src → swf2js}/model/transpile-result.js +0 -0
  385. /package/{src → swf2js}/parser/bit-reader.js +0 -0
  386. /package/{src → swf2js}/parser/decompressor.js +0 -0
  387. /package/{src → swf2js}/parser/swf-parser.js +0 -0
  388. /package/{src → swf2js}/pretty-printer/pretty-printer.js +0 -0
  389. /package/{src → swf2js}/runtime/avm2-runtime.js +0 -0
  390. /package/{src → swf2js}/runtime/embedded-movie-runtime.js +0 -0
  391. /package/{src → swf2js}/transpiler/avm1/avm1-ir.js +0 -0
  392. /package/{src → swf2js}/transpiler/avm1/avm1-rewrite.js +0 -0
  393. /package/{src → swf2js}/transpiler/avm2/abc-reader.js +0 -0
  394. /package/{src → swf2js}/transpiler/cfg-structurer.js +0 -0
  395. /package/{src → swf2js}/util/diagnostics.js +0 -0
  396. /package/{src → swf2js}/util/logger.js +0 -0
  397. /package/{src/runtime/swflib → swooflib}/bitmap-image.js +0 -0
  398. /package/{src/runtime/swflib → swooflib}/bitmap.js +0 -0
  399. /package/{src/runtime/swflib → swooflib}/bytearray.js +0 -0
  400. /package/{src/runtime/swflib → swooflib}/compiled-swf.js +0 -0
  401. /package/{src/runtime/swflib → swooflib}/cursor-flag.js +0 -0
  402. /package/{src/runtime/swflib → swooflib}/dictionary.js +0 -0
  403. /package/{src/runtime/swflib → swooflib}/filters.js +0 -0
  404. /package/{src/runtime/swflib → swooflib}/geom.js +0 -0
  405. /package/{src/runtime/swflib → swooflib}/glyph-metrics.js +0 -0
  406. /package/{src/runtime/swflib → swooflib}/host.js +0 -0
  407. /package/{src/runtime/swflib → swooflib}/inherit.js +0 -0
  408. /package/{src/runtime/swflib → swooflib}/marks.js +0 -0
  409. /package/{src/runtime/swflib → swooflib}/matrix3d.js +0 -0
  410. /package/{src/runtime/swflib → swooflib}/pointer-bridge.js +0 -0
  411. /package/{src/runtime/swflib → swooflib}/projection.js +0 -0
  412. /package/{src/runtime/swflib → swooflib}/sprite-drag.js +0 -0
  413. /package/{src/runtime/swflib → swooflib}/stage-ref.js +0 -0
  414. /package/{src/runtime/swflib → swooflib}/text-field.js +0 -0
  415. /package/{src/runtime/swflib → swooflib}/transform.js +0 -0
  416. /package/{src/runtime/swflib → swooflib}/xml.js +0 -0
@@ -0,0 +1,1164 @@
1
+ // Studio project → swf2js movie (studiospec/actionscript.md §3). Preview plays the project itself
2
+ // on the swf2js runtime, so ActionScript kept from imported SWFs runs against the project's own
3
+ // objects, edits included.
4
+ //
5
+ // The output is what swf2js builds from a SWF: a display list (frames with placements, and
6
+ // shape, text, sprite, and button characters) plus the tags the ActionScript transpiler reads
7
+ // (DoAction per frame, DoInitAction, sprites with their frame scripts). Shapes are drawn by
8
+ // Studio's own geometry code into a swooflib Graphics recorder, so they match the editor.
9
+ import { readFile } from 'node:fs/promises';
10
+ import '../../swooflib/flash.js';
11
+ import { Graphics } from '../../swooflib/graphics.js';
12
+ import { Matrix } from '../../swooflib/geom.js';
13
+ import { TAG } from '../../swf2js/decoder/tag-types.js';
14
+ import { transpileAvm1WithMeta } from '../../swf2js/transpiler/avm1/avm1-transpiler.js';
15
+ import { DiagnosticsCollector } from '../../swf2js/util/diagnostics.js';
16
+ import { paintVectorGeometry } from '../src/vector-geometry.js';
17
+ import { nativeMorphs } from './swf-morphs.js';
18
+ import { placementFilters } from '../src/placement-effects.js';
19
+ import { bitmapLayout } from '../src/media-assets.js';
20
+ import { matrixComponents, orderedSceneElements, poseAt, visibleAt } from '../src/model.js';
21
+ import { beginVectorFill, hasVectorFill } from '../src/vector-style.js';
22
+ import { CLIP_EVENT_HANDLERS } from '../../swf2js/runtime/avm1-runtime.js';
23
+ import { encodeComponentParameters } from '../src/components.js';
24
+ import { fieldText } from '../src/text-fields.js';
25
+ import { audioInfo } from './audio-info.js';
26
+ import { openClassLibrary } from './as3-library.js';
27
+ import { CompileError, compileActionScript } from '../../swf2js/compiler/index.js';
28
+
29
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
30
+ const CLIP_FLAGS = Object.fromEntries(CLIP_EVENT_HANDLERS.map(([bit, name]) => [name[2].toLowerCase() + name.slice(3), bit]));
31
+ const BUTTON_CONDITIONS = {
32
+ press: 'overUpToOverDown', release: 'overDownToOverUp', releaseOutside: 'outDownToIdle', rollOver: 'idleToOverUp',
33
+ rollOut: 'overUpToIdle', dragOver: 'outDownToOverDown', dragOut: 'overDownToOutDown',
34
+ menuDragOver: 'idleToOverDown', menuDragOut: 'overDownToIdle',
35
+ };
36
+ // Flash key codes for Studio's keyboard triggers (BUTTONCONDACTION keyPress codes).
37
+ const KEY_PRESS = { ArrowLeft: 1, ArrowRight: 2, Home: 3, End: 4, Insert: 5, Delete: 6, Backspace: 8, Enter: 13, ArrowUp: 14, ArrowDown: 15, Space: 32 };
38
+
39
+ // --- Colors and fills -------------------------------------------------------
40
+
41
+ function hexNumber(hex) {
42
+ return parseInt(String(hex ?? '#000000').slice(1, 7), 16) || 0;
43
+ }
44
+
45
+ function cssColor(color, alpha = 1) {
46
+ if (typeof color === 'string' && !color.startsWith('#')) return color;
47
+ const value = typeof color === 'number' ? color : hexNumber(color);
48
+ const r = (value >> 16) & 255, g = (value >> 8) & 255, b = value & 255;
49
+ if (alpha >= 1) return '#' + value.toString(16).padStart(6, '0');
50
+ return `rgba(${r},${g},${b},${Math.round(alpha * 10000) / 10000})`;
51
+ }
52
+
53
+ const plainMatrix = m => ({ a: m.a, b: m.b, c: m.c, d: m.d, tx: m.tx, ty: m.ty });
54
+
55
+ function fillFromGraphics(fill, bitmapIds) {
56
+ if (!fill) return null;
57
+ if (fill.gradientType) {
58
+ return {
59
+ type: fill.gradientType === 'radial' ? 'radial' : 'linear',
60
+ matrix: plainMatrix(fill.matrix ?? new Matrix()),
61
+ stops: fill.colors.map((color, i) => ({ ratio: fill.ratios[i] ?? 0, color: cssColor(color, fill.alphas[i] ?? 1) })),
62
+ focal: fill.focalPointRatio || 0, spreadMode: { reflect: 1, repeat: 2 }[fill.spreadMethod] ?? 0,
63
+ interpolationMode: fill.interpolationMethod === 'linearRGB' ? 1 : 0,
64
+ };
65
+ }
66
+ if (fill.bitmap) {
67
+ return { type: 'bitmap', bitmapId: bitmapIds(fill.bitmap), matrix: plainMatrix(fill.matrix ?? new Matrix()), repeat: !!fill.repeat, smoothed: !!fill.smooth };
68
+ }
69
+ return { type: 'solid', color: fill.color };
70
+ }
71
+
72
+ // --- Graphics recording → swf2js draw lists ----------------------------------
73
+
74
+ // SWF geometry is stored in twips (1/20 px). Draws snapped to whole twips match what Flash
75
+ // itself can express, and swf2js stores them in its compact geometry encoding
76
+ // (swooflib/path-stream.js), which takes only whole-twip coordinates.
77
+ const TWIP = 1 / 20;
78
+ const snap = value => Math.round(value * 20) / 20;
79
+ const snapCommand = command => command.map((value, index) => index === 0 ? value : snap(value));
80
+
81
+ // Cubic → quadratics. A cubic that is an elevated quadratic (SWF curves imported as cubic
82
+ // handles, whose stored handles are rounded) becomes that quadratic when its two control-point
83
+ // estimates agree within a twip; others are split in four.
84
+ function cubicToQuads(x0, y0, c1x, c1y, c2x, c2y, x, y) {
85
+ // Studio draws every segment as a cubic; one whose control points lie on the line between its
86
+ // ends (no handles, as on straight edges) is that line.
87
+ if (onSegment(c1x, c1y, x0, y0, x, y) && onSegment(c2x, c2y, x0, y0, x, y)) return [['L', x, y]];
88
+ const qx1 = (3 * c1x - x0) / 2, qy1 = (3 * c1y - y0) / 2;
89
+ const qx2 = (3 * c2x - x) / 2, qy2 = (3 * c2y - y) / 2;
90
+ if (Math.abs(qx1 - qx2) <= TWIP && Math.abs(qy1 - qy2) <= TWIP) return [['Q', (qx1 + qx2) / 2, (qy1 + qy2) / 2, x, y]];
91
+ const out = [];
92
+ const point = (t, a, b, c, d) => {
93
+ const u = 1 - t;
94
+ return u * u * u * a + 3 * u * u * t * b + 3 * u * t * t * c + t * t * t * d;
95
+ };
96
+ const derivative = (t, a, b, c, d) => {
97
+ const u = 1 - t;
98
+ return 3 * (u * u * (b - a) + 2 * u * t * (c - b) + t * t * (d - c));
99
+ };
100
+ const steps = 4;
101
+ let px = x0, py = y0;
102
+ for (let i = 1; i <= steps; i++) {
103
+ const t0 = (i - 1) / steps, t1 = i / steps;
104
+ const ex = point(t1, x0, c1x, c2x, x), ey = point(t1, y0, c1y, c2y, y);
105
+ // Control point where the end tangents meet; midpoint fallback when parallel.
106
+ const d0x = derivative(t0, x0, c1x, c2x, x), d0y = derivative(t0, y0, c1y, c2y, y);
107
+ const d1x = derivative(t1, x0, c1x, c2x, x), d1y = derivative(t1, y0, c1y, c2y, y);
108
+ const cross = d0x * d1y - d0y * d1x;
109
+ let cx, cy;
110
+ if (Math.abs(cross) > 1e-9) {
111
+ const s = ((ex - px) * d1y - (ey - py) * d1x) / cross;
112
+ cx = px + d0x * s; cy = py + d0y * s;
113
+ } else {
114
+ const mt = (t0 + t1) / 2;
115
+ cx = 2 * point(mt, x0, c1x, c2x, x) - (px + ex) / 2; cy = 2 * point(mt, y0, c1y, c2y, y) - (py + ey) / 2;
116
+ }
117
+ out.push(['Q', cx, cy, ex, ey]);
118
+ px = ex; py = ey;
119
+ }
120
+ return out;
121
+ }
122
+
123
+ /** True when (px, py) lies within half a twip of the segment (ax, ay)–(bx, by). */
124
+ function onSegment(px, py, ax, ay, bx, by) {
125
+ const dx = bx - ax, dy = by - ay, length = dx * dx + dy * dy;
126
+ const t = length ? Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / length)) : 0;
127
+ return Math.hypot(px - (ax + t * dx), py - (ay + t * dy)) <= TWIP / 2;
128
+ }
129
+
130
+ function circlePath(x, y, r) {
131
+ const k = 0.5522847498 * r;
132
+ return [['M', x + r, y],
133
+ ...cubicToQuads(x + r, y, x + r, y + k, x + k, y + r, x, y + r),
134
+ ...cubicToQuads(x, y + r, x - k, y + r, x - r, y + k, x - r, y),
135
+ ...cubicToQuads(x - r, y, x - r, y - k, x - k, y - r, x, y - r),
136
+ ...cubicToQuads(x, y - r, x + k, y - r, x + r, y - k, x + r, y), ['Z']];
137
+ }
138
+
139
+ /**
140
+ * A path of M, L and Q commands cut into dashes: `dash` lists on and off lengths (repeated, as
141
+ * canvas and SVG repeat an odd list twice), starting `offset` into the pattern.
142
+ */
143
+ export function dashedPath(path, dash, offset = 0) {
144
+ const pattern = dash.length % 2 ? [...dash, ...dash] : dash;
145
+ const total = pattern.reduce((sum, value) => sum + value, 0);
146
+ if (!(total > 0)) return path;
147
+ const out = [];
148
+ let index = 0, left = pattern[0], on = true;
149
+ let skip = ((offset % total) + total) % total;
150
+ while (skip > 0) {
151
+ if (skip < left) { left -= skip; break; }
152
+ skip -= left; index = (index + 1) % pattern.length; left = pattern[index]; on = !on;
153
+ }
154
+ let x = 0, y = 0, drawing = false;
155
+ const point = (p0, p1, p2, t) => p2 ? [(1 - t) ** 2 * p0[0] + 2 * (1 - t) * t * p1[0] + t * t * p2[0], (1 - t) ** 2 * p0[1] + 2 * (1 - t) * t * p1[1] + t * t * p2[1]]
156
+ : [p0[0] + (p1[0] - p0[0]) * t, p0[1] + (p1[1] - p0[1]) * t];
157
+ // A quadratic piece between t0 and t1 (its control point by blossoming).
158
+ const quadPiece = (p0, c, p2, t0, t1) => {
159
+ const blossom = (a, b) => [(1 - a) * (1 - b) * p0[0] + ((1 - a) * b + a * (1 - b)) * c[0] + a * b * p2[0], (1 - a) * (1 - b) * p0[1] + ((1 - a) * b + a * (1 - b)) * c[1] + a * b * p2[1]];
160
+ const [cx, cy] = blossom(t0, t1), [ex, ey] = blossom(t1, t1);
161
+ return ['Q', cx, cy, ex, ey];
162
+ };
163
+ for (const command of path) {
164
+ if (command[0] === 'M') { x = command[1]; y = command[2]; drawing = false; continue; }
165
+ const start = [x, y], control = command[0] === 'Q' ? [command[1], command[2]] : null, end = command[0] === 'Q' ? [command[3], command[4]] : [command[1], command[2]];
166
+ // Arc length by sampling; t for a length by interpolating the samples.
167
+ const samples = control ? 16 : 1, lengths = [0];
168
+ let previous = start;
169
+ for (let i = 1; i <= samples; i++) {
170
+ const next = point(start, control ?? end, control ? end : null, i / samples);
171
+ lengths.push(lengths[i - 1] + Math.hypot(next[0] - previous[0], next[1] - previous[1]));
172
+ previous = next;
173
+ }
174
+ const length = lengths[samples];
175
+ const tAt = distance => {
176
+ if (!control) return length ? distance / length : 0;
177
+ let i = 1;
178
+ while (i < samples && lengths[i] < distance) i++;
179
+ const span = lengths[i] - lengths[i - 1] || 1;
180
+ return (i - 1 + (distance - lengths[i - 1]) / span) / samples;
181
+ };
182
+ let at = 0;
183
+ while (at < length - 1e-9) {
184
+ const step = Math.min(left, length - at);
185
+ if (on) {
186
+ const t0 = tAt(at), t1 = tAt(at + step);
187
+ if (!drawing) { const p = point(start, control ?? end, control ? end : null, t0); out.push(['M', p[0], p[1]]); drawing = true; }
188
+ if (control) out.push(quadPiece(start, control, end, t0, t1));
189
+ else { const p = point(start, end, null, t1); out.push(['L', p[0], p[1]]); }
190
+ }
191
+ at += step; left -= step;
192
+ if (left <= 1e-9) { index = (index + 1) % pattern.length; left = pattern[index]; on = !on; drawing = false; }
193
+ }
194
+ x = end[0]; y = end[1];
195
+ }
196
+ return out;
197
+ }
198
+
199
+ /** Convert recorded Graphics commands into swf2js draws: one fill draw and one stroke draw per run. */
200
+ function graphicsDraws(commands, bitmapIds) {
201
+ const draws = [];
202
+ let fill = null, line = null, path = [], x = 0, y = 0, startX = 0, startY = 0, evenOdd = false, nonZero = false;
203
+ const flush = () => {
204
+ if (path.length > 1 || path.some(command => command[0] !== 'M')) {
205
+ path = path.map(snapCommand);
206
+ if (fill) draws.push({ fill: fillFromGraphics(fill, bitmapIds), evenOdd, ...(nonZero && { nonZero }), path });
207
+ if (line && line.width > 0) {
208
+ const stroke = { width: line.width, color: line.color, cap: line.cap, join: line.join, miterLimit: line.miterLimit };
209
+ if (line.fill) stroke.fill = fillFromGraphics(line.fill, bitmapIds);
210
+ // SWF has no dashes: the stroke is cut into its dashes.
211
+ draws.push({ stroke, path: line.dash ? dashedPath(path, line.dash, line.dashOffset) : path });
212
+ }
213
+ }
214
+ path = [];
215
+ };
216
+ for (const command of commands) {
217
+ switch (command.op) {
218
+ case 'winding': flush(); evenOdd = command.rule === 'evenodd'; nonZero = !evenOdd; break;
219
+ case 'fill': flush(); fill = command.fill; break;
220
+ case 'endFill': flush(); fill = null; break;
221
+ case 'lineStyle': flush(); line = command.line; break;
222
+ case 'M': path.push(['M', command.x, command.y]); x = startX = command.x; y = startY = command.y; break;
223
+ case 'L': path.push(['L', command.x, command.y]); x = command.x; y = command.y; break;
224
+ case 'Q': path.push(['Q', command.cx, command.cy, command.x, command.y]); x = command.x; y = command.y; break;
225
+ case 'C': path.push(...cubicToQuads(x, y, command.c1x, command.c1y, command.c2x, command.c2y, command.x, command.y)); x = command.x; y = command.y; break;
226
+ case 'Z': path.push(['L', startX, startY]); x = startX; y = startY; break;
227
+ case 'circle': path.push(...circlePath(command.x, command.y, command.r)); break;
228
+ default: break;
229
+ }
230
+ }
231
+ flush();
232
+ return draws;
233
+ }
234
+
235
+ function drawsBounds(draws) {
236
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
237
+ for (const draw of draws) {
238
+ const pad = (draw.stroke?.width ?? 0) / 2;
239
+ for (const command of draw.path) {
240
+ for (let i = 1; i < command.length; i += 2) {
241
+ minX = Math.min(minX, command[i] - pad); maxX = Math.max(maxX, command[i] + pad);
242
+ minY = Math.min(minY, command[i + 1] - pad); maxY = Math.max(maxY, command[i + 1] + pad);
243
+ }
244
+ }
245
+ }
246
+ if (minX === Infinity) return { x: 0, y: 0, w: 0, h: 0 };
247
+ return { x: minX, y: minY, w: maxX - minX, h: maxY - minY };
248
+ }
249
+
250
+ // A multipart imported shape has editable Studio layers. Preserve its native Shape
251
+ // identity on a frame seek: Flash can retain a MovieClip instance when rewinding.
252
+ function compoundDraws(places, characters) {
253
+ const draws = [];
254
+ for (const place of places) {
255
+ const shape = characters[place.characterId], m = place.matrix;
256
+ if (shape?.type !== 'shape' || !shape.draws || place.colorTransform || place.filters?.length ||
257
+ place.blendMode > 1 || place.clipDepth || place.name || !m || m.a !== 1 || m.d !== 1 || m.b || m.c) return null;
258
+ const x = m.tx / 20, y = m.ty / 20;
259
+ const translateFill = fill => fill?.matrix
260
+ ? { ...fill, matrix: { ...fill.matrix, tx: fill.matrix.tx + x, ty: fill.matrix.ty + y } } : fill;
261
+ for (const draw of shape.draws) {
262
+ const path = draw.path.map(([op, ...coords]) => [op, ...coords.map((v, i) => snap(v + (i % 2 ? y : x)))]);
263
+ draws.push({ ...draw, path, ...(draw.fill && { fill: translateFill(draw.fill) }),
264
+ ...(draw.stroke?.fill && { stroke: { ...draw.stroke, fill: translateFill(draw.stroke.fill) } }) });
265
+ }
266
+ }
267
+ return draws;
268
+ }
269
+
270
+ // --- AVM1 for Studio's typed actions ------------------------------------------
271
+
272
+ function avm1String(text) {
273
+ return [0, ...Buffer.from(String(text), 'utf8'), 0];
274
+ }
275
+ function avm1Push(...values) {
276
+ const body = values.flatMap(value => {
277
+ if (typeof value === 'string') return avm1String(value);
278
+ if (typeof value === 'boolean') return [5, value ? 1 : 0];
279
+ const bytes = Buffer.alloc(8);
280
+ bytes.writeDoubleLE(value);
281
+ return [6, ...bytes.subarray(4), ...bytes.subarray(0, 4)]; // AVM1 doubles store the high word first.
282
+ });
283
+ return [0x96, body.length & 255, body.length >> 8, ...body];
284
+ }
285
+ const gotoFrame = index => [0x81, 2, 0, index & 255, (index >> 8) & 255];
286
+
287
+ /** Bytecode for typed actions. `frameIndex(target)` maps Studio frames to timeline indexes. */
288
+ function typedActionBytes(actions, { frameIndex, sceneStart, objectPath, sceneTransition = () => null }) {
289
+ const out = [];
290
+ for (const action of actions) {
291
+ if (action.type === 'stop') out.push(0x07);
292
+ else if (action.type === 'play') out.push(0x06);
293
+ else if (action.type === 'gotoFrame') {
294
+ out.push(...gotoFrame(frameIndex(action.target)));
295
+ if (action.play) out.push(0x06); else out.push(0x07);
296
+ } else if (action.type === 'gotoScene') {
297
+ const start = sceneStart(action.target);
298
+ if (start == null) continue;
299
+ // A scene with an entry transition first lays the outgoing stage over it (SWF export).
300
+ out.push(...(sceneTransition(action.target) ?? []));
301
+ // Scenes live on the root timeline: SetTarget2 "_root", jump, then back to this timeline.
302
+ out.push(...avm1Push('_root'), 0x20, ...gotoFrame(start), action.play ? 0x06 : 0x07, ...avm1Push(''), 0x20);
303
+ } else if (action.type === 'show' || action.type === 'hide' || action.type === 'toggleVisibility') {
304
+ const path = objectPath(action.target);
305
+ if (!path) continue;
306
+ if (action.type === 'toggleVisibility') out.push(...avm1Push(path, 7, path, 7), 0x22, 0x12, 0x23);
307
+ else out.push(...avm1Push(path, 7, action.type === 'show'), 0x23);
308
+ }
309
+ }
310
+ return out.length ? new Uint8Array([...out, 0]) : null;
311
+ }
312
+
313
+ // --- Images -------------------------------------------------------------------
314
+
315
+ export function imageSize(data) {
316
+ if (data[0] === 0x89 && data[1] === 0x50) return { width: data.readUInt32BE(16), height: data.readUInt32BE(20) };
317
+ if (data[0] === 0xff && data[1] === 0xd8) {
318
+ let offset = 2;
319
+ while (offset + 9 < data.length) {
320
+ if (data[offset] !== 0xff) { offset++; continue; }
321
+ const marker = data[offset + 1];
322
+ const length = data.readUInt16BE(offset + 2);
323
+ if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) {
324
+ return { width: data.readUInt16BE(offset + 7), height: data.readUInt16BE(offset + 5) };
325
+ }
326
+ offset += 2 + length;
327
+ }
328
+ }
329
+ if (data.toString('ascii', 0, 4) === 'RIFF' && data.toString('ascii', 8, 12) === 'WEBP') return null;
330
+ if (data.toString('ascii', 0, 3) === 'GIF') return { width: data.readUInt16LE(6), height: data.readUInt16LE(8) };
331
+ return null;
332
+ }
333
+
334
+ // Same placement as Studio's bitmapLayout for "stretch", "contain", and "cover".
335
+ // --- Conversion -----------------------------------------------------------------
336
+
337
+ /** A written script that does not compile: Preview and export stop with it, naming the script. */
338
+ export class ScriptCompileError extends Error {
339
+ constructor(message, scriptId, cause) {
340
+ super(message);
341
+ this.name = 'ScriptCompileError';
342
+ this.scriptId = scriptId;
343
+ this.line = cause.line ?? null;
344
+ this.column = cause.column ?? null;
345
+ }
346
+ }
347
+
348
+ /**
349
+ * Convert a parsed project. `readAsset(asset)` returns `{ bytes, ext, mimeType }` for an image
350
+ * or audio asset. Returns the emit input plus the asset files to write.
351
+ */
352
+ export async function buildProjectMovie(project, { readAsset, streamAudio = true, nativeControls = false, sceneTransitions = false }) {
353
+ const report = [];
354
+ const note = message => { if (!report.includes(message)) report.push(message); };
355
+ const usesAvm2 = [...project.scenes, ...(project.symbols ?? [])].some(timeline => timeline.avm2?.length);
356
+ const swfVersion = Math.max(usesAvm2 ? 9 : 6, ...(project.scripts ?? []).map(script => script.swfVersion));
357
+ // Exported SWFs without scripts are SWF 8 (swf-export.js). Transitions draw the stage into a
358
+ // BitmapData, which needs SWF 8, and are written for AVM1 movies only.
359
+ const transitionsWritten = sceneTransitions && !usesAvm2 && (project.scripts?.length ? swfVersion : Math.max(8, swfVersion)) >= 8 &&
360
+ project.scenes.some(scene => scene.transition);
361
+ const transitionCalls = new Map();
362
+ const sceneTransition = targetId => {
363
+ if (!transitionsWritten) return null;
364
+ const index = project.scenes.findIndex(scene => scene.id === targetId);
365
+ const transition = project.scenes[index]?.transition;
366
+ if (!transition) return null;
367
+ if (!transitionCalls.has(targetId)) {
368
+ const first = project.scenes.slice(0, index).reduce((sum, scene) => sum + scene.durationFrames, 0) + 1;
369
+ const last = first + project.scenes[index].durationFrames - 1;
370
+ const call = compileActionScript(`__swoofTransition(${first}, ${last}, ${JSON.stringify(transition.type)}, ${transition.durationFrames}, ` +
371
+ `${JSON.stringify(transition.easing)}, ${project.stage.width}, ${project.stage.height});`, { swfVersion: 8 });
372
+ transitionCalls.set(targetId, call.at(-1) === 0 ? call.subarray(0, -1) : call);
373
+ }
374
+ return transitionCalls.get(targetId);
375
+ };
376
+ const scriptsById = new Map((project.scripts ?? []).map(script => [script.id, script]));
377
+ // Written scripts are compiled here, when the project is built for playback (actionscript.md §4.4).
378
+ const sceneOffsets = {};
379
+ project.scenes.reduce((offset, scene) => { sceneOffsets[scene.name] = offset; return offset + scene.durationFrames; }, 0);
380
+ const compiledScripts = new Map();
381
+ const bytecodeOf = script => {
382
+ if (script.language !== 'actionscript') return new Uint8Array(Buffer.from(script.bytecode, 'base64'));
383
+ if (!compiledScripts.has(script.id)) {
384
+ try {
385
+ compiledScripts.set(script.id, compileActionScript(script.code, { swfVersion: script.swfVersion, scenes: sceneOffsets }));
386
+ } catch (error) {
387
+ if (!(error instanceof CompileError)) throw error;
388
+ const where = error.line ? ` (line ${error.line}, column ${error.column})` : '';
389
+ throw new ScriptCompileError(`Script "${script.name ?? script.id}" has an error${where}: ${error.reason}`, script.id, error);
390
+ }
391
+ }
392
+ return compiledScripts.get(script.id);
393
+ };
394
+ const symbolsById = new Map((project.symbols ?? []).map(symbol => [symbol.id, symbol]));
395
+ // Keep the original adjacent record with its frame action. An AVM1 branch can
396
+ // enter that record even when its total size exceeds the signed jump range.
397
+ const frameActionTags = (script, fields) => {
398
+ const action = { ...fields, bytecode: bytecodeOf(script) };
399
+ return script.linkedPrefix ? [{ code: 253, data: Buffer.from(script.linkedPrefix, 'base64') }, action] : [action];
400
+ };
401
+ const characters = {};
402
+ const nativeLibrary = await openClassLibrary(project);
403
+ let nextId = (nativeLibrary?.maxId ?? 0) + 1;
404
+ const allocate = () => nextId++;
405
+
406
+ // Images become bitmap assets that shapes fill.
407
+ const files = [];
408
+ const assetManifest = [];
409
+ const bitmaps = new Map();
410
+ async function bitmapFor(assetId) {
411
+ if (bitmaps.has(assetId)) return bitmaps.get(assetId);
412
+ const asset = (project.assets ?? []).find(item => item.id === assetId);
413
+ let entry = null;
414
+ if (asset) {
415
+ const file = await readAsset(asset);
416
+ if (file) {
417
+ const id = allocate();
418
+ const name = `image_${id}.${file.ext}`;
419
+ files.push({ name, bytes: file.bytes });
420
+ assetManifest.push({ id, type: 'bitmap', mimeType: file.mimeType, path: `assets/${name}` });
421
+ entry = { id, size: imageSize(file.bytes) ?? { width: 1, height: 1 } };
422
+ }
423
+ }
424
+ bitmaps.set(assetId, entry);
425
+ return entry;
426
+ }
427
+
428
+ // Sounds: audio assets that clips play or scripts attach by linkage name.
429
+ const sounds = new Map(); // asset id → { id, seconds }
430
+ const eventSoundAssets = new Set();
431
+ async function soundFor(assetId, streamOnly = false) {
432
+ if (!streamOnly) eventSoundAssets.add(assetId);
433
+ if (sounds.has(assetId)) return sounds.get(assetId);
434
+ const asset = (project.assets ?? []).find(item => item.kind === 'audio' && item.id === assetId);
435
+ let entry = null;
436
+ const file = asset && await readAsset(asset);
437
+ if (file) {
438
+ const id = allocate();
439
+ const name = `sound_${id}.${file.ext}`;
440
+ const info = audioInfo(file.bytes);
441
+ files.push({ name, bytes: file.bytes });
442
+ assetManifest.push({ id, type: 'audio', mimeType: file.mimeType, path: `assets/${name}`,
443
+ sampleRate: info?.sampleRate ?? 44100, sampleCount: info?.sampleCount ?? 0 });
444
+ entry = { id, seconds: info?.sampleCount ? info.sampleCount / info.sampleRate : 0 };
445
+ }
446
+ sounds.set(assetId, entry);
447
+ return entry;
448
+ }
449
+
450
+ /**
451
+ * Frame cues for a timeline's audio clips (swooflib-integration.md): a clip starts its sound at
452
+ * its start frame, looping for its length when `loop` is set, and stops it on the frame after
453
+ * its end, as leaving a clip does in the editor.
454
+ */
455
+ const linkedSounds = new Set([...project.scenes, ...(project.symbols ?? [])].flatMap(timeline =>
456
+ (timeline.avm2 ?? []).flatMap(record => (record.classes ?? []).filter(binding =>
457
+ binding.asset ? project.assets?.some(asset => asset.kind === 'audio' && asset.id === binding.asset)
458
+ : nativeLibrary?.symbolTable.get(binding.native)?.type === 'Sound').map(binding => binding.name.replace('::', '.')))));
459
+ async function clipSounds(timeline, frame) {
460
+ const cues = [];
461
+ for (const clip of timeline.audioClips ?? []) {
462
+ if (streamAudio && clip.streamSync && !clip.loop) continue;
463
+ if (clip.start !== frame && clip.end + 1 !== frame) continue;
464
+ const byClass = clip.soundClassName && linkedSounds.has(clip.soundClassName.replace('::', '.'));
465
+ const sound = byClass ? null : await soundFor(clip.assetId);
466
+ if (!byClass && !sound) continue;
467
+ if (clip.soundInfo) {
468
+ const reference = byClass ? { soundClassName: clip.soundClassName } : { soundId: sound.id };
469
+ if (clip.start === frame) cues.push({ ...reference, soundInfo: clip.soundInfo });
470
+ if (clip.cutAtEnd && frame === clip.end + 1) cues.push({ ...reference, soundInfo: { syncStop: true } });
471
+ continue;
472
+ }
473
+ if (clip.start === frame) {
474
+ const seconds = (clip.end - clip.start + 1) / project.stage.frameRate;
475
+ const loopCount = clip.loop ? (sound.seconds ? Math.max(1, Math.ceil(seconds / sound.seconds)) : 1000) : null;
476
+ cues.push({ soundId: sound.id, soundInfo: { loopCount } });
477
+ }
478
+ if (clip.end + 1 === frame) cues.push({ soundId: sound.id, soundInfo: { syncStop: true } });
479
+ }
480
+ return cues;
481
+ }
482
+
483
+ // A streamed sound follows its owning timeline when a script jumps, pauses, or loops.
484
+ // Multiple segments can reference the same media file but need distinct runtime entries.
485
+ async function attachStreams(timeline, frameOffset, spriteId) {
486
+ let attached = false;
487
+ for (const clip of timeline.audioClips ?? []) {
488
+ if (!clip.streamSync || clip.loop) continue;
489
+ if (!streamAudio) { note('Streaming audio exported as event sounds'); continue; }
490
+ const sound = await soundFor(clip.assetId, true);
491
+ if (!sound) continue;
492
+ const asset = assetManifest.find(entry => entry.id === sound.id);
493
+ const segment = asset.stream ? { ...asset, id: allocate() } : asset;
494
+ const start = frameOffset + clip.start - 1;
495
+ Object.assign(segment, { stream: true, spriteStream: spriteId, streamStart: start, streamEnd: frameOffset + clip.end,
496
+ streamSync: { ...clip.streamSync, seekMap: clip.streamSync.seekMap.map(block => ({ ...block, frame: start + block.frame })) } });
497
+ if (streamAudio === 'native' && clip.nativeStream) segment.nativeStream = clip.nativeStream;
498
+ if (segment !== asset) assetManifest.push(segment);
499
+ attached = true;
500
+ }
501
+ return attached;
502
+ }
503
+
504
+ // Shape and text characters are shared by every placement with the same look.
505
+ const looks = new Map();
506
+ async function artworkCharacter(element, pose) {
507
+ if (element.type === 'text') {
508
+ const field = element.field ?? {};
509
+ const key = JSON.stringify(['text', element.id, pose.width, pose.height, pose.text, pose.fontFamily, pose.fontSize, pose.textColor, pose.textAlign, pose.bold, element.italic]);
510
+ if (looks.has(key)) return looks.get(key);
511
+ const id = allocate();
512
+ const fontId = field.fontLibrary ? nativeLibrary?.fontIds.get(field.fontLibrary)?.get(field.fontId) : field.fontId;
513
+ characters[id] = {
514
+ type: 'text', kind: 'edit', bounds: { x: -pose.width / 2, y: -pose.height / 2, w: pose.width, h: pose.height },
515
+ ...(pose.fontFamily === field.fontFamily && nativeLibrary?.symbolTable.get(fontId)?.type === 'Font' &&
516
+ { fontId, ...(field.useOutlines && { outlineFontId: fontId }) }),
517
+ color: cssColor(pose.textColor), text: fieldText(element, pose), hasText: true,
518
+ fontSize: pose.fontSize, font: pose.fontFamily, bold: !!pose.bold, italic: !!element.italic,
519
+ readOnly: !(field.editable ?? element.inputText), editable: !!(field.editable ?? element.inputText),
520
+ selectable: !!(field.selectable ?? element.inputText), border: !!field.border, wasStatic: false,
521
+ password: !!field.password, wordWrap: field.wordWrap ?? true, multiline: field.multiline ?? true, html: !!field.html,
522
+ maxLength: field.maxLength ?? 0, align: pose.textAlign ?? 'left', leftMargin: 0, rightMargin: 0, indent: 0, leading: 0,
523
+ variableName: field.variable ?? '',
524
+ };
525
+ looks.set(key, id);
526
+ return id;
527
+ }
528
+ const graphics = new Graphics();
529
+ let key;
530
+ if (element.type === 'bitmap') {
531
+ const bitmap = await bitmapFor(element.assetId);
532
+ if (!bitmap) return null;
533
+ // Same layout as the editor (canvas.js), crop-to-fill alignment and source rectangle included.
534
+ const box = bitmapLayout(pose.width, pose.height, bitmap.size.width || pose.width, bitmap.size.height || pose.height,
535
+ element.fit, element.cropX, element.cropY, element.crop);
536
+ key = JSON.stringify(['bitmap', element.assetId, element.smoothed, element.fit, element.cropX, element.cropY, element.crop, pose.width, pose.height]);
537
+ if (looks.has(key)) return looks.get(key);
538
+ const matrix = new Matrix(box.scaleX, 0, 0, box.scaleY, box.x, box.y);
539
+ graphics.beginBitmapFill(bitmap.id, matrix, false, element.smoothed ?? true);
540
+ graphics.drawRect(-box.width / 2, -box.height / 2, box.width, box.height);
541
+ graphics.endFill();
542
+ } else {
543
+ key = JSON.stringify(['vector', element.type, element.assetId, element.bitmapFill, element.bitmapStroke, element.closed, pose.starPoints, pose.starRadius, pose.cornerRadius, pose.erasures, pose.width, pose.height, pose.fill, pose.stroke, pose.strokeWidth, pose.strokeGradient, pose.gradient, pose.points, pose.subpaths,
544
+ element.lineCap, element.lineJoin, element.miterLimit, element.strokeDash, element.strokeDashOffset, element.fillRule,
545
+ pose.text && [pose.text, pose.fontFamily, pose.fontSize, pose.textColor, pose.textAlign, pose.bold]]);
546
+ if (looks.has(key)) return looks.get(key);
547
+ const filled = hasVectorFill(element);
548
+ if (element.bitmapFill) {
549
+ const bitmap = await bitmapFor(element.assetId);
550
+ if (!bitmap) return null;
551
+ const { matrix: m, repeat, smoothed } = element.bitmapFill;
552
+ graphics.beginBitmapFill(bitmap.id, new Matrix(m.a, m.b, m.c, m.d, m.tx, m.ty), repeat, smoothed);
553
+ } else if (filled) beginVectorFill(graphics, pose);
554
+ const strokeBitmap = element.bitmapStroke && await bitmapFor(element.bitmapStroke.assetId);
555
+ paintVectorGeometry(graphics, element, pose, filled, strokeBitmap?.id);
556
+ }
557
+ const draws = graphicsDraws(graphics._cmds, bitmap => bitmap);
558
+ const shapeId = allocate();
559
+ characters[shapeId] = { type: 'shape', bounds: drawsBounds(draws), draws };
560
+ // A shape with a label (a "NEXT" button, a tag) is the shape with a read-only text field on
561
+ // top, centered vertically as the editor draws it (canvas.js makeArtwork).
562
+ let id = shapeId;
563
+ if (pose.text && element.type !== 'bitmap') {
564
+ const height = Math.min(pose.height, pose.fontSize * 1.25 + 4);
565
+ const labelId = allocate();
566
+ characters[labelId] = {
567
+ type: 'text', kind: 'edit', bounds: { x: -pose.width / 2, y: -height / 2, w: pose.width, h: height },
568
+ color: cssColor(pose.textColor), text: pose.text, hasText: true, fontSize: pose.fontSize, font: pose.fontFamily, bold: !!pose.bold,
569
+ readOnly: true, editable: false, selectable: false, border: false, wasStatic: false, password: false,
570
+ wordWrap: true, multiline: true, html: false, maxLength: 0, align: pose.textAlign ?? 'center',
571
+ leftMargin: 0, rightMargin: 0, indent: 0, leading: 0, variableName: '',
572
+ };
573
+ id = allocate();
574
+ characters[id] = { type: 'sprite', frameCount: 1, bounds: drawsBounds(draws),
575
+ frames: [{ frameIndex: 0, removes: [], places: [{ depth: 1, characterId: shapeId }, { depth: 2, characterId: labelId }] }] };
576
+ }
577
+ looks.set(key, id);
578
+ return id;
579
+ }
580
+
581
+ // Sprite IDs first, so timelines can refer to symbols defined later (and to themselves).
582
+ const morphVariants = nativeControls ? await nativeMorphs(project, allocate, bitmapFor, characters, note) : new Map();
583
+ const spriteIds = new Map();
584
+ for (const symbol of project.symbols ?? []) spriteIds.set(symbol.id, nativeLibrary?.ids.get(symbol.id) ?? allocate());
585
+ // A Flash clip loops unless a script stops it. Studio sets looping per symbol and per instance
586
+ // (symbolMode), so an instance that plays differently from its symbol gets its own copy.
587
+ const pendingSprites = (project.symbols ?? []).map(symbol => ({ symbol, id: spriteIds.get(symbol.id), loops: !!symbol.loop }));
588
+ const spriteVariants = new Map();
589
+ const authoringVariants = [], automaticStops = new Set();
590
+ function spriteFor(symbolId, loops) {
591
+ const symbol = symbolsById.get(symbolId);
592
+ if (!symbol) return null;
593
+ if (symbol.button || loops === undefined || loops === !!symbol.loop) return spriteIds.get(symbolId);
594
+ const key = `${symbolId}:${loops}`;
595
+ if (!spriteVariants.has(key)) {
596
+ const id = allocate();
597
+ spriteVariants.set(key, id);
598
+ if (nativeControls) authoringVariants.push(['s', id, spriteIds.get(symbolId), Number(!!symbol.loop)]);
599
+ pendingSprites.push({ symbol, id, loops });
600
+ }
601
+ return spriteVariants.get(key);
602
+ }
603
+
604
+ /** Matrix for an element at `pose`, in its parent's coordinates (translation in twips). */
605
+ function placementMatrix(element, pose, parentOrigin) {
606
+ const { a, b, c, d } = matrixComponents(pose);
607
+ let m;
608
+ if (element.type === 'symbol') {
609
+ const definition = symbolsById.get(element.symbolId);
610
+ const sx = pose.width / (definition?.width || pose.width || 1), sy = pose.height / (definition?.height || pose.height || 1);
611
+ const origin = definition?.origin ?? { x: 0, y: 0 };
612
+ const lx = -sx * origin.x - pose.width / 2, ly = -sy * origin.y - pose.height / 2;
613
+ m = { a: a * sx, b: b * sx, c: c * sy, d: d * sy, tx: pose.x + a * lx + c * ly, ty: pose.y + b * lx + d * ly };
614
+ } else if (element.type === 'control') {
615
+ const sx = pose.width / element.width, sy = pose.height / element.height;
616
+ m = { a: a * sx, b: b * sx, c: c * sy, d: d * sy, tx: pose.x, ty: pose.y };
617
+ } else {
618
+ m = { a, b, c, d, tx: pose.x, ty: pose.y };
619
+ }
620
+ const r = value => Math.round(value * 1e6) / 1e6;
621
+ return { a: r(m.a), b: r(m.b), c: r(m.c), d: r(m.d), tx: Math.round((m.tx + parentOrigin.x) * 20), ty: Math.round((m.ty + parentOrigin.y) * 20) };
622
+ }
623
+
624
+ const buttonWrappers = new Map();
625
+ /** A clickable non-symbol element becomes a button whose states show its artwork. */
626
+ function wrapAsButton(characterId, actions) {
627
+ const key = `${characterId}:${JSON.stringify(actions)}`;
628
+ if (buttonWrappers.has(key)) return buttonWrappers.get(key);
629
+ const id = allocate();
630
+ const record = { characterId, depth: 1, matrix: { a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0 } };
631
+ characters[id] = { type: 'button', trackAsMenu: false, actions, buttonHitStates: [record], buttonStates: { up: [record], over: [record], down: [record] } };
632
+ buttonWrappers.set(key, id);
633
+ if (nativeControls) authoringVariants.push(['w', id, characterId]);
634
+ return id;
635
+ }
636
+
637
+ function transpiled(bytes, label) {
638
+ return transpileAvm1WithMeta(bytes, new DiagnosticsCollector(), {
639
+ timelineDeclarations: true, scopeLookup: true, sharedAvm1Runtime: true, nameSpellings: swfVersion >= 7 ? null : undefined, label,
640
+ }).js;
641
+ }
642
+
643
+ /** A Studio button action as a Flash button handler: `{ conditions, bytes, script }`. */
644
+ function buttonActionScript(action, timeline, timelineInfo) {
645
+ const bytes = action.type === 'script' ? bytecodeOf(scriptsById.get(action.script)) : typedActionBytes([action], timelineInfo);
646
+ if (!bytes) return null;
647
+ const conditions = {};
648
+ if (action.trigger === 'keyDown' || action.trigger === 'keyUp') {
649
+ // Flash key handlers fire on press; Studio's key-up bindings run then too.
650
+ const code = KEY_PRESS[action.key] ?? (action.key?.length === 1 ? action.key.toLowerCase().charCodeAt(0) : 0);
651
+ if (!code) return null;
652
+ conditions.keyPress = code;
653
+ } else if (action.trigger === 'click' || action.trigger === undefined || action.trigger === 'touchTap') {
654
+ conditions.overDownToOverUp = true;
655
+ } else {
656
+ return null; // Swipes have no Flash equivalent.
657
+ }
658
+ return { conditions, bytes, script: transpiled(bytes, `studio_button_${timeline.id}`) };
659
+ }
660
+
661
+ // A control has a stable MovieClip identity. Each live placement receives its own
662
+ // parameters, value and listeners before the owning timeline's frame script runs.
663
+ async function controlCharacter(element, timeline, timelineInfo) {
664
+ const id = allocate();
665
+ const actions = [];
666
+ for (const event of timeline.events ?? []) {
667
+ if (event.source !== element.id) continue;
668
+ for (const action of event.actions) {
669
+ const bytes = action.type === 'script' ? bytecodeOf(scriptsById.get(action.script)) : typedActionBytes([action], timelineInfo);
670
+ if (bytes) actions.push({ conditions: { [event.trigger]: true },
671
+ ...(nativeControls ? { bytes } : { script: transpiled(bytes, `control_${id}_${actions.length}`) }) });
672
+ }
673
+ }
674
+ const parameters = element.parameters ?? {};
675
+ const assets = Object.create(null);
676
+ for (const path of [parameters.contentPath, parameters.icon]) {
677
+ if (!path) continue;
678
+ const asset = project.assets?.find(asset => asset.kind === 'image' && [asset.id, asset.name, asset.linkage].includes(path));
679
+ const bitmap = asset && await bitmapFor(asset.id);
680
+ if (bitmap) assets[path] = bitmap.id;
681
+ }
682
+ const bounds = { x: -element.width / 2, y: -element.height / 2, w: element.width, h: element.height };
683
+ characters[id] = { type: 'sprite', frameCount: 1, frames: [{ frameIndex: 0, places: [], removes: [] }], bounds, actions,
684
+ studioControl: { kind: element.control, parameters, variable: element.variable, assets } };
685
+ return id;
686
+ }
687
+
688
+ // Button symbols placed with their own Studio action get a copy carrying that handler.
689
+ const buttonVariants = [];
690
+
691
+ /**
692
+ * How a symbol instance plays and responds: its character, and clip actions for a start
693
+ * frame (Studio's firstFrame and single-frame mode) or a click action on a movie clip.
694
+ */
695
+ function symbolInstance(element, timeline, timelineInfo) {
696
+ const definition = symbolsById.get(element.symbolId);
697
+ if (!definition) return null;
698
+ const morph = morphVariants.get(element.symbolId);
699
+ if (morph && !element.buttonAction && !element.scriptEvents?.length && !element.component && !timeline.button) {
700
+ return { characterId: morph.id, ratio: morph.ratio, clipActions: [] };
701
+ }
702
+ const mode = element.symbolMode;
703
+ let characterId = spriteFor(element.symbolId, mode === 'loop' ? true : mode === 'once' ? false : undefined);
704
+ const clipActions = [];
705
+ const start = element.firstFrame ?? definition.startFrame ?? 1;
706
+ if (!definition.button && definition.durationFrames > 1 && (mode === 'single' || start !== 1)) {
707
+ clipActions.push({ eventFlags: CLIP_FLAGS.load, bytecode: new Uint8Array([...gotoFrame(start - 1), mode === 'single' ? 0x07 : 0x06, 0]) });
708
+ }
709
+ if (element.buttonAction) {
710
+ const action = buttonActionScript(element.buttonAction, timeline, timelineInfo);
711
+ if (!action) {
712
+ note('Swipe actions do not run in ActionScript preview');
713
+ } else if (definition.button) {
714
+ const id = allocate();
715
+ if (nativeControls) authoringVariants.push(['b', id, characterId]);
716
+ buttonVariants.push({ id, baseId: characterId, action: { conditions: action.conditions, script: action.script, bytes: action.bytes } });
717
+ characterId = id;
718
+ } else {
719
+ // Clip scripts run in the placed clip. Studio's navigation presets target the owning timeline.
720
+ const body = element.buttonAction.type === 'script' ? action.bytes
721
+ : new Uint8Array([...avm1Push('_parent'), 0x20, ...action.bytes.subarray(0, -1), 0]);
722
+ clipActions.push(action.conditions.keyPress
723
+ ? { eventFlags: CLIP_FLAGS.keyPress, keyCode: action.conditions.keyPress, bytecode: body }
724
+ : { eventFlags: CLIP_FLAGS.release, bytecode: body });
725
+ }
726
+ }
727
+ return { characterId, clipActions };
728
+ }
729
+
730
+ /**
731
+ * Convert one timeline. Returns display-list frames plus the script tags for the transpiler:
732
+ * `frameTags[i]` lists DoAction tags (and clip-action placements) for frame i.
733
+ */
734
+ async function convertTimeline(timeline, { origin = { x: 0, y: 0 }, frameOffset = 0, sceneStart, isRoot, loops = !!timeline.loop }) {
735
+ let automaticStop = false;
736
+ const visibleElements = orderedSceneElements(timeline, { includeHidden: false });
737
+ // Masks: Studio links targets to a mask by `maskId`, in any order; Flash masks a depth range
738
+ // (clipDepth). A mask stacked above its first target moves just below it; it clips up to its
739
+ // last target.
740
+ const targetsOf = new Map();
741
+ for (const element of visibleElements) {
742
+ if (element.maskId) targetsOf.set(element.maskId, [...(targetsOf.get(element.maskId) ?? []), element]);
743
+ }
744
+ const masks = new Map(visibleElements.filter(element => targetsOf.has(element.id)).map(element => [element.id, element]));
745
+ const firstTarget = new Map([...targetsOf].map(([id, targets]) => [id, visibleElements.indexOf(targets[0])]));
746
+ const inPlace = mask => visibleElements.indexOf(mask) < firstTarget.get(mask.id);
747
+ const elements = [];
748
+ for (const element of visibleElements) {
749
+ if (masks.has(element.id) && inPlace(element)) {
750
+ if (element.maskId) note('Masks that are themselves masked (the outer mask is ignored)');
751
+ elements.push(element);
752
+ continue;
753
+ }
754
+ if (masks.has(element.id)) continue;
755
+ // A target whose mask is on a hidden layer is hidden too, as in the editor.
756
+ if (element.maskId && !masks.has(element.maskId)) continue;
757
+ const mask = masks.get(element.maskId);
758
+ if (mask && !elements.includes(mask)) {
759
+ if (mask.maskId) note('Masks that are themselves masked (the outer mask is ignored)');
760
+ elements.push(mask);
761
+ }
762
+ elements.push(element);
763
+ }
764
+ // Depths follow Studio's stacking order. Imported objects keep their SWF depth (scripts use
765
+ // it) while the order allows; objects added or reordered in Studio take the next depth up.
766
+ const depthOf = new Map();
767
+ let below = 0, belowStored;
768
+ for (const element of elements) {
769
+ const stored = element.depth;
770
+ const depth = stored !== undefined && (stored > below || (stored === below && stored === belowStored)) ? stored : below + 1;
771
+ depthOf.set(element.id, depth);
772
+ below = depth;
773
+ belowStored = stored;
774
+ }
775
+ // Imported masks keep their SWF clip depth while the depths it covers are as imported: the
776
+ // mask and everything in its range keep their SWF depth and no object there belongs to
777
+ // another mask. That covers a mask that replaces another at the same depth (Flash animates
778
+ // masks that way) and symbol masks the editor cannot link; an object added or moved into the
779
+ // range falls back to the editor's links, so Preview never masks what the editor shows.
780
+ // A target linked to an earlier mask in the same slot (same depth and clip depth) counts as
781
+ // this mask's: the editor links a target to one mask, Flash swaps the shape at the depth.
782
+ const sameSlot = (mask, id) => {
783
+ const other = timeline.elements.find(item => item.id === id);
784
+ return other && other.depth === mask.depth && other.clipDepth === mask.clipDepth;
785
+ };
786
+ const asImported = (mask, clipDepth) => depthOf.get(mask.id) === mask.depth && elements.every(other => {
787
+ const depth = depthOf.get(other.id);
788
+ if (depth <= mask.depth || depth > clipDepth) return true;
789
+ return other.depth === depth && (!other.maskId || other.maskId === mask.id || sameSlot(mask, other.maskId));
790
+ });
791
+ const clipDepthOf = new Map();
792
+ for (const element of elements) {
793
+ const targets = targetsOf.get(element.id);
794
+ const last = targets ? depthOf.get(targets.at(-1).id) : 0;
795
+ const kept = element.clipDepth !== undefined && asImported(element, element.clipDepth) ? element.clipDepth : 0;
796
+ if (last || kept) clipDepthOf.set(element.id, Math.max(last, kept));
797
+ }
798
+ const shown = element => new Set(Array.from({ length: timeline.durationFrames }, (_, i) => i + 1).filter(frame => visibleAt(element, frame)));
799
+ for (const [id, mask] of masks) {
800
+ const from = elements.indexOf(mask), to = elements.indexOf(targetsOf.get(id).at(-1));
801
+ const between = elements.slice(from + 1, to).filter(element => element.maskId !== id);
802
+ if (!between.length) continue;
803
+ const frames = shown(mask);
804
+ if (between.some(element => [...shown(element)].some(frame => frames.has(frame)))) note('Objects stacked between masked objects are masked too');
805
+ }
806
+ const nameOf = element => IDENTIFIER.test(element.name) ? element.name : undefined;
807
+ const timelineInfo = {
808
+ frameIndex: target => frameOffset + target - 1,
809
+ sceneStart,
810
+ sceneTransition,
811
+ objectPath: id => {
812
+ const element = timeline.elements.find(item => item.id === id);
813
+ return element && nameOf(element);
814
+ },
815
+ };
816
+ const frames = [];
817
+ const frameTags = [];
818
+ const current = new Map(); // depth → { characterId, matrixKey, ctKey, elementId }
819
+ const instances = new Map(); // element id → symbolInstance()
820
+ const artworkActions = new Map(); // element id → button handler for drawn objects
821
+ for (let frame = 1; frame <= timeline.durationFrames; frame++) {
822
+ const places = [];
823
+ const removes = [];
824
+ const tags = [];
825
+ const present = new Set();
826
+ for (const element of elements) {
827
+ if (!visibleAt(element, frame)) continue;
828
+ const keyStart = (element.keyframes[0]?.frame ?? 1);
829
+ if (frame < keyStart) continue;
830
+ const depth = depthOf.get(element.id);
831
+ const pose = poseAt(element, frame, element.keyframes);
832
+ let characterId;
833
+ let instance = null;
834
+ if (element.type === 'symbol') {
835
+ if (!instances.has(element.id)) instances.set(element.id, symbolInstance(element, timeline, timelineInfo));
836
+ instance = instances.get(element.id);
837
+ characterId = instance?.characterId;
838
+ } else if (element.type === 'control') {
839
+ if (!instances.has(element.id)) instances.set(element.id, await controlCharacter(element, timeline, timelineInfo));
840
+ characterId = instances.get(element.id);
841
+ } else {
842
+ characterId = await artworkCharacter(element, pose);
843
+ }
844
+ if (!characterId) continue;
845
+ if (element.buttonAction && element.type !== 'symbol' && element.type !== 'control') {
846
+ if (!artworkActions.has(element.id)) artworkActions.set(element.id, buttonActionScript(element.buttonAction, timeline, timelineInfo));
847
+ const action = artworkActions.get(element.id);
848
+ if (action) characterId = wrapAsButton(characterId, [{ conditions: action.conditions, script: action.script, bytes: action.bytes }]);
849
+ else note('Swipe actions do not run in ActionScript preview');
850
+ }
851
+ present.add(depth);
852
+ const matrix = placementMatrix(element, pose, origin);
853
+ const alpha = Math.max(0, Math.min(1, pose.opacity ?? 1));
854
+ const tint = pose.colorTransform;
855
+ // Masks clip by shape only; their color and opacity do not apply.
856
+ const colorTransform = !clipDepthOf.has(element.id) && (alpha < 1 || tint) ? {
857
+ rMult: Math.round((tint?.redMultiplier ?? 1) * 256), gMult: Math.round((tint?.greenMultiplier ?? 1) * 256),
858
+ bMult: Math.round((tint?.blueMultiplier ?? 1) * 256), aMult: Math.round(alpha * 256),
859
+ rAdd: Math.round(tint?.redOffset ?? 0), gAdd: Math.round(tint?.greenOffset ?? 0), bAdd: Math.round(tint?.blueOffset ?? 0), aAdd: 0,
860
+ } : undefined;
861
+ const filters = placementFilters(pose);
862
+ const blendMode = pose.blendMode ?? 1;
863
+ const fxKey = JSON.stringify([filters, blendMode]);
864
+ const previous = current.get(depth);
865
+ const matrixKey = JSON.stringify(matrix), ctKey = JSON.stringify(colorTransform ?? null);
866
+ const ratio = instance?.ratio;
867
+ const name = nameOf(element), clipDepth = clipDepthOf.get(element.id);
868
+ if (previous && (previous.elementId === element.id || (ratio != null && previous.characterId === characterId &&
869
+ previous.name === name && previous.clipDepth === clipDepth))) {
870
+ if (previous.characterId === characterId && previous.matrixKey === matrixKey && previous.ctKey === ctKey && previous.fxKey === fxKey && previous.ratio === ratio) continue;
871
+ const place = { depth, move: true, matrix };
872
+ if (previous.characterId !== characterId) place.characterId = characterId;
873
+ if (ratio != null && previous.ratio !== ratio) place.ratio = ratio;
874
+ place.colorTransform = colorTransform ?? { rMult: 256, gMult: 256, bMult: 256, aMult: 256, rAdd: 0, gAdd: 0, bAdd: 0, aAdd: 0 };
875
+ if (previous.fxKey !== fxKey) Object.assign(place, { filters, blendMode });
876
+ places.push(place);
877
+ current.set(depth, { ...previous, elementId: element.id, characterId, matrixKey, ctKey, fxKey, ratio });
878
+ continue;
879
+ }
880
+ if (previous) places.push({ depth, remove: true });
881
+ const place = { depth, move: false, characterId, matrix };
882
+ if (clipDepthOf.has(element.id)) place.clipDepth = clipDepthOf.get(element.id);
883
+ if (ratio != null) place.ratio = ratio;
884
+ if (name) place.name = name;
885
+ if (colorTransform) place.colorTransform = colorTransform;
886
+ if (filters.length) place.filters = filters;
887
+ if (blendMode !== 1) place.blendMode = blendMode;
888
+ places.push(place);
889
+ current.set(depth, { elementId: element.id, characterId, matrixKey, ctKey, fxKey, name, clipDepth, ratio });
890
+ // A component's parameters run first, as Flash's generated handler did (controls.md §1.4).
891
+ const parameters = element.component && CLIP_FLAGS[element.component.event]
892
+ ? [{ eventFlags: CLIP_FLAGS[element.component.event], bytecode: encodeComponentParameters(element.component.parameters) }] : [];
893
+ const clipActions = [...parameters, ...(instance?.clipActions ?? []), ...(element.scriptEvents ?? []).map(event => {
894
+ const script = scriptsById.get(event.script);
895
+ const eventFlags = event.on.reduce((flags, name) => flags | (CLIP_FLAGS[name] ?? 0), 0);
896
+ return script && eventFlags ? { eventFlags, ...(event.key ? { keyCode: event.key } : {}), bytecode: bytecodeOf(script) } : null;
897
+ }).filter(Boolean)];
898
+ if (clipActions.length) tags.push({ type: 'PlaceObject2', depth, characterId, clipActions, name });
899
+ }
900
+ for (const depth of [...current.keys()]) {
901
+ if (present.has(depth)) continue;
902
+ if (places.length) places.push({ depth, remove: true }); else removes.push(depth);
903
+ current.delete(depth);
904
+ }
905
+ const entry = { frameIndex: frame - 1, places, removes };
906
+ const cues = await clipSounds(timeline, frame);
907
+ if (cues.length) entry.sounds = cues;
908
+ const labels = (timeline.labels ?? []).filter(item => item.frame === frame).map(item => item.name);
909
+ if (labels.length) {
910
+ entry.label = labels.at(-1);
911
+ if (labels.length > 1) entry.labels = labels;
912
+ }
913
+ // Frame events: scripts run as written; typed actions become small AVM1 blocks, in order.
914
+ const event = timeline.events?.find(item => item.frame === frame && item.trigger === 'frameEnter');
915
+ const actions = [...(frame === 1 ? timeline.events?.filter(item => item.trigger === 'timelineStart').flatMap(item => item.actions) ?? [] : []),
916
+ ...(event?.actions ?? [])];
917
+ let typed = [];
918
+ const flushTyped = () => {
919
+ const bytes = typedActionBytes(typed, timelineInfo);
920
+ if (bytes) tags.push({ type: 'DoAction', bytecode: bytes });
921
+ typed = [];
922
+ };
923
+ for (const action of actions) {
924
+ if (action.type === 'script') {
925
+ flushTyped();
926
+ const script = scriptsById.get(action.script);
927
+ if (script) tags.push(...frameActionTags(script, { type: 'DoAction' }));
928
+ } else {
929
+ typed.push(action);
930
+ }
931
+ }
932
+ flushTyped();
933
+ // Studio timelines stop at their last frame unless they loop (Flash would continue).
934
+ if (frame === timeline.durationFrames && !isRoot && !usesAvm2) {
935
+ const jumps = actions.some(action => ['stop', 'gotoFrame', 'gotoScene', 'script'].includes(action.type));
936
+ if (!jumps && !loops && timeline.durationFrames > 1) {
937
+ tags.push({ type: 'DoAction', bytecode: new Uint8Array([0x07, 0]) });
938
+ automaticStop = true;
939
+ }
940
+ }
941
+ frames.push(entry);
942
+ frameTags.push(tags);
943
+ }
944
+ return { frames, frameTags, automaticStop };
945
+ }
946
+
947
+ // Symbols → sprite (or button) characters with their own frame scripts.
948
+ const spriteTags = [];
949
+ const mergedParts = new Set();
950
+ const scriptedInstances = new Set([...project.scenes, ...(project.symbols ?? [])].flatMap(timeline =>
951
+ timeline.elements.filter(e => e.type === 'symbol' && (e.scriptEvents?.length || e.buttonAction || e.component ||
952
+ timeline.events?.some(event => event.source === e.id))).map(e => e.symbolId)));
953
+ async function convertSymbol({ symbol, id, loops }) {
954
+ const morph = morphVariants.get(symbol.id);
955
+ if (morph) {
956
+ characters[id] = { type: 'sprite', frameCount: 1, frames: [{ frameIndex: 0, removes: [],
957
+ places: [{ depth: 1, characterId: morph.id, ratio: morph.ratio }] }] };
958
+ return;
959
+ }
960
+ const origin = symbol.origin ?? { x: 0, y: 0 };
961
+ const { frames, frameTags, automaticStop } = await convertTimeline(symbol, { origin, sceneStart: () => null, isRoot: false, loops });
962
+ if (symbol.compoundShape && frames.length === 1 && !symbol.button && !symbol.scalingGrid && !symbol.linkage &&
963
+ !symbol.audioClips?.length && !symbol.events?.length && !symbol.avm2?.length && !symbol.scriptEvents?.length &&
964
+ !symbol.initScript && !scriptedInstances.has(symbol.id) && !nativeLibrary?.ids.has(symbol.id) &&
965
+ symbol.elements.every(e => !e.buttonAction && !e.scriptEvents?.length && !e.maskId)) {
966
+ const draws = compoundDraws(frames[0].places, characters);
967
+ if (draws) {
968
+ for (const place of frames[0].places) mergedParts.add(place.characterId);
969
+ characters[id] = { type: 'shape', draws, bounds: drawsBounds(draws) };
970
+ return;
971
+ }
972
+ }
973
+ if (automaticStop) automaticStops.add(id);
974
+ if (symbol.button) {
975
+ const records = index => (frames.slice(0, index + 1).reduce((display, frame) => {
976
+ for (const depth of frame.removes) display.delete(depth);
977
+ for (const place of frame.places) {
978
+ if (place.remove) display.delete(place.depth);
979
+ else display.set(place.depth, { ...display.get(place.depth), ...place });
980
+ }
981
+ return display;
982
+ }, new Map()));
983
+ const state = index => [...records(index).values()].map(place => ({
984
+ characterId: place.characterId, depth: place.depth, matrix: place.matrix,
985
+ ...(place.filters?.length && { filters: place.filters }), ...(place.blendMode && { blendMode: place.blendMode }),
986
+ colorTransform: place.colorTransform ?? { rMult: 256, gMult: 256, bMult: 256, aMult: 256, rAdd: 0, gAdd: 0, bAdd: 0, aAdd: 0 },
987
+ })).sort((a, b) => a.depth - b.depth);
988
+ const actions = (symbol.scriptEvents ?? []).map((event, index) => {
989
+ const script = scriptsById.get(event.script);
990
+ if (!script) return null;
991
+ const conditions = {};
992
+ for (const name of event.on) if (BUTTON_CONDITIONS[name]) conditions[BUTTON_CONDITIONS[name]] = true;
993
+ if (event.on.includes('keyPress')) conditions.keyPress = event.key ?? 0;
994
+ // Bytes beside the transpiled script: SWF export writes them as they are.
995
+ const bytes = bytecodeOf(script);
996
+ return { conditions, bytes, script: transpiled(bytes, `button_${id}_action_${index}`) };
997
+ }).filter(Boolean);
998
+ const last = Math.min(3, frames.length - 1);
999
+ const buttonSounds = {};
1000
+ for (const [transition, cue] of Object.entries(symbol.buttonSounds ?? {})) {
1001
+ const sound = await soundFor(cue.assetId);
1002
+ if (sound) buttonSounds[transition] = { soundId: sound.id, soundInfo: cue.soundInfo };
1003
+ }
1004
+ characters[id] = { type: 'button', trackAsMenu: !!symbol.trackAsMenu, actions,
1005
+ ...(symbol.scalingGrid && { scalingGrid: symbol.scalingGrid }),
1006
+ ...(Object.keys(buttonSounds).length ? { buttonSounds } : {}),
1007
+ buttonStates: { up: state(0), over: state(Math.min(1, last)), down: state(Math.min(2, last)) }, buttonHitStates: state(last) };
1008
+ return;
1009
+ }
1010
+ characters[id] = { type: 'sprite', ...(symbol.scalingGrid && { scalingGrid: symbol.scalingGrid }),
1011
+ frameCount: frames.length, hasStream: await attachStreams(symbol, 0, id), frames, tagStreamBytes: 0 };
1012
+ const raw = [];
1013
+ frameTags.forEach(tags => {
1014
+ for (const tag of tags) {
1015
+ if (tag.code === 253) raw.push(tag);
1016
+ else if (tag.type === 'DoAction') raw.push({ code: TAG.DoAction, data: tag.bytecode });
1017
+ else raw.push({ code: TAG.PlaceObject2, data: new Uint8Array(0), decoded: tag });
1018
+ }
1019
+ raw.push({ code: TAG.ShowFrame, data: new Uint8Array(0) });
1020
+ });
1021
+ if (raw.some(tag => tag.code !== TAG.ShowFrame)) spriteTags.push({ type: 'Sprite', characterId: id, tags: raw });
1022
+ }
1023
+
1024
+ // Converting a timeline can ask for more sprite copies; convert until none are left.
1025
+ const drainSprites = async () => {
1026
+ while (pendingSprites.length) await convertSymbol(pendingSprites.shift());
1027
+ };
1028
+ await drainSprites();
1029
+
1030
+ // Scenes play one after another on the root timeline, as in a SWF.
1031
+ const scenes = [];
1032
+ let offset = 0;
1033
+ for (const scene of project.scenes) {
1034
+ scenes.push({ name: scene.name, offset, numFrames: scene.durationFrames });
1035
+ offset += scene.durationFrames;
1036
+ }
1037
+ const sceneStart = id => scenes[project.scenes.findIndex(scene => scene.id === id)]?.offset ?? null;
1038
+ const rootFrames = [];
1039
+ const rootTagFrames = [];
1040
+ for (const [index, scene] of project.scenes.entries()) {
1041
+ const { frames, frameTags } = await convertTimeline(scene, { frameOffset: scenes[index].offset, sceneStart, isRoot: true });
1042
+ await attachStreams(scene, scenes[index].offset);
1043
+ // A scene starts with a fresh stage: clear what the previous scene left.
1044
+ if (index > 0 && rootFrames.length) {
1045
+ const live = new Set();
1046
+ for (const frame of rootFrames) {
1047
+ for (const depth of frame.removes) live.delete(depth);
1048
+ for (const place of frame.places) place.remove ? live.delete(place.depth) : live.add(place.depth);
1049
+ }
1050
+ frames[0].places.unshift(...[...live].map(depth => ({ depth, remove: true })));
1051
+ }
1052
+ const lastIndex = frames.length - 1;
1053
+ frames.forEach((frame, i) => {
1054
+ frame.frameIndex = scenes[index].offset + i;
1055
+ rootFrames.push(frame);
1056
+ const rootTags = frameTags[i];
1057
+ rootTagFrames.push(rootTags);
1058
+ // Studio scenes stop at their end unless they loop or jump.
1059
+ if (i === lastIndex && !usesAvm2) {
1060
+ const event = scene.events?.find(item => item.frame === i + 1);
1061
+ const jumps = event?.actions.some(action => ['stop', 'gotoFrame', 'gotoScene', 'script'].includes(action.type));
1062
+ if (!jumps) {
1063
+ if (scene.loop && frames.length > 1) rootTags.push({ type: 'DoAction', bytecode: new Uint8Array([...gotoFrame(scenes[index].offset), 0x06, 0]) });
1064
+ else if (!scene.loop) rootTags.push({ type: 'DoAction', bytecode: new Uint8Array([0x07, 0]) });
1065
+ }
1066
+ }
1067
+ rootTags.push({ type: 'ShowFrame' });
1068
+ });
1069
+ }
1070
+
1071
+ if (transitionCalls.size && rootTagFrames.length) {
1072
+ // Defined before any frame action or button can jump (swf-transition-runtime.as).
1073
+ const source = await readFile(new URL('./swf-transition-runtime.as', import.meta.url), 'utf8');
1074
+ rootTagFrames[0].unshift({ type: 'DoAction', bytecode: compileActionScript(source, { swfVersion: 8 }) });
1075
+ }
1076
+
1077
+ await drainSprites();
1078
+ for (const { id, baseId, action } of buttonVariants) {
1079
+ const base = characters[baseId];
1080
+ if (base) characters[id] = { ...base, actions: [...(base.actions ?? []), action] };
1081
+ }
1082
+ if (mergedParts.size) {
1083
+ // Shared parts can also be placed directly in a different clip or button.
1084
+ for (const frames of [rootFrames, ...Object.values(characters).map(character => character.frames ?? [])]) {
1085
+ for (const frame of frames) for (const place of frame.places) mergedParts.delete(place.characterId);
1086
+ }
1087
+ for (const character of Object.values(characters)) {
1088
+ for (const records of [...Object.values(character.buttonStates ?? {}), character.buttonHitStates ?? []]) {
1089
+ for (const record of records) mergedParts.delete(record.characterId);
1090
+ }
1091
+ }
1092
+ for (const id of mergedParts) delete characters[id];
1093
+ }
1094
+ const exports = (project.symbols ?? []).filter(symbol => symbol.linkage).map(symbol => ({ id: spriteIds.get(symbol.id), name: symbol.linkage }));
1095
+ for (const asset of project.assets ?? []) {
1096
+ if (asset.kind !== 'audio' || !asset.linkage) continue;
1097
+ const sound = await soundFor(asset.id);
1098
+ if (sound) exports.push({ id: sound.id, name: asset.linkage });
1099
+ }
1100
+ // A later frame may introduce or replace a component class. Preserve initialization
1101
+ // order within each source frame, including classes no instance has placed yet.
1102
+ const initializers = new Map();
1103
+ for (const symbol of project.symbols ?? []) {
1104
+ const script = scriptsById.get(symbol.initScript);
1105
+ if (!script) continue;
1106
+ const frame = symbol.initAt ? sceneStart(symbol.initAt.scene) + symbol.initAt.frame - 1 : 0;
1107
+ if (!initializers.has(frame)) initializers.set(frame, []);
1108
+ initializers.get(frame).push(...frameActionTags(script, { type: 'DoInitAction', spriteId: spriteIds.get(symbol.id) }));
1109
+ }
1110
+ const rootTags = [...spriteTags];
1111
+ if (exports.length) rootTags.push({ type: 'ExportAssets', assets: exports });
1112
+ const avm2Frames = new Map();
1113
+ async function appendAvm2(timeline, offset) {
1114
+ for (const record of timeline.avm2 ?? []) {
1115
+ if (record.library) continue;
1116
+ // Library declarations become available from the host movie's first frame.
1117
+ const frame = offset == null ? 0 : offset + record.frame - 1;
1118
+ if (!avm2Frames.has(frame)) avm2Frames.set(frame, []);
1119
+ const target = avm2Frames.get(frame);
1120
+ if (record.script) {
1121
+ const script = scriptsById.get(record.script);
1122
+ target.push({ type: 'DoABC', flags: script.flags, name: script.abcName, legacy: script.legacy, abcData: bytecodeOf(script) });
1123
+ continue;
1124
+ }
1125
+ const classes = [];
1126
+ for (const binding of record.classes) {
1127
+ let id;
1128
+ if (binding.document) id = 0;
1129
+ else if (binding.native) id = binding.native;
1130
+ else if (binding.symbol) id = spriteIds.get(binding.symbol);
1131
+ else if (binding.binary !== undefined) {
1132
+ id = allocate();
1133
+ rootTags.push({ type: 'DefineBinaryData', characterId: id, rawData: Buffer.from(binding.binary, 'base64') });
1134
+ } else {
1135
+ const asset = project.assets?.find(item => item.id === binding.asset);
1136
+ if (asset) id = (asset.kind === 'image' ? await bitmapFor(asset.id) : await soundFor(asset.id))?.id;
1137
+ }
1138
+ if (id !== undefined) classes.push({ id, name: binding.name });
1139
+ else note(`Missing artwork for ActionScript 3 class ${binding.name}`);
1140
+ }
1141
+ if (classes.length) target.push({ type: 'SymbolClass', classes });
1142
+ }
1143
+ }
1144
+ for (const symbol of project.symbols ?? []) await appendAvm2(symbol, null);
1145
+ for (const [index, scene] of project.scenes.entries()) await appendAvm2(scene, scenes[index].offset);
1146
+ rootTagFrames.forEach((tags, i) => {
1147
+ for (const tag of avm2Frames.get(i) ?? []) rootTags.push(tag);
1148
+ for (const tag of initializers.get(i) ?? []) rootTags.push(tag);
1149
+ for (const tag of tags) rootTags.push(tag);
1150
+ });
1151
+
1152
+ const header = {
1153
+ version: swfVersion, frameRate: project.stage.frameRate, frameCount: rootFrames.length, fileLength: nativeLibrary?.sourceLength ?? 0,
1154
+ frameSize: { xMin: 0, yMin: 0, xMax: project.stage.width * 20, yMax: project.stage.height * 20 },
1155
+ };
1156
+ return {
1157
+ header, tags: rootTags, displayList: { frames: rootFrames, characters, scenes },
1158
+ transitionsWritten,
1159
+ ...(nativeControls && { authoringVariants: authoringVariants.map(row => row[0] === 's'
1160
+ ? [...row, Number(automaticStops.has(row[2]))] : row) }),
1161
+ assetManifest, files, backgroundColor: project.stage.background, report, nativeLibrary,
1162
+ ...(streamAudio === 'native' && { eventSoundIds: new Set([...eventSoundAssets].map(id => sounds.get(id)?.id)) }),
1163
+ };
1164
+ }