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,897 @@
1
+ /**
2
+ * @fileoverview ActionScript tree → AVM1 bytecode (studiospec/actionscript.md §4).
3
+ *
4
+ * The output follows what Flash's own compiler writes, so the transpiler and Flash Player read it
5
+ * the same way: global functions such as `stop()`, `gotoAndPlay()` and `getURL()` become their
6
+ * actions, bare clip properties (`_x`) become GetProperty/SetProperty on the current clip, named
7
+ * functions are defined first, and `&&`/`||` keep the deciding value on the stack.
8
+ *
9
+ * Code is laid out as a flat list of items (actions, labels, jumps, and sized actions such as
10
+ * DefineFunction whose header records the length of the code after it), then assembled in two
11
+ * passes: offsets, then bytes.
12
+ */
13
+ import { OP } from '../transpiler/avm1/avm1-opcodes.js';
14
+ import { CompileError } from './as2-parser.js';
15
+
16
+ /** Clip properties by GetProperty index. */
17
+ export const CLIP_PROPERTIES = ['_x', '_y', '_xscale', '_yscale', '_currentframe', '_totalframes', '_alpha', '_visible',
18
+ '_width', '_height', '_rotation', '_target', '_framesloaded', '_name', '_droptarget', '_url', '_highquality',
19
+ '_focusrect', '_soundbuftime', '_quality', '_xmouse', '_ymouse'];
20
+
21
+ /** Actions that need a later SWF version than 5. */
22
+ const MINIMUM_VERSION = {
23
+ [OP.StrictEquals]: 6, [OP.Greater]: 6, [OP.InstanceOf]: 6, [OP.Enumerate2]: 6,
24
+ [OP.Try]: 7, [OP.Throw]: 7,
25
+ };
26
+
27
+ const SCRATCH = 0; // Register for a value read back right away (assignment results, for…in names).
28
+ const SWITCH = 3; // Register holding a switch's value while its cases are tested.
29
+ const ARGUMENTS = 1; // DefineFunction2 preloads `arguments` here (the first preload register).
30
+ const PRELOAD_ARGUMENTS = 0x04;
31
+
32
+ const BINARY_OPS = {
33
+ '+': [OP.Add2], '-': [OP.Subtract], '*': [OP.Multiply], '/': [OP.Divide], '%': [OP.Modulo],
34
+ '==': [OP.Equals2], '!=': [OP.Equals2, OP.Not], '===': [OP.StrictEquals], '!==': [OP.StrictEquals, OP.Not],
35
+ '<': [OP.LessThan2], '>': [OP.Greater], '<=': [OP.Greater, OP.Not], '>=': [OP.LessThan2, OP.Not],
36
+ '&': [OP.BitAnd], '|': [OP.BitOr], '^': [OP.BitXor], '<<': [OP.BitLShift], '>>': [OP.BitRShift], '>>>': [OP.BitURShift],
37
+ instanceof: [OP.InstanceOf],
38
+ };
39
+
40
+ class Assembler {
41
+ constructor(version) {
42
+ this.items = [];
43
+ this.labels = 0;
44
+ this.version = version;
45
+ this.encoder = new TextEncoder();
46
+ }
47
+
48
+ label() { return `L${++this.labels}`; }
49
+ place(label) { this.items.push({ label }); }
50
+ op(code, data) { this.items.push({ code, data }); }
51
+ jump(label) { this.items.push({ jump: OP.Jump, to: label }); }
52
+ /** If: pops a value and jumps when it is true. */
53
+ branch(label) { this.items.push({ jump: OP.If, to: label }); }
54
+ push(...values) { this.items.push({ push: values }); }
55
+ /** An action whose payload depends on label offsets (sizes of the code that follows it). */
56
+ sized(code, length, build) { this.items.push({ code, length, build }); }
57
+
58
+ string(text) {
59
+ if (this.version >= 6) return [...this.encoder.encode(text), 0];
60
+ return [...[...text].map(char => char.charCodeAt(0) < 256 ? char.charCodeAt(0) : 0x3f), 0];
61
+ }
62
+
63
+ pushValueBytes(value) {
64
+ switch (value.type) {
65
+ case 'string': {
66
+ const index = this.pool?.get(value.value);
67
+ if (index !== undefined) return index < 256 ? [8, index] : [9, index & 0xff, index >> 8];
68
+ return [0, ...this.string(value.value)];
69
+ }
70
+ case 'null': return [2];
71
+ case 'undefined': return [3];
72
+ case 'register': return [4, value.value];
73
+ case 'boolean': return [5, value.value ? 1 : 0];
74
+ case 'number': {
75
+ const n = value.value;
76
+ if (Number.isInteger(n) && n >= -0x80000000 && n <= 0x7fffffff && !Object.is(n, -0)) {
77
+ return [7, n & 0xff, (n >> 8) & 0xff, (n >> 16) & 0xff, (n >>> 24) & 0xff];
78
+ }
79
+ const bytes = new Uint8Array(new Float64Array([n]).buffer);
80
+ // AVM1 stores the two 32-bit halves of a double in reverse order.
81
+ return [6, ...bytes.slice(4, 8), ...bytes.slice(0, 4)];
82
+ }
83
+ default: throw new Error(`Unknown push value ${value.type}`);
84
+ }
85
+ }
86
+
87
+ assemble() {
88
+ // Merge consecutive pushes into one action, as Flash does.
89
+ const items = [];
90
+ for (const item of this.items) {
91
+ const last = items.at(-1);
92
+ if (item.push && last?.push) last.push = [...last.push, ...item.push];
93
+ else items.push(item.push ? { push: [...item.push] } : item);
94
+ }
95
+ // A constant pool, as Flash writes one: the most used strings, while the action stays under
96
+ // 64 KB. Functions keep the pool that was current where they were defined.
97
+ const uses = new Map();
98
+ for (const item of items) for (const value of item.push ?? []) if (value.type === 'string') uses.set(value.value, (uses.get(value.value) ?? 0) + 1);
99
+ const pooled = [...uses].filter(([, count]) => count > 1).sort((a, b) => b[1] - a[1]).map(([text]) => text);
100
+ this.pool = new Map();
101
+ let poolBytes = 2;
102
+ for (const text of pooled) {
103
+ const size = this.string(text).length;
104
+ if (this.pool.size >= 65535 || poolBytes + size > 65535) break;
105
+ this.pool.set(text, this.pool.size);
106
+ poolBytes += size;
107
+ }
108
+ if (this.pool.size) {
109
+ items.unshift({ code: OP.ConstantPool, data: [this.pool.size & 0xff, this.pool.size >> 8, ...[...this.pool.keys()].flatMap(text => this.string(text))] });
110
+ }
111
+ for (const item of items) {
112
+ if (item.push) item.data = item.push.flatMap(value => this.pushValueBytes(value));
113
+ }
114
+ const size = item => item.label !== undefined ? 0
115
+ : item.jump ? 5
116
+ : item.push ? 3 + item.data.length
117
+ : item.build ? 3 + item.length
118
+ : item.code >= 0x80 ? 3 + (item.data?.length ?? 0) : 1;
119
+ const offsets = new Map();
120
+ let offset = 0;
121
+ for (const item of items) {
122
+ if (item.label !== undefined) offsets.set(item.label, offset);
123
+ item.offset = offset;
124
+ offset += size(item);
125
+ }
126
+ const offsetOf = label => {
127
+ if (!offsets.has(label)) throw new Error(`Unplaced label ${label}`);
128
+ return offsets.get(label);
129
+ };
130
+ const out = [];
131
+ const ui16 = value => [value & 0xff, (value >> 8) & 0xff];
132
+ for (const item of items) {
133
+ if (item.label !== undefined) continue;
134
+ const after = item.offset + size(item);
135
+ if (item.jump) {
136
+ const delta = offsetOf(item.to) - after;
137
+ if (delta < -32768 || delta > 32767) throw new CompileError('Script too long: a jump is more than 32 KB');
138
+ out.push(item.jump, 2, 0, ...ui16(delta & 0xffff));
139
+ continue;
140
+ }
141
+ const code = item.push ? OP.Push : item.code;
142
+ const data = item.build ? item.build(offsetOf, after) : item.data ?? [];
143
+ if (item.build && data.length !== item.length) throw new Error('Sized action length changed');
144
+ out.push(code);
145
+ if (code >= 0x80) out.push(...ui16(data.length), ...data);
146
+ }
147
+ return out;
148
+ }
149
+ }
150
+
151
+ /**
152
+ * Compile a parsed Program. Options: `swfVersion` (default 8); `scenes`: scene name → frame offset
153
+ * for `gotoAndPlay("Scene", frame)`.
154
+ */
155
+ export function generate(program, { swfVersion = 8, scenes = null } = {}) {
156
+ const asm = new Assembler(swfVersion);
157
+ const fail = (message, node) => { throw new CompileError(message, node?.line, node?.column); };
158
+ // Break/continue targets, innermost last: { kind, labels, breakTo, continueTo }.
159
+ let targets = [];
160
+ let inFunction = false;
161
+ let argumentsRegister = false; // In a DefineFunction2 that preloads `arguments`.
162
+ let superRegister = 0;
163
+
164
+ const op = (code, node) => {
165
+ const minimum = MINIMUM_VERSION[code];
166
+ if (minimum && swfVersion < minimum) fail(`This needs SWF ${minimum} or later (the script is SWF ${swfVersion})`, node);
167
+ asm.op(code);
168
+ };
169
+ const str = value => ({ type: 'string', value: String(value) });
170
+ const num = value => ({ type: 'number', value });
171
+ const UNDEFINED = { type: 'undefined' };
172
+ const pushLiteral = value => {
173
+ if (value === null) asm.push({ type: 'null' });
174
+ else if (value === undefined) asm.push(UNDEFINED);
175
+ else if (typeof value === 'boolean') asm.push({ type: 'boolean', value });
176
+ else if (typeof value === 'number') asm.push(num(value));
177
+ else asm.push(str(value));
178
+ };
179
+
180
+ // ---- Statements ----
181
+
182
+ function body(statements) {
183
+ // Named functions are defined before the rest of the block, as in Flash.
184
+ for (const statement of statements) if (statement.type === 'FunctionDeclaration') functionDefinition(statement);
185
+ for (const statement of statements) if (statement.type !== 'FunctionDeclaration') emitStatement(statement);
186
+ }
187
+
188
+ function findTarget(node, label, forContinue) {
189
+ for (let i = targets.length - 1; i >= 0; i--) {
190
+ const target = targets[i];
191
+ if (target.kind === 'try' || target.kind === 'with') {
192
+ fail(`${forContinue ? 'continue' : 'break'} cannot leave a ${target.kind} block yet`, node);
193
+ }
194
+ if (target.kind === 'function') break;
195
+ const matches = label ? target.labels.includes(label) : (forContinue ? target.continueTo : target.kind !== 'block');
196
+ if (!matches) continue;
197
+ if (forContinue && !target.continueTo) fail(`continue ${label} does not name a loop`, node);
198
+ return target;
199
+ }
200
+ fail(label ? `Unknown label ${label}` : `${forContinue ? 'continue' : 'break'} outside a loop`, node);
201
+ }
202
+
203
+ function loop(labels, emit) {
204
+ const breakTo = asm.label(), continueTo = asm.label();
205
+ const target = { kind: 'loop', labels, breakTo, continueTo };
206
+ targets.push(target);
207
+ emit(target);
208
+ targets.pop();
209
+ }
210
+
211
+ function emitStatement(node, labels = []) {
212
+ switch (node.type) {
213
+ case 'EmptyStatement': return;
214
+ case 'BlockStatement': body(node.body); return;
215
+ case 'ExpressionStatement': discard(node.expression); return;
216
+ case 'FunctionDeclaration': functionDefinition(node); return;
217
+ case 'VariableDeclaration':
218
+ for (const declaration of node.declarations) {
219
+ asm.push(str(declaration.id.name));
220
+ if (declaration.init) { value(declaration.init); asm.op(OP.DefineLocal); } else asm.op(OP.DefineLocal2);
221
+ }
222
+ return;
223
+ case 'LabeledStatement': {
224
+ const all = [...labels, node.label];
225
+ if (['WhileStatement', 'DoWhileStatement', 'ForStatement', 'ForInStatement', 'LabeledStatement'].includes(node.body.type)) {
226
+ emitStatement(node.body, all);
227
+ return;
228
+ }
229
+ const breakTo = asm.label();
230
+ targets.push({ kind: 'block', labels: all, breakTo });
231
+ emitStatement(node.body);
232
+ targets.pop();
233
+ asm.place(breakTo);
234
+ return;
235
+ }
236
+ case 'IfStatement': {
237
+ const otherwise = asm.label(), end = asm.label();
238
+ condition(node.test);
239
+ asm.op(OP.Not);
240
+ asm.branch(node.alternate ? otherwise : end);
241
+ emitStatement(node.consequent);
242
+ if (node.alternate) {
243
+ asm.jump(end);
244
+ asm.place(otherwise);
245
+ emitStatement(node.alternate);
246
+ }
247
+ asm.place(end);
248
+ return;
249
+ }
250
+ case 'IfFrameLoadedStatement': {
251
+ let bias = 0;
252
+ if (node.scene) {
253
+ const scene = literal(node.scene);
254
+ if (typeof scene !== 'string' || !scenes || !(scene in scenes)) fail('ifFrameLoaded needs an existing scene name', node.scene);
255
+ bias = scenes[scene];
256
+ }
257
+ const frame = literal(node.frame);
258
+ if (Number.isInteger(frame) && frame + bias >= 1 && frame + bias <= 65536) {
259
+ const index = frame + bias - 1;
260
+ asm.op(OP.WaitForFrame, [index & 255, index >> 8, 1]);
261
+ } else {
262
+ value(node.frame);
263
+ if (bias) { asm.push(num(bias)); asm.op(OP.Add2); }
264
+ asm.op(OP.WaitForFrame2, [1]);
265
+ }
266
+ // Skip one short jump when unloaded, independent of how many actions the body contains.
267
+ const loaded = asm.label(), end = asm.label();
268
+ asm.jump(loaded);
269
+ if (node.alternate) emitStatement(node.alternate);
270
+ asm.jump(end);
271
+ asm.place(loaded); emitStatement(node.body); asm.place(end);
272
+ return;
273
+ }
274
+ case 'ClassExtends':
275
+ value(node.child); value(node.parent); op(OP.Extends, node); return;
276
+ case 'ClassImplements':
277
+ argumentsOf(node.interfaces); value(node.child); op(OP.Implements, node); return;
278
+ case 'WhileStatement':
279
+ loop(labels, ({ breakTo, continueTo }) => {
280
+ asm.place(continueTo);
281
+ condition(node.test);
282
+ asm.op(OP.Not);
283
+ asm.branch(breakTo);
284
+ emitStatement(node.body);
285
+ asm.jump(continueTo);
286
+ asm.place(breakTo);
287
+ });
288
+ return;
289
+ case 'DoWhileStatement':
290
+ loop(labels, ({ breakTo, continueTo }) => {
291
+ const top = asm.label();
292
+ asm.place(top);
293
+ emitStatement(node.body);
294
+ asm.place(continueTo);
295
+ condition(node.test);
296
+ asm.branch(top);
297
+ asm.place(breakTo);
298
+ });
299
+ return;
300
+ case 'ForStatement':
301
+ if (node.init?.type === 'VariableDeclaration') emitStatement(node.init);
302
+ else if (node.init) discard(node.init);
303
+ loop(labels, ({ breakTo, continueTo }) => {
304
+ const top = asm.label();
305
+ asm.place(top);
306
+ if (node.test) {
307
+ condition(node.test);
308
+ asm.op(OP.Not);
309
+ asm.branch(breakTo);
310
+ }
311
+ emitStatement(node.body);
312
+ asm.place(continueTo);
313
+ if (node.update) discard(node.update);
314
+ asm.jump(top);
315
+ asm.place(breakTo);
316
+ });
317
+ return;
318
+ case 'ForInStatement': {
319
+ // Enumerate2 pushes null, then every name. Each turn takes one name; null ends the loop.
320
+ // `break` drains the names left on the stack.
321
+ value(node.right);
322
+ op(OP.Enumerate2, node);
323
+ const drain = asm.label(), end = asm.label();
324
+ const target = { kind: 'loop', labels, breakTo: drain, continueTo: asm.label() };
325
+ asm.place(target.continueTo);
326
+ asm.op(OP.StoreRegister, [SCRATCH]);
327
+ asm.push({ type: 'null' });
328
+ asm.op(OP.Equals2);
329
+ asm.branch(end);
330
+ const name = { type: 'register', value: SCRATCH };
331
+ if (node.left.type === 'VariableDeclaration') {
332
+ asm.push(str(node.left.declarations[0].id.name), name);
333
+ asm.op(OP.DefineLocal);
334
+ } else {
335
+ assign(node.left, () => asm.push(name), false);
336
+ }
337
+ targets.push(target);
338
+ emitStatement(node.body);
339
+ targets.pop();
340
+ asm.jump(target.continueTo);
341
+ asm.place(drain);
342
+ asm.push({ type: 'null' });
343
+ asm.op(OP.Equals2);
344
+ asm.op(OP.Not);
345
+ asm.branch(drain);
346
+ asm.place(end);
347
+ return;
348
+ }
349
+ case 'SwitchStatement': {
350
+ const end = asm.label();
351
+ const entries = node.cases.map(() => asm.label());
352
+ value(node.discriminant);
353
+ asm.op(OP.StoreRegister, [SWITCH]);
354
+ asm.op(OP.Pop);
355
+ node.cases.forEach((item, index) => {
356
+ if (!item.test) return;
357
+ asm.push({ type: 'register', value: SWITCH });
358
+ value(item.test);
359
+ op(swfVersion >= 6 ? OP.StrictEquals : OP.Equals2, item);
360
+ asm.branch(entries[index]);
361
+ });
362
+ const fallback = node.cases.findIndex(item => !item.test);
363
+ asm.jump(fallback >= 0 ? entries[fallback] : end);
364
+ targets.push({ kind: 'switch', labels, breakTo: end });
365
+ node.cases.forEach((item, index) => {
366
+ asm.place(entries[index]);
367
+ body(item.consequent);
368
+ });
369
+ targets.pop();
370
+ asm.place(end);
371
+ return;
372
+ }
373
+ case 'BreakStatement': asm.jump(findTarget(node, node.label, false).breakTo); return;
374
+ case 'ContinueStatement': asm.jump(findTarget(node, node.label, true).continueTo); return;
375
+ case 'ReturnStatement':
376
+ if (!inFunction) fail('return is only allowed in a function', node);
377
+ if (node.argument) value(node.argument); else asm.push(UNDEFINED);
378
+ asm.op(OP.Return);
379
+ return;
380
+ case 'ThrowStatement':
381
+ value(node.argument);
382
+ op(OP.Throw, node);
383
+ return;
384
+ case 'TryStatement': {
385
+ if (swfVersion < 7) fail(`try needs SWF 7 or later (the script is SWF ${swfVersion})`, node);
386
+ const tryEnd = asm.label(), catchEnd = asm.label(), finallyEnd = asm.label();
387
+ const name = node.param ? asm.string(node.param.name) : [0];
388
+ const flags = (node.handler ? 1 : 0) | (node.finalizer ? 2 : 0);
389
+ asm.sized(OP.Try, 7 + name.length, (offsetOf, after) => {
390
+ const sizes = [offsetOf(tryEnd) - after, offsetOf(catchEnd) - offsetOf(tryEnd), offsetOf(finallyEnd) - offsetOf(catchEnd)];
391
+ return [flags, ...sizes.flatMap(size => [size & 0xff, size >> 8]), ...name];
392
+ });
393
+ targets.push({ kind: 'try', labels: [] });
394
+ body(node.block.body);
395
+ asm.place(tryEnd);
396
+ if (node.handler) body(node.handler.body);
397
+ asm.place(catchEnd);
398
+ if (node.finalizer) body(node.finalizer.body);
399
+ asm.place(finallyEnd);
400
+ targets.pop();
401
+ return;
402
+ }
403
+ case 'WithStatement': {
404
+ const end = asm.label();
405
+ value(node.object);
406
+ asm.sized(OP.With, 2, (offsetOf, after) => { const size = offsetOf(end) - after; return [size & 0xff, size >> 8]; });
407
+ targets.push({ kind: 'with', labels: [] });
408
+ emitStatement(node.body);
409
+ targets.pop();
410
+ asm.place(end);
411
+ return;
412
+ }
413
+ case 'TellTargetStatement': {
414
+ value(node.target);
415
+ asm.op(OP.SetTarget2);
416
+ emitStatement(node.body);
417
+ asm.op(OP.SetTarget, asm.string(''));
418
+ return;
419
+ }
420
+ default:
421
+ fail(`${node.type} is not supported`, node);
422
+ }
423
+ }
424
+
425
+ function functionDefinition(node) {
426
+ const end = asm.label();
427
+ // A function expression always leaves its value, even when it has a name.
428
+ const name = asm.string(node.type === 'FunctionDeclaration' ? node.id.name : '');
429
+ const count = [node.params.length & 0xff, node.params.length >> 8];
430
+ // From SWF 7, DefineFunction2 as Flash writes it: four local registers (the compiler's
431
+ // scratch and switch registers stay local to the call), `arguments` preloaded when used.
432
+ // Parameters stay named variables.
433
+ const modern = swfVersion >= 7;
434
+ const usesArguments = modern && mentionsName(node.body, 'arguments');
435
+ const usesSuper = modern && mentionsName(node.body, 'super');
436
+ const header = modern
437
+ ? [...name, ...count, 4, (usesArguments ? PRELOAD_ARGUMENTS : 0) | (usesSuper ? 0x10 : 0), 0, ...node.params.flatMap(param => [0, ...asm.string(param.name)])]
438
+ : [...name, ...count, ...node.params.flatMap(param => asm.string(param.name))];
439
+ asm.sized(modern ? OP.DefineFunction2 : OP.DefineFunction, header.length + 2, (offsetOf, after) => {
440
+ const size = offsetOf(end) - after;
441
+ if (size > 0xffff) throw new CompileError('Function too long (more than 64 KB)', node.line, node.column);
442
+ return [...header, size & 0xff, size >> 8];
443
+ });
444
+ const saved = [targets, inFunction, argumentsRegister, superRegister];
445
+ targets = [{ kind: 'function' }];
446
+ inFunction = true;
447
+ argumentsRegister = usesArguments;
448
+ superRegister = usesSuper ? (usesArguments ? 2 : 1) : 0;
449
+ body(node.body);
450
+ [targets, inFunction, argumentsRegister, superRegister] = saved;
451
+ asm.place(end);
452
+ }
453
+
454
+ /** Whether a function body reads `arguments` (not counting nested functions, which have their own). */
455
+ function mentionsName(statements, name) {
456
+ let found = false;
457
+ const visit = value => {
458
+ if (found || !value || typeof value !== 'object') return;
459
+ if (Array.isArray(value)) { value.forEach(visit); return; }
460
+ if (value.type === 'FunctionDeclaration' || value.type === 'FunctionExpression') return;
461
+ if (value.type === 'Identifier' && value.name === name) { found = true; return; }
462
+ for (const key of Object.keys(value)) if (key !== 'line' && key !== 'column') visit(value[key]);
463
+ };
464
+ visit(statements);
465
+ return found;
466
+ }
467
+
468
+ // ---- Expressions ----
469
+
470
+ /** Compile a condition (any value; If converts it to a boolean). */
471
+ function condition(node) { value(node); }
472
+
473
+ /** Evaluate for side effects only. */
474
+ function discard(node) {
475
+ switch (node.type) {
476
+ case 'AssignmentExpression': assignment(node, false); return;
477
+ case 'UpdateExpression': update(node, false); return;
478
+ case 'SequenceExpression': node.expressions.forEach(discard); return;
479
+ case 'CallExpression': if (call(node, false)) asm.op(OP.Pop); return;
480
+ case 'UnaryExpression':
481
+ if (node.operator === 'void' || node.operator === 'delete') { value(node); asm.op(OP.Pop); return; }
482
+ break;
483
+ default:
484
+ }
485
+ value(node);
486
+ asm.op(OP.Pop);
487
+ }
488
+
489
+ function propertyIndex(name) { return CLIP_PROPERTIES.indexOf(name); }
490
+
491
+ /** Push the value of `node`. */
492
+ function value(node) {
493
+ switch (node.type) {
494
+ case 'Literal': pushLiteral(node.value); return;
495
+ case 'ThisExpression': asm.push(str('this')); asm.op(OP.GetVariable); return;
496
+ case 'Identifier': {
497
+ if (node.name === 'super' && superRegister) { asm.push({ type: 'register', value: superRegister }); return; }
498
+ if (node.name === 'NaN') { asm.push(num(NaN)); return; }
499
+ if (node.name === 'Infinity') { asm.push(num(Infinity)); return; }
500
+ if (node.name === 'newline') { asm.push(str('\n')); return; }
501
+ if (node.name === 'arguments' && argumentsRegister) { asm.push({ type: 'register', value: ARGUMENTS }); return; }
502
+ const property = propertyIndex(node.name);
503
+ if (property >= 0) { asm.push(str(''), num(property)); asm.op(OP.GetProperty); return; }
504
+ asm.push(str(node.name));
505
+ asm.op(OP.GetVariable);
506
+ return;
507
+ }
508
+ case 'MemberExpression':
509
+ value(node.object);
510
+ memberName(node);
511
+ asm.op(OP.GetMember);
512
+ return;
513
+ case 'ArrayExpression':
514
+ for (let i = node.elements.length - 1; i >= 0; i--) value(node.elements[i]);
515
+ asm.push(num(node.elements.length));
516
+ asm.op(OP.InitArray);
517
+ return;
518
+ case 'ObjectExpression':
519
+ for (const property of node.properties) { asm.push(str(property.key)); value(property.value); }
520
+ asm.push(num(node.properties.length));
521
+ asm.op(OP.InitObject);
522
+ return;
523
+ case 'FunctionExpression': functionDefinition(node); return;
524
+ case 'SequenceExpression':
525
+ node.expressions.slice(0, -1).forEach(discard);
526
+ value(node.expressions.at(-1));
527
+ return;
528
+ case 'AssignmentExpression': assignment(node, true); return;
529
+ case 'UpdateExpression': update(node, true); return;
530
+ case 'CallExpression': if (!call(node, true)) asm.push(UNDEFINED); return;
531
+ case 'NewExpression': {
532
+ argumentsOf(node.arguments);
533
+ if (node.callee.type === 'Identifier') {
534
+ asm.push(str(node.callee.name));
535
+ asm.op(OP.NewObject);
536
+ } else if (node.callee.type === 'MemberExpression') {
537
+ value(node.callee.object);
538
+ memberName(node.callee);
539
+ asm.op(OP.NewMethod);
540
+ } else {
541
+ value(node.callee);
542
+ asm.push(UNDEFINED);
543
+ asm.op(OP.NewMethod);
544
+ }
545
+ return;
546
+ }
547
+ case 'ConditionalExpression': {
548
+ const yes = asm.label(), end = asm.label();
549
+ condition(node.test);
550
+ asm.branch(yes);
551
+ value(node.alternate);
552
+ asm.jump(end);
553
+ asm.place(yes);
554
+ value(node.consequent);
555
+ asm.place(end);
556
+ return;
557
+ }
558
+ case 'LogicalExpression': {
559
+ // Keep the left value when it decides the result, as Flash does.
560
+ const end = asm.label();
561
+ value(node.left);
562
+ asm.op(OP.PushDuplicate);
563
+ if (node.operator === '&&') asm.op(OP.Not);
564
+ asm.branch(end);
565
+ asm.op(OP.Pop);
566
+ value(node.right);
567
+ asm.place(end);
568
+ return;
569
+ }
570
+ case 'BinaryExpression': {
571
+ const ops = BINARY_OPS[node.operator];
572
+ if (!ops) fail(`The ${node.operator} operator is not supported`, node);
573
+ value(node.left);
574
+ value(node.right);
575
+ for (const code of ops) op(code, node);
576
+ return;
577
+ }
578
+ case 'UnaryExpression':
579
+ switch (node.operator) {
580
+ case '!': value(node.argument); asm.op(OP.Not); return;
581
+ case '-':
582
+ if (node.argument.type === 'Literal' && typeof node.argument.value === 'number') { asm.push(num(-node.argument.value)); return; }
583
+ asm.push(num(0)); value(node.argument); asm.op(OP.Subtract); return;
584
+ case '+': value(node.argument); asm.op(OP.ToNumber); return;
585
+ case '~': value(node.argument); asm.push(num(4294967295)); asm.op(OP.BitXor); return;
586
+ case 'typeof': value(node.argument); asm.op(OP.TypeOf); return;
587
+ case 'void': value(node.argument); asm.op(OP.Pop); asm.push(UNDEFINED); return;
588
+ case 'delete':
589
+ if (node.argument.type === 'Identifier') { asm.push(str(node.argument.name)); asm.op(OP.Delete2); return; }
590
+ value(node.argument.object);
591
+ memberName(node.argument);
592
+ asm.op(OP.Delete);
593
+ return;
594
+ default:
595
+ }
596
+ break;
597
+ default:
598
+ }
599
+ fail(`${node.type} is not supported`, node);
600
+ }
601
+
602
+ function memberName(node) {
603
+ if (node.computed) value(node.property);
604
+ else asm.push(str(node.property.name));
605
+ }
606
+
607
+ function argumentsOf(list) {
608
+ for (let i = list.length - 1; i >= 0; i--) value(list[i]);
609
+ asm.push(num(list.length));
610
+ }
611
+
612
+ /**
613
+ * Store into `target` the value pushed by `emitValue`. With `keep`, the stored value is left
614
+ * on the stack (read back from a register, as Flash does).
615
+ */
616
+ function assign(target, emitValue, keep) {
617
+ const finish = () => { if (keep) asm.op(OP.StoreRegister, [SCRATCH]); };
618
+ if (target.type === 'Identifier') {
619
+ const property = propertyIndex(target.name);
620
+ if (property >= 0) {
621
+ asm.push(str(''), num(property));
622
+ emitValue(); finish();
623
+ asm.op(OP.SetProperty);
624
+ } else {
625
+ asm.push(str(target.name));
626
+ emitValue(); finish();
627
+ asm.op(OP.SetVariable);
628
+ }
629
+ } else {
630
+ value(target.object);
631
+ memberName(target);
632
+ emitValue(); finish();
633
+ asm.op(OP.SetMember);
634
+ }
635
+ if (keep) asm.push({ type: 'register', value: SCRATCH });
636
+ }
637
+
638
+ /**
639
+ * The current value of a read-modify-write target (`+=`, `++`). As in Flash, a member target's
640
+ * object and property name are evaluated again for the read.
641
+ */
642
+ function current(target) { value(target); }
643
+
644
+ function assignment(node, keep) {
645
+ if (node.operator === '=') {
646
+ assign(node.left, () => value(node.right), keep);
647
+ return;
648
+ }
649
+ const operator = node.operator.slice(0, -1);
650
+ assign(node.left, () => {
651
+ current(node.left);
652
+ value(node.right);
653
+ for (const code of BINARY_OPS[operator]) op(code, node);
654
+ }, keep);
655
+ }
656
+
657
+ function update(node, keep) {
658
+ const step = node.operator === '++' ? OP.Increment : OP.Decrement;
659
+ if (node.prefix || !keep) {
660
+ assign(node.argument, () => { current(node.argument); asm.op(step); }, keep);
661
+ return;
662
+ }
663
+ // Postfix with its value used: the old value is the result.
664
+ assign(node.argument, () => {
665
+ current(node.argument);
666
+ asm.op(OP.StoreRegister, [SCRATCH]);
667
+ asm.op(step);
668
+ }, false);
669
+ asm.push({ type: 'register', value: SCRATCH });
670
+ }
671
+
672
+ /** Compile a call. Returns whether it pushed a value. */
673
+ function call(node, wantValue) {
674
+ const { callee } = node;
675
+ if (callee.type === 'Identifier' && !callee.parenthesized && !(callee.name === 'super' && superRegister)) {
676
+ const builtin = BUILTINS[callee.name];
677
+ if (builtin) return builtin(node.arguments, node, wantValue);
678
+ argumentsOf(node.arguments);
679
+ asm.push(str(callee.name));
680
+ asm.op(OP.CallFunction);
681
+ return true;
682
+ }
683
+ argumentsOf(node.arguments);
684
+ if (callee.type === 'MemberExpression') {
685
+ value(callee.object);
686
+ memberName(callee);
687
+ } else {
688
+ value(callee);
689
+ asm.push(UNDEFINED);
690
+ }
691
+ asm.op(OP.CallMethod);
692
+ return true;
693
+ }
694
+
695
+ // ---- Global functions that are actions ----
696
+
697
+ const literal = node => node?.type === 'Literal' ? node.value : node?.type === 'UnaryExpression' && node.operator === '-' && typeof node.argument.value === 'number' ? -node.argument.value : undefined;
698
+ const arity = (args, node, name, min, max = min) => {
699
+ if (args.length < min || args.length > max) fail(`${name} takes ${min === max ? min : `${min} to ${max}`} argument${max === 1 ? '' : 's'}`, node);
700
+ };
701
+ const action = (name, code, count) => (args, node) => {
702
+ arity(args, node, name, count);
703
+ args.forEach(value);
704
+ op(code, node);
705
+ return false;
706
+ };
707
+ const valueAction = (name, code, count) => (args, node) => {
708
+ arity(args, node, name, count);
709
+ args.forEach(value);
710
+ op(code, node);
711
+ return true;
712
+ };
713
+ const levelTarget = level => {
714
+ const n = literal(level);
715
+ if (typeof n === 'number') { asm.push(str(`_level${n}`)); return; }
716
+ asm.push(str('_level'));
717
+ value(level);
718
+ asm.op(OP.Add2);
719
+ };
720
+ const methodFlag = (method, node) => {
721
+ if (!method) return 0;
722
+ const text = literal(method);
723
+ if (typeof text !== 'string' || !/^(get|post)$/i.test(text)) fail('The method must be "GET" or "POST"', node);
724
+ return /^get$/i.test(text) ? 1 : 2;
725
+ };
726
+ const goto = play => (args, node) => {
727
+ const name = play ? 'gotoAndPlay' : 'gotoAndStop';
728
+ arity(args, node, name, 1, 2);
729
+ const frame = args.at(-1);
730
+ let bias = null;
731
+ if (args.length === 2) {
732
+ const scene = literal(args[0]);
733
+ if (typeof scene !== 'string') fail(`${name}: the scene must be a name in quotes`, args[0]);
734
+ if (!scenes || !(scene in scenes)) fail(`${name}: no scene named "${scene}"`, args[0]);
735
+ bias = scenes[scene];
736
+ }
737
+ const constant = literal(frame);
738
+ if (typeof constant === 'number' && Number.isInteger(constant) && constant >= 1 && bias === null) {
739
+ asm.op(OP.GotoFrame, [(constant - 1) & 0xff, (constant - 1) >> 8]);
740
+ if (play) asm.op(OP.Play);
741
+ } else if (typeof constant === 'string' && bias === null) {
742
+ asm.op(OP.GotoLabel, asm.string(constant));
743
+ if (play) asm.op(OP.Play);
744
+ } else {
745
+ value(frame);
746
+ asm.op(OP.GotoFrame2, bias === null ? [play ? 1 : 0] : [(play ? 1 : 0) | 2, bias & 0xff, bias >> 8]);
747
+ }
748
+ return false;
749
+ };
750
+ const load = (name, { variables, level }) => (args, node) => {
751
+ arity(args, node, name, 2, 3);
752
+ value(args[0]);
753
+ if (level) levelTarget(args[1]); else value(args[1]);
754
+ asm.op(OP.GetURL2, [(variables ? 0x80 : 0) | (level ? 0 : 0x40) | methodFlag(args[2], node)]);
755
+ return false;
756
+ };
757
+ const BUILTINS = {
758
+ trace: action('trace', OP.Trace, 1),
759
+ stop: action('stop', OP.Stop, 0),
760
+ play: action('play', OP.Play, 0),
761
+ nextFrame: action('nextFrame', OP.NextFrame, 0),
762
+ prevFrame: action('prevFrame', OP.PrevFrame, 0),
763
+ stopAllSounds: action('stopAllSounds', OP.StopSounds, 0),
764
+ toggleHighQuality: action('toggleHighQuality', OP.ToggleQuality, 0),
765
+ stopDrag: action('stopDrag', OP.StopDrag, 0),
766
+ removeMovieClip: action('removeMovieClip', OP.RemoveSprite, 1),
767
+ call: action('call', OP.CallFrame, 1),
768
+ random: valueAction('random', OP.RandomNumber, 1),
769
+ getTimer: valueAction('getTimer', OP.GetTime, 0),
770
+ int: valueAction('int', OP.ToInteger, 1),
771
+ chr: valueAction('chr', OP.Chr, 1),
772
+ ord: valueAction('ord', OP.Ord, 1),
773
+ mbchr: valueAction('mbchr', OP.MBAsciiToChar, 1),
774
+ mbord: valueAction('mbord', OP.MBCharToAscii, 1),
775
+ length: valueAction('length', OP.StringLength, 1),
776
+ mblength: valueAction('mblength', OP.MBStringLength, 1),
777
+ substring: valueAction('substring', OP.StringExtract, 3),
778
+ mbsubstring: valueAction('mbsubstring', OP.MBStringExtract, 3),
779
+ targetPath: valueAction('targetPath', OP.TargetPath, 1),
780
+ eval: valueAction('eval', OP.GetVariable, 1),
781
+ gotoAndPlay: goto(true),
782
+ gotoAndStop: goto(false),
783
+ getVersion(args, node) {
784
+ arity(args, node, 'getVersion', 0);
785
+ asm.push(str('/:$version'));
786
+ asm.op(OP.GetVariable);
787
+ return true;
788
+ },
789
+ set(args, node) {
790
+ arity(args, node, 'set', 2);
791
+ value(args[0]);
792
+ value(args[1]);
793
+ asm.op(OP.SetVariable);
794
+ return false;
795
+ },
796
+ getURL(args, node) {
797
+ arity(args, node, 'getURL', 1, 3);
798
+ const url = literal(args[0]), target = args[1] ? literal(args[1]) : '';
799
+ if (typeof url === 'string' && typeof target === 'string' && !args[2]) {
800
+ asm.op(OP.GetURL, [...asm.string(url), ...asm.string(target)]);
801
+ return false;
802
+ }
803
+ value(args[0]);
804
+ if (args[1]) value(args[1]); else asm.push(str(''));
805
+ asm.op(OP.GetURL2, [methodFlag(args[2], node)]);
806
+ return false;
807
+ },
808
+ fscommand(args, node) {
809
+ arity(args, node, 'fscommand', 1, 2);
810
+ const command = literal(args[0]), parameters = args[1] ? literal(args[1]) : '';
811
+ if (typeof command === 'string' && typeof parameters === 'string') {
812
+ asm.op(OP.GetURL, [...asm.string(`FSCommand:${command}`), ...asm.string(parameters)]);
813
+ return false;
814
+ }
815
+ asm.push(str('FSCommand:'));
816
+ value(args[0]);
817
+ asm.op(OP.Add2);
818
+ if (args[1]) value(args[1]); else asm.push(str(''));
819
+ asm.op(OP.GetURL2, [0]);
820
+ return false;
821
+ },
822
+ loadMovie: load('loadMovie', { variables: false, level: false }),
823
+ loadMovieNum: load('loadMovieNum', { variables: false, level: true }),
824
+ loadVariables: load('loadVariables', { variables: true, level: false }),
825
+ loadVariablesNum: load('loadVariablesNum', { variables: true, level: true }),
826
+ unloadMovie(args, node) {
827
+ arity(args, node, 'unloadMovie', 1);
828
+ asm.push(str(''));
829
+ value(args[0]);
830
+ asm.op(OP.GetURL2, [0x40]);
831
+ return false;
832
+ },
833
+ unloadMovieNum(args, node) {
834
+ arity(args, node, 'unloadMovieNum', 1);
835
+ asm.push(str(''));
836
+ levelTarget(args[0]);
837
+ asm.op(OP.GetURL2, [0]);
838
+ return false;
839
+ },
840
+ duplicateMovieClip(args, node) {
841
+ arity(args, node, 'duplicateMovieClip', 3);
842
+ value(args[0]);
843
+ value(args[1]);
844
+ value(args[2]);
845
+ asm.push(num(16384));
846
+ asm.op(OP.Add2);
847
+ asm.op(OP.CloneSprite);
848
+ return false;
849
+ },
850
+ startDrag(args, node) {
851
+ if (args.length !== 1 && args.length !== 2 && args.length !== 6) fail('startDrag takes 1, 2 or 6 arguments', node);
852
+ if (args.length === 6) {
853
+ args.slice(2).forEach(value);
854
+ asm.push({ type: 'boolean', value: true });
855
+ } else {
856
+ asm.push(num(0));
857
+ }
858
+ if (args[1]) value(args[1]); else asm.push(num(0));
859
+ value(args[0]);
860
+ asm.op(OP.StartDrag);
861
+ return false;
862
+ },
863
+ setProperty(args, node) {
864
+ arity(args, node, 'setProperty', 3);
865
+ value(args[0]);
866
+ clipProperty(args[1]);
867
+ value(args[2]);
868
+ asm.op(OP.SetProperty);
869
+ return false;
870
+ },
871
+ getProperty(args, node) {
872
+ arity(args, node, 'getProperty', 2);
873
+ value(args[0]);
874
+ clipProperty(args[1]);
875
+ asm.op(OP.GetProperty);
876
+ return true;
877
+ },
878
+ };
879
+ function clipProperty(node) {
880
+ const name = node.type === 'Identifier' ? node.name : literal(node);
881
+ const index = propertyIndex(String(name));
882
+ if (index < 0) fail('Expected a clip property such as _x or _alpha', node);
883
+ asm.push(num(index));
884
+ }
885
+
886
+ // Wrap builtins so that a value is pushed when the call's value is used.
887
+ for (const [name, emit] of Object.entries(BUILTINS)) {
888
+ BUILTINS[name] = (args, node, wantValue) => {
889
+ const pushed = emit(args, node);
890
+ if (!pushed && wantValue) asm.push(UNDEFINED);
891
+ return pushed || wantValue;
892
+ };
893
+ }
894
+
895
+ body(program.body);
896
+ return new Uint8Array([...asm.assemble(), 0]);
897
+ }