swf2js 0.0.0-stage → 0.1.1
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.
- package/LICENSE-GPL +680 -0
- package/README.md +208 -2
- package/package.json +24 -4
- package/src/cli.js +272 -0
- package/src/decoder/button-decoder.js +136 -0
- package/src/decoder/shape-decoder.js +786 -0
- package/src/decoder/symbol-table.js +36 -0
- package/src/decoder/tag-decoder.js +1190 -0
- package/src/decoder/tag-types.js +258 -0
- package/src/emitter/asset-encoder.js +708 -0
- package/src/emitter/bundle-emitter.js +596 -0
- package/src/emitter/embedded-swf.js +246 -0
- package/src/emitter/font-encoder.js +365 -0
- package/src/emitter/timeline-data-codec.js +58 -0
- package/src/model/swf-document.js +59 -0
- package/src/model/transpile-result.js +32 -0
- package/src/parser/bit-reader.js +237 -0
- package/src/parser/decompressor.js +91 -0
- package/src/parser/swf-parser.js +164 -0
- package/src/pretty-printer/pretty-printer.js +137 -0
- package/src/runtime/avm1-runtime.js +4907 -0
- package/src/runtime/avm2-runtime.js +1591 -0
- package/src/runtime/embedded-movie-runtime.js +208 -0
- package/src/runtime/index.js +17 -0
- package/src/runtime/movie-runtime.js +306 -0
- package/src/runtime/swflib.js +14050 -0
- package/src/transpiler/actionscript.js +390 -0
- package/src/transpiler/avm1/avm1-ir.js +205 -0
- package/src/transpiler/avm1/avm1-opcodes.js +149 -0
- package/src/transpiler/avm1/avm1-rewrite.js +291 -0
- package/src/transpiler/avm1/avm1-transpiler.js +2082 -0
- package/src/transpiler/avm2/abc-reader.js +416 -0
- package/src/transpiler/avm2/avm2-transpiler.js +2560 -0
- package/src/transpiler/cfg-structurer.js +876 -0
- package/src/transpiler/timeline/display-list.js +643 -0
- package/src/transpiler/timeline/timeline-codegen.js +6354 -0
- package/src/util/diagnostics.js +50 -0
- package/src/util/logger.js +40 -0
package/README.md
CHANGED
|
@@ -1,3 +1,209 @@
|
|
|
1
|
-
#
|
|
1
|
+
# swoof — SWF-to-Browser Transpiler
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**swoof** statically transpiles Adobe Flash `.swf` files into plain JavaScript that runs in modern browsers — no Flash plugin required.
|
|
4
|
+
|
|
5
|
+
It parses the binary SWF format, decodes tags (shapes, timelines, sounds, fonts), and transpiles embedded ActionScript bytecode (AVM1 and AVM2) to ES2020 class-based JavaScript with structured control flow (`while`, `if/else`).
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## Install and run
|
|
10
|
+
|
|
11
|
+
Install Node.js 20 or later. Run the published CLI without installing it globally:
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
npx swf2js --help
|
|
15
|
+
npx swf2js -o out "path/to/game.swf"
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
To run from a source checkout, install the locked dependencies and check the CLI:
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
npm ci
|
|
22
|
+
npm start -- --help
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Convert a demo SWF from the source checkout to try the full workflow:
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
npm start -- -o out demos/neon-grid.swf
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Open `out/neon-grid/index.html` in a browser. Click a square to make your move. The computer takes the next turn.
|
|
32
|
+
|
|
33
|
+
To convert your own movie from the source checkout, run `npm start -- -o out "path/to/game.swf"` and open `out/game/index.html`. If you omit `-o`, Swoof creates the output folder next to the source SWF.
|
|
34
|
+
|
|
35
|
+
To test over HTTP, serve the output directory with Python 3 and open `http://127.0.0.1:8000/neon-grid/`.
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
python3 -m http.server 8000 --bind 127.0.0.1 --directory out
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Test with the provided demos
|
|
42
|
+
|
|
43
|
+
The demo SWFs are included in the source checkout, but not in the published npm package. Run this command from the project directory to convert all seven demos.
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
npm start -- -o out/demos demos/*.swf
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Open `out/demos/<folder>/index.html` for each demo. Click inside the game before using keyboard controls.
|
|
50
|
+
|
|
51
|
+
| Demo folder | What to try |
|
|
52
|
+
|---|---|
|
|
53
|
+
| `swoof-intro` | Watch the rocket launch, landing, and feature slides. Click **Replay with sound** in the lower-right corner to test the soundtrack. |
|
|
54
|
+
| `relic-match` | Flip two cards. Look for matching pairs to stay face up and for the move counter to update. Press **R** to shuffle. |
|
|
55
|
+
| `neon-grid` | Click an empty square to play tic-tac-toe against the computer. Check that it replies and that **R** starts a new round. |
|
|
56
|
+
| `vesper-patrol` | Click **Start Patrol**. Move with the arrow keys or **WASD**, fire with **Space**, and pause or resume with **P**. |
|
|
57
|
+
| `target-circuit` | Click **Start Run**, then click the colored rings. Check that a hit advances the target and increases the score. |
|
|
58
|
+
| `signal-sequence` | Click **Start Pattern**. Watch the sequence, then repeat it by clicking the pads or pressing **1** through **4**. |
|
|
59
|
+
| `lane-relay` | Click **Start Run**. Use **Left**, **Up**, and **Right** to switch to the left, center, and right lanes and pass through barrier openings. |
|
|
60
|
+
|
|
61
|
+
---
|
|
62
|
+
|
|
63
|
+
## License
|
|
64
|
+
|
|
65
|
+
**swoof** is available under a dual-licensing model:
|
|
66
|
+
|
|
67
|
+
* **Open Source:** Licensed under the [GNU General Public License v3.0](./LICENSE-GPL) (`GPL-3.0-only`).
|
|
68
|
+
* **Commercial License:** For proprietary use without GPL obligations, contact the project maintainer to discuss a commercial license.
|
|
69
|
+
|
|
70
|
+
## Usage
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
npx swf2js [options] <file.swf> [file.swf ...]
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
| Option | Description |
|
|
77
|
+
|---|---|
|
|
78
|
+
| `--inspect` | Pretty-print the parsed SWF structure (tags, frames, assets) |
|
|
79
|
+
| `--actionscript` | Print transpiled ActionScript as JavaScript to stdout |
|
|
80
|
+
| `--pack-timeline` | Pack timeline data even for small movies |
|
|
81
|
+
| `--plain-timeline` | Keep timeline data readable and usable without browser gzip support |
|
|
82
|
+
| `--output-dir, -o <path>` | Output directory for the generated bundle |
|
|
83
|
+
| `--verbose` | Print per-tag diagnostics |
|
|
84
|
+
| `--warn-unknown` | Warn on unrecognized tags or opcodes |
|
|
85
|
+
| `--version, -v` | Print version |
|
|
86
|
+
| `--help, -h` | Print help |
|
|
87
|
+
|
|
88
|
+
---
|
|
89
|
+
|
|
90
|
+
## How to Transpile
|
|
91
|
+
|
|
92
|
+
### 1. Inspect the SWF structure
|
|
93
|
+
|
|
94
|
+
See what's inside the file before transpiling:
|
|
95
|
+
|
|
96
|
+
```bash
|
|
97
|
+
node src/cli.js game.swf --inspect
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
This prints a tree of parsed tags — frames, shapes, sounds, embedded scripts — without generating any output files.
|
|
101
|
+
|
|
102
|
+
### 2. View the transpiled JavaScript
|
|
103
|
+
|
|
104
|
+
Print the transpiled ActionScript (AVM1 + AVM2) to your terminal:
|
|
105
|
+
|
|
106
|
+
```bash
|
|
107
|
+
node src/cli.js game.swf --actionscript
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Redirect to a file for review:
|
|
111
|
+
|
|
112
|
+
```bash
|
|
113
|
+
node src/cli.js game.swf --actionscript > game.js
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
The output is self-contained ES2020 — class definitions, method bodies, and runtime stubs — parsed and validated against `acorn`.
|
|
117
|
+
|
|
118
|
+
### 3. Convert multiple movies for the browser
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
node src/cli.js -o out Swf/*.swf
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
---
|
|
125
|
+
|
|
126
|
+
## Running the Output
|
|
127
|
+
|
|
128
|
+
Open the generated `index.html` in a browser and keep its companion files and `assets/` directory together. Use `--actionscript` when you want to inspect the compiled script.
|
|
129
|
+
|
|
130
|
+
| File | Contents |
|
|
131
|
+
|---|---|
|
|
132
|
+
| `swflib.js` | Shared player with `__swoof_swflib.mountMovie(...)`, Flash APIs, AVM1 and AVM2 helpers, Canvas rendering, effects, input, and audio |
|
|
133
|
+
| `timeline-data.js` | Frames, scene labels, symbols, and geometry. CLI output packs timelines at 8 MiB when packing saves space. |
|
|
134
|
+
| `binary-data.js` | Original linked ByteArray payloads, retained for ActionScript code that reads or changes them |
|
|
135
|
+
| `bundle.js` | One shared-player call with movie metadata, compiled ActionScript, and compact class and namespace metadata |
|
|
136
|
+
| `assets/` | Images, sounds, and compiled embedded movies loaded on demand. Named children use paths such as `assets/preloader/preloader.js`. |
|
|
137
|
+
|
|
138
|
+
Every conversion using the same transpiler sources emits the same `swflib.js`. Each folder includes a copy for direct file playback. A web server can use one shared copy for its generated pages. Packed timelines use gzip in a classic JavaScript sidecar and open directly from disk in browsers with `DecompressionStream` gzip support. Use `--plain-timeline` for older browsers or to inspect a large timeline as text.
|
|
139
|
+
|
|
140
|
+
The shared AVM2 runtime registers classes and methods, initializes activation slots, and caches ordered property keys from each compiled block's namespace table. Compiled AVM1 scripts use shared enumeration and string helpers.
|
|
141
|
+
|
|
142
|
+
The emitted linkage table routes an unmodified embedded ByteArray straight to its compiled child movie. The runtime decodes the original payload on the first byte read, write, or fallback comparison.
|
|
143
|
+
|
|
144
|
+
Use `--omit-embedded-swf-bytes` for movies that pass their linked child resources directly to `Loader.loadBytes`. This keeps the compiled children and removes their original SWF bytes from the output. Direct byte access to those resources requires the regular export. Non-SWF binary assets and SWFs that could not be precompiled keep their data.
|
|
145
|
+
|
|
146
|
+
Swoof automatically precompiles referenced SWFs beside the main SWF when their filenames appear as literals in ActionScript or as imported assets. The export loads the generated JavaScript on demand.
|
|
147
|
+
|
|
148
|
+
- Use `--companion-swf movies/intro.swf` for a package-relative subfolder or a filename computed at runtime.
|
|
149
|
+
- Use `--companion-swf intro.swf=../shared/opening.swf` to map the movie’s requested URL to a file elsewhere. The file path is relative to the CLI’s working directory unless absolute.
|
|
150
|
+
- Use `--blank-companion-swf 'http://ads.example.test/preroll.swf'` for a transparent placeholder. It loads as a compiled two-frame clip and stops on its second frame. It has no source SWF or custom application events.
|
|
151
|
+
|
|
152
|
+
These options are repeatable. Explicit mappings also accept complete HTTP(S) URLs backed by local files. A mapping to a local `.js` file packages a movie factory. The script assigns a function to `document.currentScript._swoofMovieFactory` that returns a detached DisplayObject.
|
|
153
|
+
|
|
154
|
+
A source SWF can carry its local mappings in a sibling `<movie>.companions.json` file. The JSON object maps requested SWF URLs to paths inside the source directory. Explicit CLI mappings take precedence. Raze 2 uses this manifest to preserve its offline companion on ordinary rebuilds.
|
|
155
|
+
|
|
156
|
+
```sh
|
|
157
|
+
node src/cli.js Swf/raze-2.swf
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
AS3 `Loader.load` and AVM1 clip loading use these compiled companions, including with `--omit-embedded-swf-bytes`.
|
|
161
|
+
|
|
162
|
+
An unregistered SWF URL loads a small unavailable-movie animation from the shared runtime without a network request. The placeholder sends the normal load completion events, plays for one second, and then holds on frame 2. It exposes zero source bytes. Use an explicit mapping for the original movie or `--blank-companion-swf` for a transparent replacement.
|
|
163
|
+
|
|
164
|
+
---
|
|
165
|
+
|
|
166
|
+
## Running Tests
|
|
167
|
+
|
|
168
|
+
```bash
|
|
169
|
+
# Unit + property tests
|
|
170
|
+
npm test
|
|
171
|
+
|
|
172
|
+
# SWF corpus integration tests
|
|
173
|
+
npm run test:integration
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
---
|
|
177
|
+
|
|
178
|
+
## Project Layout
|
|
179
|
+
|
|
180
|
+
```
|
|
181
|
+
src/
|
|
182
|
+
cli.js # Entry point
|
|
183
|
+
parser/ # Binary SWF parser (bit-reader, swf-parser)
|
|
184
|
+
decoder/ # Tag decoder (shapes, fonts, sounds, DoABC, DoAction)
|
|
185
|
+
transpiler/
|
|
186
|
+
avm1/ # AVM1 ActionScript transpiler
|
|
187
|
+
avm2/ # AVM2 ActionScript 3 transpiler (abc-reader, avm2-transpiler)
|
|
188
|
+
cfg-structurer.js # Control-flow graph → structured JS (while/if/else)
|
|
189
|
+
actionscript.js # Coordinator: runs AVM1 + AVM2 transpilation
|
|
190
|
+
util/ # Diagnostics, bit utilities
|
|
191
|
+
Swf/ # Test corpus (27 Flash games)
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
---
|
|
195
|
+
|
|
196
|
+
## Status
|
|
197
|
+
|
|
198
|
+
| Feature | Status |
|
|
199
|
+
|---|---|
|
|
200
|
+
| SWF parsing (all tag types) | ✅ |
|
|
201
|
+
| AVM1 ActionScript transpilation | ✅ |
|
|
202
|
+
| AVM2 ActionScript 3 transpilation | ✅ |
|
|
203
|
+
| CFG structured control flow | ✅ |
|
|
204
|
+
| Timeline / display-list codegen | 🚧 In progress |
|
|
205
|
+
| Shape → Canvas 2D rendering | 🚧 In progress |
|
|
206
|
+
| Audio / sound playback | 🚧 In progress |
|
|
207
|
+
| HTML bundle output | Available through the CLI |
|
|
208
|
+
|
|
209
|
+
**Capability matrix** (shapes, morphs, tweens, swflib W/P/S audit, corpus needs): see [SUPPORT.md](./SUPPORT.md).
|
package/package.json
CHANGED
|
@@ -1,6 +1,26 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "swf2js",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "SWF-to-browser transpiler — converts compiled .swf files to self-contained HTML/JS bundles",
|
|
5
|
+
"license": "SEE LICENSE IN LICENSE-GPL",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"bin": {
|
|
8
|
+
"swf2js": "src/cli.js"
|
|
9
|
+
},
|
|
10
|
+
"scripts": {
|
|
11
|
+
"start": "node src/cli.js",
|
|
12
|
+
"test": "vitest --run",
|
|
13
|
+
"test:integration": "vitest --run --config vitest.integration.config.js"
|
|
14
|
+
},
|
|
15
|
+
"devDependencies": {
|
|
16
|
+
"fast-check": "^3.0.0",
|
|
17
|
+
"vitest": "^2.0.0"
|
|
18
|
+
},
|
|
19
|
+
"engines": {
|
|
20
|
+
"node": ">=20.0.0"
|
|
21
|
+
},
|
|
22
|
+
"dependencies": {
|
|
23
|
+
"acorn": "^8.19.0",
|
|
24
|
+
"lzma-js": "^1.0.1"
|
|
25
|
+
}
|
|
26
|
+
}
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* swoof — SWF-to-browser transpiler CLI
|
|
4
|
+
* Usage: swf2js [options] <file.swf> ...
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { readFileSync, globSync, existsSync, statSync } from 'fs';
|
|
8
|
+
import { dirname, resolve, isAbsolute } from 'path';
|
|
9
|
+
import { parse } from './parser/swf-parser.js';
|
|
10
|
+
import { decode } from './decoder/tag-decoder.js';
|
|
11
|
+
import { prettyPrint } from './pretty-printer/pretty-printer.js';
|
|
12
|
+
import { transpileActionScript } from './transpiler/actionscript.js';
|
|
13
|
+
import { precompileCompanionSwfs, precompileEmbeddedSwfs } from './emitter/embedded-swf.js';
|
|
14
|
+
import { emit, backgroundFromTags } from './emitter/bundle-emitter.js';
|
|
15
|
+
import { DiagnosticsCollector } from './util/diagnostics.js';
|
|
16
|
+
import { Logger } from './util/logger.js';
|
|
17
|
+
|
|
18
|
+
const VERSION = '0.1.1';
|
|
19
|
+
|
|
20
|
+
// --- Argument parsing ---
|
|
21
|
+
const args = process.argv.slice(2);
|
|
22
|
+
|
|
23
|
+
if (args.length === 0 || args.includes('--help') || args.includes('-h')) {
|
|
24
|
+
printUsage();
|
|
25
|
+
process.exit(0);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
if (args.includes('--version') || args.includes('-v')) {
|
|
29
|
+
process.stdout.write(`swoof ${VERSION}\n`);
|
|
30
|
+
process.exit(0);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const opts = {
|
|
34
|
+
/** @type {string|null} null = place each bundle beside its SWF */
|
|
35
|
+
outputDir: null,
|
|
36
|
+
verbose: false,
|
|
37
|
+
warnUnknown: false,
|
|
38
|
+
inspect: false, // --inspect: pretty-print parse output instead of transpiling
|
|
39
|
+
timelineDataMode: 'auto',
|
|
40
|
+
omitEmbeddedSwfBytes: false,
|
|
41
|
+
companionSwfUrls: [],
|
|
42
|
+
blankCompanionSwfUrls: [],
|
|
43
|
+
actionscript: false, // --actionscript: print transpiled ActionScript JS to stdout
|
|
44
|
+
inputPatterns: [],
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
for (let i = 0; i < args.length; i++) {
|
|
48
|
+
if (args[i] === '--output-dir' || args[i] === '-o') {
|
|
49
|
+
opts.outputDir = args[++i];
|
|
50
|
+
} else if (args[i] === '--verbose') {
|
|
51
|
+
opts.verbose = true;
|
|
52
|
+
} else if (args[i] === '--warn-unknown') {
|
|
53
|
+
opts.warnUnknown = true;
|
|
54
|
+
} else if (args[i] === '--inspect') {
|
|
55
|
+
opts.inspect = true;
|
|
56
|
+
} else if (args[i] === '--actionscript') {
|
|
57
|
+
opts.actionscript = true;
|
|
58
|
+
} else if (args[i] === '--pack-timeline') {
|
|
59
|
+
opts.timelineDataMode = 'packed';
|
|
60
|
+
} else if (args[i] === '--plain-timeline') {
|
|
61
|
+
opts.timelineDataMode = 'plain';
|
|
62
|
+
} else if (args[i] === '--omit-embedded-swf-bytes') {
|
|
63
|
+
opts.omitEmbeddedSwfBytes = true;
|
|
64
|
+
} else if (args[i] === '--companion-swf') {
|
|
65
|
+
const url = args[++i];
|
|
66
|
+
if (!url || url.startsWith('--')) {
|
|
67
|
+
process.stderr.write('swoof: --companion-swf requires a package-relative .swf path or <url>=<local-file>\n');
|
|
68
|
+
process.exit(1);
|
|
69
|
+
}
|
|
70
|
+
opts.companionSwfUrls.push(url);
|
|
71
|
+
} else if (args[i] === '--blank-companion-swf') {
|
|
72
|
+
const url = args[++i];
|
|
73
|
+
if (!url || url.startsWith('--')) {
|
|
74
|
+
process.stderr.write('swoof: --blank-companion-swf requires a SWF URL\n');
|
|
75
|
+
process.exit(1);
|
|
76
|
+
}
|
|
77
|
+
opts.blankCompanionSwfUrls.push(url);
|
|
78
|
+
} else if (!args[i].startsWith('--')) {
|
|
79
|
+
opts.inputPatterns.push(args[i]);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
if (opts.inputPatterns.length === 0) {
|
|
84
|
+
process.stderr.write('swoof: no input files specified\n');
|
|
85
|
+
process.exit(1);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const inputFiles = expandInputs(opts.inputPatterns);
|
|
89
|
+
if (inputFiles.length === 0) {
|
|
90
|
+
process.stderr.write(`swoof: no files matched: ${opts.inputPatterns.join(' ')}\n`);
|
|
91
|
+
process.exit(1);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const logger = new Logger({ verbose: opts.verbose, warnUnknown: opts.warnUnknown });
|
|
95
|
+
|
|
96
|
+
// --- Process each file ---
|
|
97
|
+
let anyFailed = false;
|
|
98
|
+
/** @type {Set<string>} */
|
|
99
|
+
const usedBundleNames = new Set();
|
|
100
|
+
|
|
101
|
+
for (const filePath of inputFiles) {
|
|
102
|
+
try {
|
|
103
|
+
logger.verboseLog(`Processing ${filePath}`);
|
|
104
|
+
const bytes = new Uint8Array(readFileSync(filePath));
|
|
105
|
+
const diag = new DiagnosticsCollector();
|
|
106
|
+
|
|
107
|
+
let diagIdx = 0;
|
|
108
|
+
const flushDiags = () => {
|
|
109
|
+
const all = diag.all();
|
|
110
|
+
for (; diagIdx < all.length; diagIdx++) {
|
|
111
|
+
const d = all[diagIdx];
|
|
112
|
+
if (d.level === 'error') logger.error(`${filePath}: ${d.message}`);
|
|
113
|
+
else logger.warn(`${filePath}: ${d.message}`);
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
const { doc } = await parse(bytes, diag);
|
|
118
|
+
flushDiags();
|
|
119
|
+
|
|
120
|
+
if (diag.hasErrors()) {
|
|
121
|
+
logger.error(`${filePath}: parse failed — skipping`);
|
|
122
|
+
anyFailed = true;
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
if (opts.inspect) {
|
|
127
|
+
const { symbolTable } = decode(doc, diag);
|
|
128
|
+
flushDiags();
|
|
129
|
+
process.stdout.write(prettyPrint(doc, symbolTable) + '\n');
|
|
130
|
+
logger.verboseLog(`${filePath}: ${doc.tags.length} tags, ${symbolTable.ids().length} characters`);
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const { tags, symbolTable } = decode(doc, diag);
|
|
135
|
+
const asResult = transpileActionScript(tags, diag, {
|
|
136
|
+
sharedAvm1Runtime: !opts.actionscript,
|
|
137
|
+
sharedAvm2Runtime: !opts.actionscript,
|
|
138
|
+
swfVersion: doc.header.version,
|
|
139
|
+
});
|
|
140
|
+
flushDiags();
|
|
141
|
+
|
|
142
|
+
if (opts.actionscript) {
|
|
143
|
+
process.stdout.write(asResult.fullJs + '\n');
|
|
144
|
+
if (diag.hasErrors()) anyFailed = true;
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// Default: bundle folder next to the SWF. -o overrides the parent directory.
|
|
149
|
+
const outParent = opts.outputDir != null
|
|
150
|
+
? opts.outputDir
|
|
151
|
+
: dirname(resolve(filePath));
|
|
152
|
+
|
|
153
|
+
const embeddedSwfs = await precompileEmbeddedSwfs(symbolTable, diag);
|
|
154
|
+
const companionSwfs = await precompileCompanionSwfs(filePath, opts.companionSwfUrls, diag,
|
|
155
|
+
{ tags, actionScript: asResult, embeddedSwfs }, opts.blankCompanionSwfUrls);
|
|
156
|
+
const result = emit(
|
|
157
|
+
{
|
|
158
|
+
header: doc.header,
|
|
159
|
+
tags,
|
|
160
|
+
symbolTable,
|
|
161
|
+
actionScript: asResult,
|
|
162
|
+
embeddedSwfs,
|
|
163
|
+
companionSwfs,
|
|
164
|
+
backgroundColor: backgroundFromTags(tags),
|
|
165
|
+
},
|
|
166
|
+
filePath,
|
|
167
|
+
outParent,
|
|
168
|
+
diag,
|
|
169
|
+
{ usedNames: usedBundleNames, externalTimelineData: true, timelineDataMode: opts.timelineDataMode,
|
|
170
|
+
omitEmbeddedSwfBytes: opts.omitEmbeddedSwfBytes }
|
|
171
|
+
);
|
|
172
|
+
flushDiags();
|
|
173
|
+
|
|
174
|
+
if (diag.hasErrors()) {
|
|
175
|
+
anyFailed = true;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const lineCount = asResult.fullJs ? asResult.fullJs.split('\n').length : 0;
|
|
179
|
+
logger.info(`${filePath}: → ${result.bundleDir}/`);
|
|
180
|
+
logger.info(
|
|
181
|
+
` ${doc.tags.length} tags, ${symbolTable.ids().length} characters, ${result.assetCount} assets`
|
|
182
|
+
);
|
|
183
|
+
logger.info(
|
|
184
|
+
` ActionScript: ${asResult.avm1Scripts.length} AVM1, ${asResult.avm2Blocks.length} AVM2 (${lineCount} lines JS)`
|
|
185
|
+
);
|
|
186
|
+
|
|
187
|
+
} catch (err) {
|
|
188
|
+
logger.error(`${filePath}: unrecoverable error — ${err.message}`);
|
|
189
|
+
anyFailed = true;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
process.exit(anyFailed ? 1 : 0);
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Expand CLI inputs: literal paths plus glob patterns (e.g. Swf/*.swf).
|
|
197
|
+
* Shell may already expand globs; we still expand so quoted patterns work.
|
|
198
|
+
* @param {string[]} patterns
|
|
199
|
+
* @returns {string[]}
|
|
200
|
+
*/
|
|
201
|
+
function expandInputs(patterns) {
|
|
202
|
+
/** @type {string[]} */
|
|
203
|
+
const out = [];
|
|
204
|
+
for (const pattern of patterns) {
|
|
205
|
+
if (!/[*?[{]/.test(pattern)) {
|
|
206
|
+
out.push(pattern);
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
let matches = [];
|
|
210
|
+
try {
|
|
211
|
+
matches = globSync(pattern, { windowsPathsNoEscape: true });
|
|
212
|
+
} catch {
|
|
213
|
+
matches = [];
|
|
214
|
+
}
|
|
215
|
+
// Also try cwd-relative if pattern was absolute-looking miss
|
|
216
|
+
if (matches.length === 0 && !isAbsolute(pattern)) {
|
|
217
|
+
try {
|
|
218
|
+
matches = globSync(pattern, { cwd: process.cwd(), windowsPathsNoEscape: true });
|
|
219
|
+
} catch {
|
|
220
|
+
matches = [];
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
for (const m of matches) {
|
|
224
|
+
try {
|
|
225
|
+
if (existsSync(m) && statSync(m).isFile()) out.push(m);
|
|
226
|
+
} catch {
|
|
227
|
+
/* skip */
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
// De-dupe while preserving order (shell + our expand can overlap)
|
|
232
|
+
return [...new Set(out)];
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function printUsage() {
|
|
236
|
+
process.stdout.write(`
|
|
237
|
+
swoof ${VERSION} — SWF-to-browser transpiler
|
|
238
|
+
|
|
239
|
+
Usage:
|
|
240
|
+
swf2js [options] <file.swf> [file.swf ...]
|
|
241
|
+
swf2js [options] <glob> e.g. Swf/*.swf
|
|
242
|
+
|
|
243
|
+
By default each SWF writes a folder next to that file (same directory):
|
|
244
|
+
swf2js demos/neon-grid.swf → demos/neon-grid/index.html + bundle.js + assets/
|
|
245
|
+
swf2js demos/*.swf → demos/<name>/ for each match
|
|
246
|
+
|
|
247
|
+
Options:
|
|
248
|
+
--output-dir, -o <path> Parent directory for output folders (default: beside each SWF)
|
|
249
|
+
--inspect Pretty-print parse output instead of emitting
|
|
250
|
+
--actionscript Print transpiled ActionScript JS to stdout
|
|
251
|
+
--pack-timeline Pack timeline data even for small movies (default: auto at 8 MiB)
|
|
252
|
+
--plain-timeline Write readable timeline data for inspection or older browsers
|
|
253
|
+
--omit-embedded-swf-bytes Keep compiled child movies and omit their original ByteArray data
|
|
254
|
+
--companion-swf <path> Explicitly compile a package-relative SWF (repeatable)
|
|
255
|
+
--companion-swf <url>=<file>
|
|
256
|
+
Map a SWF URL to a local SWF or JavaScript movie factory
|
|
257
|
+
--blank-companion-swf <url>
|
|
258
|
+
Map a SWF URL to an empty compiled clip
|
|
259
|
+
--verbose Print per-tag diagnostics
|
|
260
|
+
--warn-unknown Print warnings for unrecognized tags/opcodes
|
|
261
|
+
--version, -v Print version
|
|
262
|
+
--help, -h Print this help
|
|
263
|
+
|
|
264
|
+
Examples:
|
|
265
|
+
swf2js demos/neon-grid.swf
|
|
266
|
+
swf2js demos/*.swf -o out/
|
|
267
|
+
swf2js demos/neon-grid.swf --inspect
|
|
268
|
+
swf2js demos/neon-grid.swf --actionscript
|
|
269
|
+
|
|
270
|
+
Demo files are available in the source checkout and are not included in the npm package.
|
|
271
|
+
`.trimStart());
|
|
272
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Decode DefineButton and DefineButton2 state records and actions.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { BitReader } from '../parser/bit-reader.js';
|
|
6
|
+
import { decodeFilters, readColorTransform } from './tag-decoder.js';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* @param {Uint8Array} rawData
|
|
10
|
+
* @param {number} version - 1 or 2
|
|
11
|
+
* @returns {{ characterId: number, trackAsMenu: boolean, actionOffset: number, up?: object, over?: object, down?: object, hit?: object, hitStates: object[], stateRecords: object, states: object[], actions: object[] }}
|
|
12
|
+
*/
|
|
13
|
+
export function decodeButton(rawData, version = 2) {
|
|
14
|
+
const r = new BitReader(rawData);
|
|
15
|
+
const characterId = r.readUI16();
|
|
16
|
+
let trackAsMenu = false;
|
|
17
|
+
let actionOffset = 0;
|
|
18
|
+
let actionOffsetPosition = -1;
|
|
19
|
+
if (version >= 2) {
|
|
20
|
+
trackAsMenu = !!(r.readUI8() & 1);
|
|
21
|
+
actionOffsetPosition = r.bytePos;
|
|
22
|
+
actionOffset = r.readUI16(); // relative to the start of this field
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** @type {{ characterId: number, matrix: object, depth: number }|undefined} */
|
|
26
|
+
let up, over, down, hit;
|
|
27
|
+
const states = [];
|
|
28
|
+
const stateRecords = { up: [], over: [], down: [], hit: [] };
|
|
29
|
+
for (;;) {
|
|
30
|
+
if (r.eof) break;
|
|
31
|
+
const flags = r.readUI8();
|
|
32
|
+
if (flags === 0) break; // end of button records
|
|
33
|
+
const stateUp = !!(flags & 0x01);
|
|
34
|
+
const characterId = r.readUI16();
|
|
35
|
+
const depth = r.readUI16();
|
|
36
|
+
const matrix = r.readMatrix();
|
|
37
|
+
const item = { characterId, matrix, depth, flags };
|
|
38
|
+
if (version >= 2) {
|
|
39
|
+
item.colorTransform = readColorTransform(r, true);
|
|
40
|
+
if (flags & 0x10) item.filters = decodeFilters(r);
|
|
41
|
+
if (flags & 0x20) item.blendMode = r.readUI8();
|
|
42
|
+
}
|
|
43
|
+
states.push(item);
|
|
44
|
+
if (stateUp) { stateRecords.up.push(item); if (!up) up = item; }
|
|
45
|
+
if (flags & 0x02) { stateRecords.over.push(item); if (!over) over = item; }
|
|
46
|
+
if (flags & 0x04) { stateRecords.down.push(item); if (!down) down = item; }
|
|
47
|
+
if (flags & 0x08) { stateRecords.hit.push(item); if (!hit) hit = item; }
|
|
48
|
+
}
|
|
49
|
+
let actions = [];
|
|
50
|
+
if (version >= 2 && actionOffset) {
|
|
51
|
+
actions = decodeButtonActions(rawData, actionOffsetPosition + actionOffset);
|
|
52
|
+
} else if (version === 1 && !r.eof) {
|
|
53
|
+
// DefineButton stores ACTIONRECORDs immediately after CharacterEndFlag.
|
|
54
|
+
actions = decodeButtonV1Actions(rawData, r.bytePos);
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
characterId,
|
|
58
|
+
trackAsMenu,
|
|
59
|
+
actionOffset,
|
|
60
|
+
up,
|
|
61
|
+
over,
|
|
62
|
+
down,
|
|
63
|
+
hit,
|
|
64
|
+
hitStates: stateRecords.hit,
|
|
65
|
+
stateRecords,
|
|
66
|
+
states,
|
|
67
|
+
actions,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function decodeButtonV1Actions(rawData, actionStart) {
|
|
72
|
+
if (rawData[actionStart] === 0) return [];
|
|
73
|
+
let actionEnd = actionStart;
|
|
74
|
+
for (;;) {
|
|
75
|
+
if (actionEnd >= rawData.length) throw new Error('DefineButton action list is missing ActionEnd');
|
|
76
|
+
const opcode = rawData[actionEnd++];
|
|
77
|
+
if (opcode === 0) break;
|
|
78
|
+
if (opcode >= 0x80) {
|
|
79
|
+
if (actionEnd + 2 > rawData.length) throw new Error('Truncated DefineButton action header');
|
|
80
|
+
const length = rawData[actionEnd] | (rawData[actionEnd + 1] << 8);
|
|
81
|
+
actionEnd += 2 + length;
|
|
82
|
+
if (actionEnd > rawData.length) throw new Error('Truncated DefineButton action payload');
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return [{
|
|
86
|
+
size: actionEnd - actionStart,
|
|
87
|
+
conditions: { overDownToOverUp: true },
|
|
88
|
+
bytecodeOffset: actionStart,
|
|
89
|
+
bytecode: rawData.slice(actionStart, actionEnd),
|
|
90
|
+
}];
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function decodeButtonActions(rawData, actionStart) {
|
|
94
|
+
if (actionStart < 0 || actionStart > rawData.length) {
|
|
95
|
+
throw new Error(`DefineButton2 ActionOffset points outside tag (${actionStart})`);
|
|
96
|
+
}
|
|
97
|
+
const r = new BitReader(rawData);
|
|
98
|
+
r.seek(actionStart);
|
|
99
|
+
const actions = [];
|
|
100
|
+
while (!r.eof) {
|
|
101
|
+
const recordStart = r.bytePos;
|
|
102
|
+
if (recordStart + 4 > rawData.length) throw new Error('Truncated BUTTONCONDACTION header');
|
|
103
|
+
const size = r.readUI16();
|
|
104
|
+
const conditionBits = r.readUB(16);
|
|
105
|
+
r.align();
|
|
106
|
+
const nextRecord = size ? recordStart + size : rawData.length;
|
|
107
|
+
if (nextRecord < r.bytePos + 1 || nextRecord > rawData.length) {
|
|
108
|
+
throw new Error(`Invalid BUTTONCONDACTION size ${size} at ${recordStart}`);
|
|
109
|
+
}
|
|
110
|
+
const bytecodeOffset = r.bytePos;
|
|
111
|
+
const actionBytes = r.readBytes(nextRecord - bytecodeOffset - 1);
|
|
112
|
+
const endFlag = r.readUI8();
|
|
113
|
+
if (endFlag !== 0) throw new Error(`Invalid BUTTONCONDACTION end flag ${endFlag}`);
|
|
114
|
+
actions.push({
|
|
115
|
+
size,
|
|
116
|
+
conditions: {
|
|
117
|
+
idleToOverDown: !!(conditionBits & 0x8000),
|
|
118
|
+
outDownToIdle: !!(conditionBits & 0x4000),
|
|
119
|
+
outDownToOverDown: !!(conditionBits & 0x2000),
|
|
120
|
+
overDownToOutDown: !!(conditionBits & 0x1000),
|
|
121
|
+
overDownToOverUp: !!(conditionBits & 0x0800),
|
|
122
|
+
overUpToOverDown: !!(conditionBits & 0x0400),
|
|
123
|
+
overUpToIdle: !!(conditionBits & 0x0200),
|
|
124
|
+
idleToOverUp: !!(conditionBits & 0x0100),
|
|
125
|
+
keyPress: (conditionBits >> 1) & 0x7f,
|
|
126
|
+
overDownToIdle: !!(conditionBits & 0x0001),
|
|
127
|
+
},
|
|
128
|
+
bytecodeOffset,
|
|
129
|
+
bytecode: actionBytes,
|
|
130
|
+
});
|
|
131
|
+
if (size === 0) break;
|
|
132
|
+
if (nextRecord <= recordStart) throw new Error('BUTTONCONDACTION size does not advance');
|
|
133
|
+
r.seek(nextRecord);
|
|
134
|
+
}
|
|
135
|
+
return actions;
|
|
136
|
+
}
|