swf2js 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/LICENSE-GPL +680 -0
  2. package/README.md +208 -2
  3. package/package.json +24 -4
  4. package/src/cli.js +272 -0
  5. package/src/decoder/button-decoder.js +136 -0
  6. package/src/decoder/shape-decoder.js +786 -0
  7. package/src/decoder/symbol-table.js +36 -0
  8. package/src/decoder/tag-decoder.js +1190 -0
  9. package/src/decoder/tag-types.js +258 -0
  10. package/src/emitter/asset-encoder.js +708 -0
  11. package/src/emitter/bundle-emitter.js +596 -0
  12. package/src/emitter/embedded-swf.js +246 -0
  13. package/src/emitter/font-encoder.js +365 -0
  14. package/src/emitter/timeline-data-codec.js +58 -0
  15. package/src/model/swf-document.js +59 -0
  16. package/src/model/transpile-result.js +32 -0
  17. package/src/parser/bit-reader.js +237 -0
  18. package/src/parser/decompressor.js +91 -0
  19. package/src/parser/swf-parser.js +164 -0
  20. package/src/pretty-printer/pretty-printer.js +137 -0
  21. package/src/runtime/avm1-runtime.js +4907 -0
  22. package/src/runtime/avm2-runtime.js +1591 -0
  23. package/src/runtime/embedded-movie-runtime.js +208 -0
  24. package/src/runtime/index.js +17 -0
  25. package/src/runtime/movie-runtime.js +306 -0
  26. package/src/runtime/swflib.js +14050 -0
  27. package/src/transpiler/actionscript.js +390 -0
  28. package/src/transpiler/avm1/avm1-ir.js +205 -0
  29. package/src/transpiler/avm1/avm1-opcodes.js +149 -0
  30. package/src/transpiler/avm1/avm1-rewrite.js +291 -0
  31. package/src/transpiler/avm1/avm1-transpiler.js +2082 -0
  32. package/src/transpiler/avm2/abc-reader.js +416 -0
  33. package/src/transpiler/avm2/avm2-transpiler.js +2560 -0
  34. package/src/transpiler/cfg-structurer.js +876 -0
  35. package/src/transpiler/timeline/display-list.js +643 -0
  36. package/src/transpiler/timeline/timeline-codegen.js +6354 -0
  37. package/src/util/diagnostics.js +50 -0
  38. package/src/util/logger.js +40 -0
@@ -0,0 +1,208 @@
1
+ /**
2
+ * Set up a loaded movie around the generated, movie-specific lexical scope.
3
+ * This function is serialized into swflib.js, so its dependencies are explicit.
4
+ */
5
+ export function createEmbeddedMovieRuntime(hostRuntime, hostGlobal, environment, metadata, loadMovieAssets, getBinaryPayload, createMovie) {
6
+ var domain = environment.applicationDomain;
7
+ var childGlobal = Object.create(hostGlobal);
8
+ var runtime = Object.create(hostRuntime);
9
+ runtime.stage = null;
10
+ runtime.pulseFrameEvents = function () {};
11
+ runtime.setAvm2DefinitionLookup = function () {};
12
+ var loaded = Object.create(null);
13
+ var movieFonts = hostRuntime.createMovieFontLookup(metadata.assets, loaded);
14
+ var MovieTextBlock = hostRuntime.createMovieTextBlock(movieFonts);
15
+ var soundHost = { loaded: loaded, assets: metadata.assets, exportAssets: metadata.exportAssets };
16
+ var scriptAudio = hostRuntime.createMovieSoundScope(function () { return soundHost; });
17
+ var timelineAudio = hostRuntime.createTimelineAudio(function () { return childGlobal.__swoof; });
18
+ var timers = hostRuntime.createMovieTimers();
19
+ var MovieLoader = hostRuntime.createMovieLoader(environment.loaderInfo, domain);
20
+ var activeTimeline = null;
21
+ var stopped = false;
22
+ function stopAudio() {
23
+ if (stopped) return;
24
+ stopped = true;
25
+ scriptAudio.stopAll();
26
+ timelineAudio.stopAll();
27
+ if (activeTimeline) activeTimeline.setStreamPlaybackSuspended(true);
28
+ }
29
+ function stopMovie() {
30
+ timers.stopAll();
31
+ stopAudio();
32
+ }
33
+ if (environment.registerPendingStop) environment.registerPendingStop(stopMovie);
34
+ runtime.playSound = function () {
35
+ if (!stopped) return timelineAudio.playSound.apply(null, arguments);
36
+ };
37
+ runtime.stopSound = timelineAudio.stopSound;
38
+
39
+ var HostDomain = hostRuntime.builtins.ApplicationDomain;
40
+ function MovieDomain(parent) {
41
+ return new HostDomain(arguments.length ? parent : domain);
42
+ }
43
+ MovieDomain.prototype = HostDomain.prototype;
44
+ Object.setPrototypeOf(MovieDomain, HostDomain);
45
+ MovieDomain.currentDomain = domain;
46
+ MovieDomain.__swoofQualifiedName = 'flash.system.ApplicationDomain';
47
+
48
+ function getMovieDefinition(name) {
49
+ var qualified = String(name).replace('::', '.');
50
+ if (qualified === 'flash.display.Loader' || qualified === 'Loader') return MovieLoader;
51
+ if (qualified === 'flash.text.TextField' || qualified === 'TextField') return runtime.builtins.TextField;
52
+ if (qualified === 'flash.text.engine.TextBlock' || qualified === 'TextBlock') return MovieTextBlock;
53
+ if (qualified === 'flash.media.Sound') return scriptAudio.Sound;
54
+ if (qualified === 'flash.utils.Timer') return timers.Timer;
55
+ if (qualified.startsWith('flash.utils.')) {
56
+ var operation = qualified.slice('flash.utils.'.length);
57
+ if (Object.prototype.hasOwnProperty.call(timers.scheduling, operation)) return timers.scheduling[operation];
58
+ }
59
+ return domain.getDefinition(name);
60
+ }
61
+ runtime.builtins = Object.assign({}, hostRuntime.builtins, {
62
+ ApplicationDomain: MovieDomain,
63
+ getDefinitionByName: getMovieDefinition,
64
+ Loader: MovieLoader,
65
+ TextBlock: MovieTextBlock,
66
+ Sound: scriptAudio.Sound,
67
+ Timer: timers.Timer,
68
+ }, timers.scheduling);
69
+ runtime.packages = Object.assign({}, hostRuntime.packages, {
70
+ system: Object.assign({}, hostRuntime.packages.system, { ApplicationDomain: MovieDomain }),
71
+ display: Object.assign({}, hostRuntime.packages.display, { Loader: MovieLoader }),
72
+ text: Object.assign({}, hostRuntime.packages.text, {
73
+ engine: Object.assign({}, hostRuntime.packages.text.engine, { TextBlock: MovieTextBlock }),
74
+ }),
75
+ utils: Object.assign({}, hostRuntime.packages.utils, timers.scheduling,
76
+ { getDefinitionByName: getMovieDefinition, Timer: timers.Timer }),
77
+ media: Object.assign({}, hostRuntime.packages.media, { Sound: scriptAudio.Sound }),
78
+ });
79
+ childGlobal.ApplicationDomain = MovieDomain;
80
+ childGlobal.Loader = MovieLoader;
81
+ childGlobal.TextBlock = MovieTextBlock;
82
+ childGlobal.Sound = scriptAudio.Sound;
83
+ childGlobal.Timer = timers.Timer;
84
+ Object.assign(childGlobal, timers.scheduling);
85
+ childGlobal.flash = Object.assign({}, hostGlobal.flash, runtime.packages);
86
+
87
+ var canvas = hostGlobal.document.createElement('canvas');
88
+ canvas.width = metadata.stageW;
89
+ canvas.height = metadata.stageH;
90
+ var ctx = canvas.getContext('2d');
91
+
92
+ function bindTimeline(timeline, displayList, characters, frames, frameCount) {
93
+ activeTimeline = timeline;
94
+ var root = {
95
+ name: 'root', x: 0, y: 0, scaleX: 100, scaleY: 100,
96
+ width: metadata.stageW, height: metadata.stageH, alpha: 100, visible: true, rotation: 0,
97
+ currentFrame: 1, totalFrames: frameCount, parent: null,
98
+ _swoofSourceBytes: metadata.sourceBytes,
99
+ gotoAndPlay: function (frame, scene, bias) { timeline.gotoAndPlay(frame, scene, bias); },
100
+ gotoAndStop: function (frame, scene, bias) { timeline.gotoAndStop(frame, scene, bias); },
101
+ nextFrame: function () { timeline.nextFrame(); },
102
+ prevFrame: function () { timeline.prevFrame(); },
103
+ play: function () { timeline.play(); },
104
+ stop: function () { timeline.stop(); },
105
+ };
106
+
107
+ var host = childGlobal.__swoof = {
108
+ stageWidth: metadata.stageW, stageHeight: metadata.stageH, frameRate: metadata.frameRate,
109
+ frameCount: frameCount, timeline: timeline, displayList: displayList,
110
+ characters: characters, frames: frames, root: root, loaded: loaded,
111
+ fontLookup: movieFonts,
112
+ bitmapData: Object.create(null), symbolClasses: metadata.symbolClasses,
113
+ };
114
+ var builtins = runtime.builtins;
115
+ var MovieTextField = hostRuntime.createMovieTextField(characters);
116
+ builtins.TextField = MovieTextField;
117
+ runtime.packages.text.TextField = MovieTextField;
118
+ childGlobal.TextField = MovieTextField;
119
+ for (var asset of metadata.assets) {
120
+ var image = loaded[asset.id];
121
+ if (asset.type !== 'bitmap' || !image) continue;
122
+ var bitmap = new builtins.BitmapData(image.naturalWidth || image.width, image.naturalHeight || image.height, true);
123
+ bitmap._img = image;
124
+ host.bitmapData[asset.id] = bitmap;
125
+ }
126
+
127
+ var constructingDocumentClass = null;
128
+ function bindConstructingDocument(instance) {
129
+ if (!constructingDocumentClass || instance.constructor !== constructingDocumentClass) return false;
130
+ instance.root = instance;
131
+ instance.loaderInfo = environment.loaderInfo;
132
+ instance.stage = environment.loader && environment.loader.stage || null;
133
+ instance._swoofTimeline = timeline;
134
+ instance._swoofHostTimeline = true;
135
+ instance.totalFrames = instance.framesLoaded = frameCount;
136
+ host.main = instance;
137
+ return true;
138
+ }
139
+
140
+ function boot(classes, resolveLinkedClass, runInitializers) {
141
+ if (classes) {
142
+ for (var name of Object.keys(classes)) {
143
+ var value = classes[name];
144
+ if (typeof value !== 'function' || !Object.prototype.hasOwnProperty.call(value, '__swoofQualifiedName')) continue;
145
+ if (value.__swoofQualifiedName === name) domain._registerDefinition(name, value);
146
+ Object.defineProperty(childGlobal, name, { value: value, writable: true, configurable: true });
147
+ }
148
+ }
149
+ for (var entry of metadata.linkedBinaryData) {
150
+ var binaryClass = resolveLinkedClass(entry[0]);
151
+ if (typeof binaryClass === 'function') binaryClass.__swoofBinaryData = getBinaryPayload(entry[1]);
152
+ }
153
+ if (runInitializers) runInitializers();
154
+
155
+ timeline.start = function () {};
156
+ environment.loaderInfo.width = metadata.stageW;
157
+ environment.loaderInfo.height = metadata.stageH;
158
+ environment.loaderInfo.frameRate = metadata.frameRate;
159
+ var documentClass = metadata.symbolClasses.find(function (symbol) { return symbol.id === 0; });
160
+ var main;
161
+ if (documentClass) {
162
+ constructingDocumentClass = resolveLinkedClass(documentClass.name);
163
+ if (typeof constructingDocumentClass !== 'function') {
164
+ throw new Error('Missing embedded document class ' + documentClass.name);
165
+ }
166
+ } else constructingDocumentClass = builtins.MovieClip;
167
+ try {
168
+ main = new constructingDocumentClass();
169
+ bindConstructingDocument(main);
170
+ } finally {
171
+ constructingDocumentClass = null;
172
+ }
173
+
174
+ if (main._playing === false) timeline.setPlayback(false);
175
+ main._swoofTimelineCanvas = canvas;
176
+ main._swoofStopTimelineAudio = stopAudio;
177
+ main._swoofStopMovieTimers = timers.stopAll;
178
+ var elapsed = 0;
179
+ main.addEventListener(builtins.Event.ENTER_FRAME, function () {
180
+ if (stopped || !hostRuntime.stage?.contains(main)) return;
181
+ var parentRate = main.stage && main.stage.frameRate || metadata.frameRate;
182
+ elapsed += metadata.frameRate / parentRate;
183
+ var steps = Math.min(3, Math.floor(elapsed));
184
+ elapsed %= 1;
185
+ for (var i = 0; i < steps; i++) timeline.tick();
186
+ });
187
+ main.addEventListener(builtins.Event.ADDED_TO_STAGE, function () {
188
+ if (!stopped) timeline.setStreamPlaybackSuspended(false);
189
+ });
190
+ main.addEventListener(builtins.Event.REMOVED_FROM_STAGE, function () {
191
+ elapsed = 0;
192
+ timeline.setStreamPlaybackSuspended(true);
193
+ });
194
+ timeline.enter();
195
+ return main;
196
+ }
197
+
198
+ return { root: root, bindConstructingDocument: bindConstructingDocument, boot: boot };
199
+ }
200
+
201
+ return loadMovieAssets(metadata.assets, loaded).then(function () {
202
+ if (stopped) return null;
203
+ return createMovie({ global: childGlobal, runtime: runtime, loaded: loaded, ctx: ctx, bindTimeline: bindTimeline }, metadata);
204
+ }).catch(function (error) {
205
+ stopMovie();
206
+ throw error;
207
+ });
208
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * @fileoverview Runtime sources inlined into browser bundles.
3
+ */
4
+
5
+ import { readFileSync } from 'fs';
6
+ import { fileURLToPath } from 'url';
7
+ import { dirname, join } from 'path';
8
+ import { createAvm2Runtime } from './avm2-runtime.js';
9
+
10
+ const __dirname = dirname(fileURLToPath(import.meta.url));
11
+
12
+ /** Shared SWF player API shim (geom, display, events, media, ui). */
13
+ export const SWFLIB_BASE_SOURCE = readFileSync(join(__dirname, 'swflib.js'), 'utf8').trim();
14
+ export const SWFLIB_SOURCE = `${SWFLIB_BASE_SOURCE}
15
+ globalThis.__swoof_swflib.createAvm2Runtime = ${createAvm2Runtime.toString()};`;
16
+
17
+ export { AVM1_RUNTIME_FACTORY_SOURCE, AVM1_RUNTIME_BOOTSTRAP, AVM1_RUNTIME_STUB } from './avm1-runtime.js';
@@ -0,0 +1,306 @@
1
+ // Serialized into swflib.js. Movie-specific lexical bindings are supplied by
2
+ // the generated script installer, while playback runs in this shared runtime.
3
+ export function installMovieRuntime(runtime, global) {
4
+ const document = global.document;
5
+ const window = global.window || global;
6
+ const fontLoads = new Map();
7
+
8
+ function readClassicAsset(path, property, kind) {
9
+ return new Promise((resolve, reject) => {
10
+ const script = document.createElement('script');
11
+ script.src = path;
12
+ script.onload = () => {
13
+ const value = script[property];
14
+ script.remove();
15
+ resolve(value);
16
+ };
17
+ script.onerror = () => {
18
+ script.remove();
19
+ reject(new Error('Unable to load compiled ' + kind + ': ' + path));
20
+ };
21
+ document.head.appendChild(script);
22
+ });
23
+ }
24
+
25
+ function loadMovieFont(asset) {
26
+ if (typeof global.FontFace !== 'function' || typeof document.fonts?.add !== 'function') return null;
27
+ const key = `${asset.family}:${!!asset.bold}:${!!asset.italic}`;
28
+ if (!fontLoads.has(key)) {
29
+ fontLoads.set(key, readClassicAsset(asset.path, '_swoofFontBytes', 'font').then(data => {
30
+ const bytes = Uint8Array.from(global.atob(data), byte => byte.charCodeAt(0));
31
+ const face = new global.FontFace(asset.family, bytes, {
32
+ weight: asset.bold ? 'bold' : 'normal', style: asset.italic ? 'italic' : 'normal',
33
+ });
34
+ return face.load().then(() => {
35
+ document.fonts.add(face);
36
+ return { family: asset.family, bold: asset.bold, italic: asset.italic };
37
+ });
38
+ }).catch(() => {
39
+ fontLoads.delete(key);
40
+ return null;
41
+ }));
42
+ }
43
+ return fontLoads.get(key);
44
+ }
45
+
46
+ function loadMovieAssets(assets, loaded) {
47
+ // Visual assets block the first paint. Audio loads in the background.
48
+ const visualPromises = [];
49
+ for (const asset of assets) {
50
+ if (!asset.path) {
51
+ loaded[asset.id] = null;
52
+ } else if (asset.type === 'font') {
53
+ visualPromises.push(Promise.resolve(loadMovieFont(asset)).then(font => { loaded[asset.id] = font; }));
54
+ } else if (asset.type === 'bitmap') {
55
+ visualPromises.push(new Promise(resolve => {
56
+ function finish(source, useMaskCoverage) {
57
+ if (source && useMaskCoverage && asset.maskCoverage != null) source._swoofMaskCoverage = asset.maskCoverage;
58
+ loaded[asset.id] = source;
59
+ resolve();
60
+ }
61
+ const image = new global.Image();
62
+ image.onload = () => {
63
+ if (!asset.alphaPath) {
64
+ finish(image, true);
65
+ return;
66
+ }
67
+ const alpha = new global.Image();
68
+ alpha.onload = () => {
69
+ const canvas = document.createElement('canvas');
70
+ canvas.width = image.naturalWidth || image.width;
71
+ canvas.height = image.naturalHeight || image.height;
72
+ const ctx = canvas.getContext('2d');
73
+ if (ctx) {
74
+ ctx.drawImage(image, 0, 0);
75
+ ctx.globalCompositeOperation = 'destination-in';
76
+ ctx.drawImage(alpha, 0, 0, canvas.width, canvas.height);
77
+ ctx.globalCompositeOperation = 'source-over';
78
+ }
79
+ finish(ctx ? canvas : image, !!ctx);
80
+ };
81
+ alpha.onerror = () => finish(image, false);
82
+ alpha.src = asset.alphaPath;
83
+ };
84
+ image.onerror = () => finish(null, false);
85
+ image.src = asset.path;
86
+ }));
87
+ } else if (asset.type === 'audio') {
88
+ try {
89
+ const audio = new global.Audio();
90
+ audio.preload = 'auto';
91
+ loaded[asset.id] = audio;
92
+ audio.addEventListener('error', () => { loaded[asset.id] = null; });
93
+ audio.src = asset.path;
94
+ } catch (_) {
95
+ loaded[asset.id] = null;
96
+ }
97
+ }
98
+ }
99
+ return Promise.all(visualPromises);
100
+ }
101
+
102
+ function registerEmbeddedMovie(base64, path, length, version, getBinaryPayload) {
103
+ let factoryPromise;
104
+ const factory = environment => {
105
+ if (!factoryPromise) {
106
+ factoryPromise = readClassicAsset(path, '_swoofMovieFactory', 'embedded SWF').then(factory => {
107
+ if (typeof factory !== 'function') throw new Error('Missing compiled embedded SWF factory: ' + path);
108
+ return factory;
109
+ }).catch(error => { factoryPromise = null; throw error; });
110
+ }
111
+ return factoryPromise.then(factory => factory(environment, loadMovieAssets, getBinaryPayload));
112
+ };
113
+ if (length != null) return runtime.registerCompiledSwf(base64, length, version, factory);
114
+ // Older bundles carry only the payload index and script path.
115
+ const bytes = Uint8Array.from(global.atob(base64), byte => byte.charCodeAt(0));
116
+ runtime.registerEmbeddedSwf(bytes, factory);
117
+ return base64;
118
+ }
119
+
120
+ function resolveLinkedClass(name, getDefinition) {
121
+ if (!name || typeof name !== 'string') return null;
122
+ const definition = typeof getDefinition === 'function' && getDefinition(name);
123
+ if (typeof definition === 'function') return definition;
124
+ if (typeof global[name] === 'function') return global[name];
125
+ const parts = name.split('.');
126
+ let value = global;
127
+ for (const part of parts) value = value == null ? undefined : value[part];
128
+ if (typeof value === 'function') return value;
129
+ const shortName = parts[parts.length - 1];
130
+ return typeof global[shortName] === 'function' ? global[shortName] : null;
131
+ }
132
+
133
+ function mountMovie(movie, installScripts) {
134
+ const { stageWidth, stageHeight, frameRate, background, assets, symbolClasses, exportAssets } = movie;
135
+ const data = movie.timelineData || global.__swoofTimelineData;
136
+ if (!data) throw new Error('Missing SWF timeline data');
137
+ if (!movie.timelineData) delete global.__swoofTimelineData;
138
+ const { frameCount, scenes } = data;
139
+ const anchorFrames = new Map();
140
+ for (const [frameIndex, frame] of data.frames.entries()) {
141
+ for (const name of frame?.namedAnchors || []) {
142
+ if (!anchorFrames.has(name)) anchorFrames.set(name, frameIndex);
143
+ }
144
+ }
145
+ function currentAnchorFrame() {
146
+ const hash = window.location?.hash;
147
+ if (!hash || hash.length < 2) return;
148
+ try {
149
+ return anchorFrames.get(decodeURIComponent(hash.slice(1)));
150
+ } catch (_) {}
151
+ }
152
+ function publishRootAnchor(frameIndex) {
153
+ const name = data.frames[frameIndex]?.namedAnchors?.[0];
154
+ if (!name || currentAnchorFrame() === frameIndex) return;
155
+ try {
156
+ // A looping timeline updates the bookmark without growing browser history.
157
+ window.history?.replaceState(window.history.state, '', '#' + encodeURIComponent(name));
158
+ } catch (_) {}
159
+ }
160
+ const binaryPayloads = movie.binaryPayloads ?? global.__swoofBinaryData;
161
+ if (!binaryPayloads) throw new Error('Missing SWF linked binary data');
162
+ if (movie.binaryPayloads == null) delete global.__swoofBinaryData;
163
+ const compiledPayloads = new Map();
164
+ const getBinaryPayload = index => compiledPayloads.get(index) ?? binaryPayloads[index];
165
+ for (const [index, path, length, version, url] of movie.embeddedMovies) {
166
+ if (!url && compiledPayloads.has(index)) continue;
167
+ const entry = registerEmbeddedMovie(binaryPayloads[index], path, length, version, getBinaryPayload);
168
+ if (index !== null && !compiledPayloads.has(index)) compiledPayloads.set(index, entry);
169
+ if (url) runtime.registerCompanionSwf(url, entry);
170
+ }
171
+ if (movie.linkedBinaryData.length) {
172
+ runtime.setLinkedBinaryData(movie.linkedBinaryData.map(([name, index]) => [name, getBinaryPayload(index)]));
173
+ }
174
+
175
+ const loaded = Object.create(null);
176
+ const canvas = document.getElementById('stage');
177
+ const ctx = canvas ? canvas.getContext('2d') : null;
178
+ const stage = runtime.stage;
179
+ stage.stageWidth = stageWidth;
180
+ stage.stageHeight = stageHeight;
181
+ stage.frameRate = frameRate;
182
+ stage.loaderInfo._configureRootLoad({
183
+ width: stageWidth, height: stageHeight, frameRate,
184
+ swfVersion: movie.swfVersion, bytesTotal: movie.swfBytesTotal,
185
+ });
186
+
187
+ let host, lookupClass, constructingDocumentClass;
188
+ function bindConstructingDocument(instance) {
189
+ if (!constructingDocumentClass || !instance || instance.constructor !== constructingDocumentClass) return false;
190
+ instance.root = instance;
191
+ instance.stage = stage;
192
+ instance.loaderInfo = stage.loaderInfo;
193
+ instance.loaderInfo.content = instance;
194
+ return true;
195
+ }
196
+
197
+ installScripts((bridge, buttonActions) => {
198
+ lookupClass = name => resolveLinkedClass(name, bridge.getDefinition);
199
+ const bindings = runtime.createTimelineEngine(data, movie, Object.assign(bridge, {
200
+ global, window, document, runtime, loaded, ctx, bindConstructingDocument,
201
+ resolveLinkedClass: lookupClass,
202
+ onRootFrameEntered: anchorFrames.size ? publishRootAnchor : undefined,
203
+ requestAnimationFrame: callback => global.requestAnimationFrame(callback),
204
+ }), buttonActions);
205
+ const { timeline, displayList, FRAMES, CHARACTERS, normalizeSceneGotoArguments } = bindings;
206
+ function goTo(play, frame, scene, sceneBias) {
207
+ const args = normalizeSceneGotoArguments(frame, scene, sceneBias, scenes);
208
+ if (args.scene == null && args.sceneBias == null) args.scene = host.root.currentScene?.name;
209
+ const method = play ? 'gotoAndPlay' : 'gotoAndStop';
210
+ timeline[method](args.frame, args.scene, args.sceneBias);
211
+ }
212
+ const root = {
213
+ name: 'root', x: 0, y: 0, scaleX: 100, scaleY: 100,
214
+ width: stageWidth, height: stageHeight, alpha: 100, visible: true, rotation: 0,
215
+ currentFrame: 1, totalFrames: frameCount, parent: null,
216
+ _swoofSourceBytes: stage.loaderInfo.bytesTotal,
217
+ gotoAndPlay: (frame, scene, bias) => goTo(true, frame, scene, bias),
218
+ gotoAndStop: (frame, scene, bias) => goTo(false, frame, scene, bias),
219
+ nextFrame: () => timeline.nextFrame(),
220
+ prevFrame: () => timeline.prevFrame(),
221
+ nextScene: () => timeline.nextScene(),
222
+ prevScene: () => timeline.prevScene(),
223
+ play: () => timeline.play(),
224
+ stop: () => timeline.stop(),
225
+ };
226
+ host = window.__swoof = {
227
+ stageWidth, stageHeight, frameRate, frameCount, background, assets, loaded, exportAssets,
228
+ fontLookup: runtime.createMovieFontLookup(assets, loaded),
229
+ timeline, displayList, characters: CHARACTERS, frames: FRAMES, root, symbolClasses,
230
+ playSound: (id, loops) => runtime.playSound(id, loops),
231
+ };
232
+ return Object.assign(bindings, {
233
+ root, loaded, ctx, canvas, bindConstructingDocument, resolveLinkedClass: lookupClass,
234
+ ASSETS: assets, SYMBOL_CLASSES: symbolClasses, EXPORT_ASSETS: exportAssets,
235
+ STAGE_WIDTH: stageWidth, STAGE_HEIGHT: stageHeight, FRAME_RATE: frameRate, BACKGROUND: background,
236
+ });
237
+ });
238
+
239
+ function bootDocumentClass() {
240
+ for (const symbol of symbolClasses) {
241
+ if (symbol.id !== 0) continue;
242
+ const Class = lookupClass(symbol.name);
243
+ if (typeof Class !== 'function') {
244
+ global.console?.warn('swoof: missing document class', symbol.name);
245
+ continue;
246
+ }
247
+ try {
248
+ constructingDocumentClass = Class;
249
+ let main;
250
+ try {
251
+ main = new Class();
252
+ bindConstructingDocument(main);
253
+ } finally {
254
+ constructingDocumentClass = null;
255
+ }
256
+ main.totalFrames = main.framesLoaded = frameCount;
257
+ main.currentFrame = (host.timeline.frame | 0) + 1;
258
+ main._swoofHostTimeline = true;
259
+ host.main = main;
260
+ if (main._playing === false) host.timeline.setPlayback(false);
261
+ main.stage = null;
262
+ global.stage = stage;
263
+ stage.addChild(main);
264
+ return;
265
+ } catch (error) {
266
+ global.console?.warn('swoof: document class', symbol.name, error?.message || error);
267
+ }
268
+ }
269
+ }
270
+
271
+ let bootStarted = false;
272
+ function boot() {
273
+ if (bootStarted) return;
274
+ bootStarted = true;
275
+ loadMovieAssets(assets, loaded).then(() => {
276
+ stage.loaderInfo.bytesLoaded = stage.loaderInfo.bytesTotal;
277
+ host.bitmapData = Object.create(null);
278
+ for (const asset of assets) {
279
+ const image = loaded[asset.id];
280
+ if (asset.type !== 'bitmap' || !image) continue;
281
+ const bitmap = new runtime.builtins.BitmapData(image.naturalWidth || asset.width || 0, image.naturalHeight || asset.height || 0, true);
282
+ bitmap._img = image;
283
+ host.bitmapData[asset.id] = bitmap;
284
+ }
285
+ if (anchorFrames.size) {
286
+ const frameIndex = currentAnchorFrame();
287
+ if (frameIndex != null) host.timeline.frame = frameIndex;
288
+ window.addEventListener?.('hashchange', () => {
289
+ const nextFrame = currentAnchorFrame();
290
+ if (nextFrame != null && nextFrame !== host.timeline.frame) host.timeline.gotoAndPlay(nextFrame + 1);
291
+ });
292
+ }
293
+ bootDocumentClass();
294
+ host.timeline.enter();
295
+ const main = host.main;
296
+ if (main?.loaderInfo) main.loaderInfo._completeRootLoad(main);
297
+ host.timeline.start();
298
+ });
299
+ }
300
+ if (document.readyState === 'complete') boot();
301
+ else window.addEventListener('load', boot);
302
+ return host;
303
+ }
304
+
305
+ runtime.mountMovie = mountMovie;
306
+ }