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.
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,2082 @@
1
+ /**
2
+ * @fileoverview AVM1_Transpiler — converts AVM1 bytecode to JavaScript.
3
+ *
4
+ * AVM1 is a stack-based VM. We transpile by:
5
+ * 1. Reading the bytecode instruction stream
6
+ * 2. Maintaining a virtual operand stack of JS expressions (strings)
7
+ * 3. Emitting JS statements when instructions consume the stack
8
+ *
9
+ * The output is a JS function body string suitable for wrapping in:
10
+ * runClipScript(root, function () { <output> })
11
+ */
12
+
13
+ import { OP, HAS_LENGTH } from './avm1-opcodes.js';
14
+ import { DiagnosticsCollector } from '../../util/diagnostics.js';
15
+ import { structureCfg } from '../cfg-structurer.js';
16
+ import { DF2, materializePreloadAliases, createUsageProfile, noteUsage, flashPropToJs, isAvm1DisplayMemberName } from './avm1-ir.js';
17
+ import { rewriteAvm1Js } from './avm1-rewrite.js';
18
+ import { _avm1Substring, _avm1RandomNumber, _avm1CharToCode, _avm1CodeToChar } from '../../runtime/avm1-runtime.js';
19
+ export { AVM1_RUNTIME_STUB, dispatchAvm1ClipKeyEvent, hitTestAvm1ClipGeometry, hitTestAvm1ShapeGeometry } from '../../runtime/avm1-runtime.js';
20
+
21
+ // Push value types in the AVM1 Push opcode
22
+ const PUSH_TYPE = {
23
+ STRING: 0,
24
+ FLOAT: 1,
25
+ NULL: 2,
26
+ UNDEFINED: 3,
27
+ REGISTER: 4,
28
+ BOOLEAN: 5,
29
+ DOUBLE: 6,
30
+ INTEGER: 7,
31
+ CONSTANT8: 8,
32
+ CONSTANT16:9,
33
+ };
34
+
35
+ function isFrameWait(op) {
36
+ return op === OP.WaitForFrame || op === OP.WaitForFrame2;
37
+ }
38
+
39
+ function decodeAvm1String(bytes) {
40
+ const data = Uint8Array.from(bytes);
41
+ if (typeof TextDecoder !== 'undefined') {
42
+ try { return new TextDecoder('utf-8', { fatal: true }).decode(data); } catch (_) {}
43
+ }
44
+ return Array.from(data, (byte) => String.fromCharCode(byte)).join('');
45
+ }
46
+
47
+ /**
48
+ * Transpile an AVM1 bytecode buffer to a JavaScript function body string.
49
+ *
50
+ * @param {Uint8Array} bytecode
51
+ * @param {DiagnosticsCollector} diagnostics
52
+ * @param {object} [opts]
53
+ * @param {string[]} [opts.constantPool] - pre-loaded constant pool from ConstantPool tag
54
+ * @param {string} [opts.label] - clip/script label for shape comments
55
+ * @param {number} [opts.entryOffset=0] - initial PC within an action stream with a linked prefix
56
+ * @param {boolean} [opts.timelineDeclarations=false] - declare top-level variables on the active movie clip
57
+ * @param {boolean} [opts.spriteFrameScope=false] - retain an authored frame's clip for bare variable fallback in its functions
58
+ * @param {boolean} [opts.clipActionScope=false] - resolve clip handlers' variables through the clip and globals
59
+ * @param {boolean} [opts.sharedAvm1Runtime=false] - use the shared player budget helper
60
+ * @returns {string}
61
+ */
62
+ export function transpileAvm1(bytecode, diagnostics, opts = {}) {
63
+ return transpileAvm1WithMeta(bytecode, diagnostics, opts).js;
64
+ }
65
+
66
+ /**
67
+ * Pass 1 (decode+CFG) + Pass 2 (rewrite/shapes).
68
+ *
69
+ * @param {Uint8Array} bytecode
70
+ * @param {DiagnosticsCollector} diagnostics
71
+ * @param {object} [opts]
72
+ * @returns {{ js: string, profile: object, shape: object|null }}
73
+ */
74
+ export function transpileAvm1WithMeta(bytecode, diagnostics, opts = {}) {
75
+ const ctx = new Avm1Context(bytecode, diagnostics, opts.constantPool ?? [], false, opts.sharedAvm1Runtime, opts.nameSpellings);
76
+ ctx.entryOffset = opts.entryOffset ?? 0;
77
+ ctx._scopeLookup = opts.scopeLookup;
78
+ ctx._clipActionScope = opts.clipActionScope;
79
+ ctx._timelineDeclarations = opts.timelineDeclarations;
80
+ ctx._spriteFrameScope = opts.spriteFrameScope;
81
+ ctx.useRuntimeNumbers = opts.useRuntimeNumbers || opts.sharedAvm1Runtime;
82
+ const rawJs = ctx.transpile();
83
+ const rewritten = rewriteAvm1Js(rawJs, { label: opts.label || 'script', profile: ctx.profile });
84
+ return {
85
+ js: rewritten.js,
86
+ profile: ctx.profile,
87
+ shape: rewritten.shape,
88
+ };
89
+ }
90
+
91
+ class Avm1Context {
92
+ /**
93
+ * @param {Uint8Array} bytecode
94
+ * @param {DiagnosticsCollector} diagnostics
95
+ * @param {string[]} constantPool
96
+ */
97
+ constructor(bytecode, diagnostics, constantPool, inheritConstantPool = false, sharedAvm1Runtime = false, nameSpellings) {
98
+ this.bytes = bytecode;
99
+ this.entryOffset = 0;
100
+ this.diag = diagnostics;
101
+ this.initialConstantPool = constantPool?.slice() ?? null;
102
+ this.constantPool = this.initialConstantPool;
103
+ this.inheritConstantPool = inheritConstantPool;
104
+ this.sharedAvm1Runtime = sharedAvm1Runtime;
105
+ this.nameSpellings = nameSpellings;
106
+ /** @type {string[]} - virtual operand stack (JS expression strings) */
107
+ this.stack = [];
108
+ /** @type {string[]} - emitted JS lines */
109
+ this.lines = [];
110
+ /** @type {Map<number, string>} - register index → JS expression */
111
+ this.registerAliases = new Map();
112
+ this.registerCount = 4; // default; DefineFunction2 overrides
113
+ /** @type {Set<string>} - DefineLocal bindings in this scope */
114
+ this.locals = new Set();
115
+ this.localIdentifiers = new Map();
116
+ this.localIdentifierNames = new Set();
117
+ this.scopeLocalBindings = new Map();
118
+ /** @type {Set<string>} - named AVM1 functions defined in this scope */
119
+ this.functionNames = new Set();
120
+ this._tmpCount = 0;
121
+ this._labelMap = new Map(); // byte offset → label name
122
+ this._pendingLabels = new Set();
123
+ this._needsRegisters = false;
124
+ this._dynamicStack = false;
125
+ this._stackDepthConflict = false;
126
+ this._dynamicPopCount = 0;
127
+ /** Pass-1 usage profile for Pass-2 shape inference */
128
+ this.profile = createUsageProfile();
129
+ }
130
+
131
+ /**
132
+ * @param {string[]} [prependLines]
133
+ * @returns {string}
134
+ */
135
+ transpile(prependLines = []) {
136
+ const headerLines = [...prependLines];
137
+ if (!this.inheritConstantPool) {
138
+ headerLines.unshift(`var _constantPool = ${JSON.stringify(this.initialConstantPool ?? [])};`);
139
+ }
140
+ const { instructions, blockStarts } = this._collectReachable();
141
+ this._hasWith = this._inheritsWith || instructions.some(({ op }) => op === OP.With);
142
+ this._deletesLocals = instructions.some(({ op }) => op === OP.Delete2);
143
+ const hasTry = instructions.some(({ op }) => op === OP.Try);
144
+ this._usesSetTarget = this._inlineTry || hasTry || instructions.some(({ op }) => op === OP.SetTarget || op === OP.SetTarget2);
145
+ this._spriteFrameScope = this._spriteFrameScope && !this._hasWith && !this._usesSetTarget;
146
+ this._needsTargetBase = !!this._formalNames && this._usesSetTarget;
147
+ this._dynamicStack = this._dynamicStack || this._inlineTry || hasTry;
148
+
149
+ if (instructions.length === 0) {
150
+ return cleanupAvm1Js(headerLines.join('\n'));
151
+ }
152
+
153
+ const rawBlocks = this._splitBasicBlocks(instructions, blockStarts);
154
+ const entryPools = this._hasWith ? new Map() : this._findEntryPools(rawBlocks);
155
+ const enclosingLocals = new Set(this.locals);
156
+ let { blocks, maxSpill } = this._simulateBlocks(rawBlocks, entryPools);
157
+
158
+ // AVM1 permits branches into the middle of ActionPush payloads. Those
159
+ // paths can join with different operand-stack depths, where static stack
160
+ // simulation would otherwise substitute `undefined` and corrupt control
161
+ // flow. Re-emit those scripts with an activation-local runtime stack.
162
+ if (this._stackDepthConflict) {
163
+ this._dynamicStack = true;
164
+ this._stackDepthConflict = false;
165
+ this._tmpCount = 0;
166
+ this._dynamicPopCount = 0;
167
+ this.locals = enclosingLocals;
168
+ this.functionNames.clear();
169
+ ({ blocks, maxSpill } = this._simulateBlocks(rawBlocks, entryPools));
170
+ }
171
+
172
+ if (maxSpill > 0) {
173
+ const stackVars = Array.from({ length: maxSpill }, (_, k) => `_s${k}`);
174
+ headerLines.push(`var ${stackVars.join(', ')};`);
175
+ }
176
+ if (!this._inlineTry && this._needsRegisters) {
177
+ headerLines.unshift(`var _registers = new Array(${this.registerCount});`);
178
+ }
179
+ if (!this._inlineTry) {
180
+ if (this._formalNames) {
181
+ headerLines.push('var _avm1Locals = _avm1CreateLocalScope(_capturedLocals);');
182
+ } else if (this._spriteFrameScope && instructions.some(({ op }) => op === OP.DefineFunction || op === OP.DefineFunction2)) {
183
+ headerLines.push('var _avm1Locals = _avm1CreateSpriteFrameScope(this);');
184
+ } else {
185
+ headerLines.push('var _avm1Locals = Object.create(null);');
186
+ }
187
+ }
188
+ if (this._needsTargetBase) headerLines.push('var _avm1TargetBase = _avm1ClosureTargetBase(_capturedTargetBase, this);');
189
+ if (this._usesSetTarget && !this._inlineTry) headerLines.push(`var _avm1Target = ${this._targetBase()};`);
190
+ if (!this._inlineTry && (this._hasWith || hasTry)) {
191
+ headerLines.push(this._capturesWith ? 'var _avm1With = _capturedWith.slice();' : 'var _avm1With = [];');
192
+ }
193
+ if (!this._inlineTry && (this._hasWith || hasTry || this._deletesLocals || this._dynamicLocalLookup ||
194
+ instructions.some(({ op }) => op === OP.NewObject || op === OP.DefineFunction || op === OP.DefineFunction2))) {
195
+ for (const [name, binding] of this.scopeLocalBindings) {
196
+ if (this._formalNames && !this._formalNames.includes(name)) continue;
197
+ headerLines.push(`_avm1DefineLocal(_avm1Locals, ${JSON.stringify(name)}, function () { return ${binding}; }, function (_v) { ${binding} = _v; });`);
198
+ }
199
+ }
200
+ if (this._dynamicStack && !this._inlineTry) headerLines.push('var _avm1Stack = [];');
201
+ if (!this._dynamicStack && instructions.some(({ op }) => op === OP.Enumerate || op === OP.Enumerate2)) {
202
+ headerLines.push('var _stack = [];');
203
+ }
204
+
205
+ // JavaScript cannot be preempted in the middle of a synchronous AVM1
206
+ // handler. Count basic-block visits so malformed or non-terminating SWF
207
+ // loops fail out and return control to the browser event loop.
208
+ if (!this._inlineTry) {
209
+ if (this.sharedAvm1Runtime) headerLines.push('var _avm1CheckBudget = _avm1BudgetGuard();');
210
+ else headerLines.push(
211
+ `var _avm1Budget = 100000;`,
212
+ `function _avm1CheckBudget(pc) { if (--_avm1Budget < 0) throw new Error('AVM1 execution limit exceeded at bytecode offset 0x' + pc.toString(16)); }`
213
+ );
214
+ }
215
+ for (const block of blocks) block.stmts.unshift(`_avm1CheckBudget(${block.id});`);
216
+
217
+ const section = this._sectionExit || '_avm1End';
218
+ const implicitExit = `break ${section};`;
219
+ let structuredLines = this._dynamicStack || this._hasWith
220
+ ? this._emitDispatcher(blocks, this.entryOffset)
221
+ : structureCfg(blocks, this.entryOffset, implicitExit, () => this._emitDispatcher(blocks, this.entryOffset));
222
+ if (structuredLines[structuredLines.length - 1] === implicitExit) structuredLines.pop();
223
+ if (structuredLines.some(line => line.trim() === implicitExit)) {
224
+ structuredLines = [`${section}: {`, ...structuredLines.map(line => ' ' + line), '}'];
225
+ }
226
+ return cleanupAvm1Js([...headerLines, ...structuredLines].join('\n'));
227
+ }
228
+
229
+ _emitDispatcher(blocks, entryId) {
230
+ if (!blocks.length) return [];
231
+ const byId = new Map(blocks.map(block => [block.id, block]));
232
+ const declaration = this._inlineTry ? 'let' : 'var';
233
+ const label = this._inlineTry ? `_avm1Dispatch${this._sectionExit}` : '_avm1Dispatch';
234
+ const lines = [`${declaration} _avm1Pc = ${entryId};`, `${label}: while (_avm1Pc !== -1) {`];
235
+ if (this._hasWith) {
236
+ const base = this._inlineTry ? '_avm1WithBase' : '0';
237
+ lines.push(
238
+ ` while (_avm1With.length > ${base} && _avm1Pc >= _avm1With[_avm1With.length - 1].end) {`,
239
+ ' var _avm1WithFrame = _avm1With.pop();',
240
+ ' _avm1Pc = _avm1WithFrame.end;',
241
+ ' _constantPool = _avm1WithFrame.pool;',
242
+ );
243
+ if (this._usesSetTarget) lines.push(' _avm1Target = _avm1WithFrame.target;');
244
+ if (this._catchPlayback) lines.push(' _avm1PlaybackTarget = _avm1WithFrame.playbackTarget;');
245
+ lines.push(' }');
246
+ }
247
+ lines.push(' switch (_avm1Pc) {');
248
+ for (const block of blocks) {
249
+ lines.push(` case ${block.id}: {`);
250
+ for (const stmt of block.stmts) lines.push(` ${stmt}`);
251
+ if (block.term === 'jump' || block.term === 'fallthrough') {
252
+ const next = block.next != null && byId.has(block.next) ? block.next : -1;
253
+ lines.push(` _avm1Pc = ${next}; break;`);
254
+ } else if (block.term === 'branch') {
255
+ const t = block.trueTarget != null && byId.has(block.trueTarget) ? block.trueTarget : -1;
256
+ const f = block.falseTarget != null && byId.has(block.falseTarget) ? block.falseTarget : -1;
257
+ lines.push(` _avm1Pc = (${block.cond || 'false'}) ? ${t} : ${f}; break;`);
258
+ } else {
259
+ if (block.term !== 'return' && block.term !== 'throw') lines.push(' _avm1Pc = -1;');
260
+ lines.push(' break;');
261
+ }
262
+ lines.push(' }');
263
+ }
264
+ lines.push(' default: _avm1Pc = -1; break;', ' }', '}');
265
+ if (this._inlineTry && this._hasWith) {
266
+ return [
267
+ 'const _avm1WithBase = _avm1With.length;',
268
+ 'try {',
269
+ ...lines.map(line => ' ' + line),
270
+ '} finally {',
271
+ ' while (_avm1With.length > _avm1WithBase) {',
272
+ ' const scope = _avm1With.pop();',
273
+ ' _constantPool = scope.pool;',
274
+ ' _avm1Target = scope.target;',
275
+ ...(this._catchPlayback ? [' _avm1PlaybackTarget = scope.playbackTarget;'] : []),
276
+ ' }',
277
+ '}',
278
+ ];
279
+ }
280
+ return lines;
281
+ }
282
+
283
+ /**
284
+ * Decode reachable AVM1 instructions from the action stream's entry.
285
+ * Stops fallthrough at unconditional Jump, Return, Throw, and End.
286
+ */
287
+ _collectReachable() {
288
+ const visited = new Set();
289
+ const blockStarts = new Set([this.entryOffset]);
290
+ /** @type {Map<number, object>} */
291
+ const insnMap = new Map();
292
+ const queue = [this.entryOffset];
293
+ const withRanges = [];
294
+
295
+ while (queue.length > 0) {
296
+ let pc = queue.pop();
297
+ while (pc >= 0 && pc < this.bytes.length && !visited.has(pc)) {
298
+ visited.add(pc);
299
+ const op = this.bytes[pc];
300
+ const scopeEnd = withRanges.reduce((end, scope) =>
301
+ pc >= scope.start && pc < scope.end ? Math.min(end, scope.end) : end, Infinity);
302
+ if (op === 0x00) { // End is an implicit return to the enclosing with continuation.
303
+ if (scopeEnd < this.bytes.length) {
304
+ blockStarts.add(scopeEnd);
305
+ insnMap.set(pc, { pc, op: OP.Jump, nextPc: pc + 1, target: scopeEnd });
306
+ queue.push(scopeEnd);
307
+ }
308
+ break;
309
+ }
310
+
311
+ let i = pc + 1;
312
+ let data = null;
313
+ /** @type {Uint8Array|null} */
314
+ let bodyBytes = null;
315
+ if (op >= 0x80) {
316
+ if (i + 2 > this.bytes.length) break;
317
+ const len = this.bytes[i] | (this.bytes[i + 1] << 8);
318
+ i += 2;
319
+ if (i + len > this.bytes.length) break;
320
+ data = this.bytes.slice(i, i + len);
321
+ i += len;
322
+ }
323
+
324
+ // DefineFunction(2): body follows the header in the stream (not inside Length)
325
+ if ((op === OP.DefineFunction || op === OP.DefineFunction2) && data) {
326
+ const codeSize = readDefineFunctionCodeSize(op, data);
327
+ if (codeSize > 0 && i + codeSize <= this.bytes.length) {
328
+ bodyBytes = this.bytes.slice(i, i + codeSize);
329
+ i += codeSize;
330
+ } else {
331
+ bodyBytes = new Uint8Array(0);
332
+ }
333
+ }
334
+ if (op === OP.Try && data?.length >= 7) {
335
+ const end = i + tryBodySize(data);
336
+ if (end <= this.bytes.length) {
337
+ bodyBytes = this.bytes.subarray(i, end);
338
+ i = end;
339
+ }
340
+ }
341
+
342
+ if (op === OP.With && data?.length >= 2) {
343
+ const start = pc + 5;
344
+ const end = Math.min(this.bytes.length, start + (data[0] | (data[1] << 8)));
345
+ insnMap.set(pc, { pc, op, nextPc: start, target: end });
346
+ blockStarts.add(start);
347
+ blockStarts.add(end);
348
+ if (start < end) withRanges.push({ start, end });
349
+ queue.push(end);
350
+ pc = start;
351
+ continue;
352
+ }
353
+
354
+ const insn = { pc, op, data, nextPc: i, target: null, bodyBytes };
355
+ if (isFrameWait(op)) {
356
+ const skipCount = data[op === OP.WaitForFrame ? 2 : 0] || 0;
357
+ const target = this._skipActions(i, skipCount, Math.min(scopeEnd, this.bytes.length));
358
+ insn.target = target;
359
+ blockStarts.add(i);
360
+ blockStarts.add(target);
361
+ if (target < this.bytes.length) queue.push(target);
362
+ }
363
+ if ((op === OP.Jump || op === OP.If) && data && data.length >= 2) {
364
+ let offset = data[0] | (data[1] << 8);
365
+ if (offset >= 0x8000) offset -= 0x10000;
366
+ const target = Math.min(i + offset, scopeEnd);
367
+ if (target >= 0 && target < this.bytes.length) {
368
+ insn.target = target;
369
+ blockStarts.add(target);
370
+ }
371
+ if (op === OP.If) blockStarts.add(i);
372
+ }
373
+
374
+ insnMap.set(pc, insn);
375
+
376
+ if (op === OP.Return || op === OP.Throw) {
377
+ break;
378
+ }
379
+ if (op === OP.Jump) {
380
+ if (insn.target !== null && !visited.has(insn.target)) {
381
+ queue.push(insn.target);
382
+ }
383
+ break;
384
+ }
385
+ if (op === OP.If) {
386
+ if (insn.target !== null && !visited.has(insn.target)) {
387
+ queue.push(insn.target);
388
+ }
389
+ }
390
+
391
+ pc = i;
392
+ }
393
+ }
394
+
395
+ const instructions = Array.from(insnMap.values()).sort((a, b) => a.pc - b.pc);
396
+ return { instructions, blockStarts };
397
+ }
398
+
399
+ // WaitForFrame counts complete action records, including any nested code.
400
+ _skipActions(start, count, end) {
401
+ let pos = start;
402
+ while (count-- > 0 && pos < end) {
403
+ const op = this.bytes[pos++];
404
+ if (op === OP.End) return pos - 1;
405
+ if (op < 0x80) continue;
406
+ if (pos + 2 > end) return end;
407
+ const length = this.bytes[pos] | (this.bytes[pos + 1] << 8);
408
+ const header = pos + 2;
409
+ pos = header + length;
410
+ if (pos > end) return end;
411
+ if (op === OP.DefineFunction || op === OP.DefineFunction2) {
412
+ pos += readDefineFunctionCodeSize(op, this.bytes.subarray(header, pos));
413
+ } else if (op === OP.With && length >= 2) {
414
+ const size = this.bytes[header] | (this.bytes[header + 1] << 8);
415
+ pos = header + 2 + size;
416
+ } else if (op === OP.Try && length >= 7) {
417
+ pos += tryBodySize(this.bytes.subarray(header, pos));
418
+ }
419
+ }
420
+ return Math.min(pos, end);
421
+ }
422
+
423
+ _splitBasicBlocks(instructions, blockStarts) {
424
+ const rawBlocks = [];
425
+ const decodedOffsets = new Set(instructions.map(insn => insn.pc));
426
+ // Physically adjacent decoded instructions need not be connected: the
427
+ // intervening ActionEnd may have been omitted, or an obfuscated jump may
428
+ // have decoded another instruction inside an overlapping action payload.
429
+ for (let i = 0; i < instructions.length - 1; i++) {
430
+ const insn = instructions[i];
431
+ const following = instructions[i + 1].pc;
432
+ if (insn.nextPc !== following) {
433
+ blockStarts.add(insn.nextPc);
434
+ blockStarts.add(following);
435
+ }
436
+ }
437
+ let current = null;
438
+
439
+ for (let idx = 0; idx < instructions.length; idx++) {
440
+ const insn = instructions[idx];
441
+ if (!current || blockStarts.has(insn.pc)) {
442
+ current = { id: insn.pc, insns: [], fallthroughId: null };
443
+ rawBlocks.push(current);
444
+ }
445
+ const previous = current.insns.at(-1);
446
+ if ((insn.op === OP.Play || insn.op === OP.Stop) && previous?.nextPc === insn.pc &&
447
+ (previous.op === OP.GotoFrame || previous.op === OP.GotoLabel) && previous.seekPlayback == null) {
448
+ // Legacy navigation and its playback instruction run before the destination's actions.
449
+ current.insns[current.insns.length - 1] = {
450
+ ...previous, nextPc: insn.nextPc, seekPlayback: insn.op === OP.Play,
451
+ };
452
+ } else {
453
+ current.insns.push(insn);
454
+ }
455
+ const endsBlock =
456
+ insn.op === OP.Jump ||
457
+ insn.op === OP.If ||
458
+ insn.op === OP.With ||
459
+ isFrameWait(insn.op) ||
460
+ insn.op === OP.Return ||
461
+ insn.op === OP.Throw;
462
+ if (endsBlock) {
463
+ if ((insn.op === OP.If || insn.op === OP.With || isFrameWait(insn.op)) &&
464
+ decodedOffsets.has(insn.nextPc)) current.fallthroughId = insn.nextPc;
465
+ current = null;
466
+ } else {
467
+ if (blockStarts.has(insn.nextPc) && decodedOffsets.has(insn.nextPc)) {
468
+ current.fallthroughId = insn.nextPc;
469
+ }
470
+ }
471
+ }
472
+ return rawBlocks;
473
+ }
474
+
475
+ // A block can use compile-time pool names only when every incoming path
476
+ // carries the same pool. Nested With restores its pool in the dispatcher.
477
+ _findEntryPools(blocks) {
478
+ const byId = new Map(blocks.map(block => [block.id, block]));
479
+ const pending = [this.entryOffset];
480
+ const entries = new Map([[this.entryOffset, this.initialConstantPool]]);
481
+ const exits = new Map();
482
+ for (let i = 0; i < pending.length; i++) {
483
+ const id = pending[i];
484
+ const block = byId.get(id);
485
+ let pool = entries.get(id);
486
+ for (const instruction of block.insns) {
487
+ if (instruction.op === OP.ConstantPool) {
488
+ instruction.pool ??= this._decodePool(instruction.data);
489
+ pool = instruction.pool;
490
+ } else if (instruction.op === OP.Try) {
491
+ pool = null;
492
+ }
493
+ }
494
+ if (exits.has(id) && exits.get(id) === pool) continue;
495
+ exits.set(id, pool);
496
+ const last = block.insns.at(-1);
497
+ const successors = last.op === OP.Jump ? [last.target] :
498
+ last.op === OP.If || isFrameWait(last.op) ? [block.fallthroughId, last.target] : [block.fallthroughId];
499
+ for (const target of successors) {
500
+ if (!byId.has(target)) continue;
501
+ const entry = entries.has(target) && entries.get(target) !== pool ? null : pool;
502
+ if (entries.has(target) && entries.get(target) === entry) continue;
503
+ entries.set(target, entry);
504
+ pending.push(target);
505
+ }
506
+ }
507
+ return entries;
508
+ }
509
+
510
+ _simulateBlocks(rawBlocks, entryPools) {
511
+ const rawMap = new Map(rawBlocks.map(block => [block.id, block]));
512
+
513
+ const entryDepth = new Map([[this.entryOffset, 0]]);
514
+ const simulated = new Map();
515
+ const queue = [this.entryOffset];
516
+ let maxSpill = 0;
517
+
518
+ while (queue.length > 0) {
519
+ const bid = queue.shift();
520
+ if (simulated.has(bid)) continue;
521
+ const raw = rawMap.get(bid);
522
+ if (!raw) continue;
523
+
524
+ this.constantPool = entryPools.get(bid) ?? null;
525
+ const d = entryDepth.get(bid) ?? 0;
526
+ this.stack = this._dynamicStack
527
+ ? this._createRuntimeStack()
528
+ : Array.from({ length: d }, (_, k) => `_s${k}`);
529
+ this.lines = [];
530
+
531
+ const lastIdx = raw.insns.length - 1;
532
+ for (let k = 0; k < lastIdx; k++) {
533
+ const insn = raw.insns[k];
534
+ this._execOp(insn);
535
+ }
536
+
537
+ const last = raw.insns[lastIdx];
538
+ let bb;
539
+
540
+ if (last.op === OP.Return || last.op === OP.Throw) {
541
+ this._execOp(last);
542
+ bb = {
543
+ id: bid,
544
+ stmts: this.lines,
545
+ term: last.op === OP.Throw ? 'throw' : 'return',
546
+ };
547
+ } else if (last.op === OP.Jump) {
548
+ const outDepth = this._spillStack();
549
+ if (outDepth > maxSpill) maxSpill = outDepth;
550
+ const target = last.target !== null && rawMap.has(last.target) ? last.target : null;
551
+ bb = { id: bid, stmts: this.lines, term: 'jump', next: target };
552
+ if (target !== null) {
553
+ if (!entryDepth.has(target)) {
554
+ entryDepth.set(target, outDepth);
555
+ queue.push(target);
556
+ } else if (entryDepth.get(target) !== outDepth) {
557
+ this._stackDepthConflict = true;
558
+ }
559
+ }
560
+ } else if (last.op === OP.If || last.op === OP.With || isFrameWait(last.op)) {
561
+ let cond;
562
+ if (isFrameWait(last.op)) {
563
+ const dynamicFrame = last.op === OP.WaitForFrame2;
564
+ const frame = dynamicFrame ? this._pop() : (last.data[0] | (last.data[1] << 8));
565
+ const loaded = this._tmp();
566
+ const clip = this._catchPlayback ? '_avm1PlaybackTarget' : this._usesSetTarget ? '_avm1Target' : 'this';
567
+ this.lines.push(`var ${loaded} = _avm1FrameLoaded(${clip}, ${frame}, ${dynamicFrame});`);
568
+ cond = `!${loaded}`;
569
+ } else {
570
+ cond = _simplifyAvm1Cond(this._pop());
571
+ if (last.op === OP.If) cond = this._booleanExpression(cond);
572
+ }
573
+ const outDepth = this._spillStack();
574
+ if (outDepth > maxSpill) maxSpill = outDepth;
575
+ const target = rawMap.has(last.target) ? last.target : null;
576
+ const fallthrough = rawMap.has(raw.fallthroughId) ? raw.fallthroughId : null;
577
+ if (last.op === OP.With) {
578
+ const end = last.target ?? last.nextPc;
579
+ const targetClip = this._usesSetTarget ? '_avm1Target' : 'this';
580
+ const playback = this._catchPlayback ? ', _avm1PlaybackTarget' : '';
581
+ cond = `_avm1EnterWith(_avm1With, ${cond}, ${end}, ${targetClip}, _constantPool${playback})`;
582
+ }
583
+ const tTarget = last.op === OP.With ? fallthrough : target;
584
+ const fTarget = last.op === OP.With ? target : fallthrough;
585
+ bb = { id: bid, stmts: this.lines, term: 'branch', cond, trueTarget: tTarget, falseTarget: fTarget };
586
+ for (const t of [fTarget, tTarget]) {
587
+ if (t !== null) {
588
+ if (!entryDepth.has(t)) {
589
+ entryDepth.set(t, outDepth);
590
+ queue.push(t);
591
+ } else if (entryDepth.get(t) !== outDepth) {
592
+ this._stackDepthConflict = true;
593
+ }
594
+ }
595
+ }
596
+ } else {
597
+ this._execOp(last);
598
+ const outDepth = this._spillStack();
599
+ if (outDepth > maxSpill) maxSpill = outDepth;
600
+ const nxt = raw.fallthroughId !== null && rawMap.has(raw.fallthroughId) ? raw.fallthroughId : null;
601
+ bb = { id: bid, stmts: this.lines, term: 'fallthrough', next: nxt };
602
+ if (nxt !== null) {
603
+ if (!entryDepth.has(nxt)) {
604
+ entryDepth.set(nxt, outDepth);
605
+ queue.push(nxt);
606
+ } else if (entryDepth.get(nxt) !== outDepth) {
607
+ this._stackDepthConflict = true;
608
+ }
609
+ }
610
+ }
611
+
612
+ simulated.set(bid, bb);
613
+ }
614
+
615
+ const blocks = rawBlocks.map(r => simulated.get(r.id)).filter(Boolean);
616
+ return { blocks, maxSpill };
617
+ }
618
+
619
+ _spillStack() {
620
+ if (this._dynamicStack) return 0;
621
+ const d = this.stack.length;
622
+ for (let k = 0; k < d; k++) {
623
+ if (this.stack[k] !== `_s${k}`) {
624
+ this.lines.push(`_s${k} = ${this.stack[k]};`);
625
+ }
626
+ }
627
+ return d;
628
+ }
629
+
630
+ _snapshotPendingValues(changingPool = false) {
631
+ if (this._dynamicStack) return;
632
+ for (let i = 0; i < this.stack.length; i++) {
633
+ const value = this.stack[i];
634
+ if (value === '__ENUM_TOP__' ||
635
+ /^(?:this|root|globals|null|undefined|true|false|NaN|Infinity|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|_[st]\d+)$/.test(value) ||
636
+ (!changingPool && /^_constantPool\[\d+\]$/.test(value)) ||
637
+ parseStringLiteral(value) != null) continue;
638
+ const temp = this._tmp();
639
+ this.lines.push(`var ${temp} = ${value};`);
640
+ this.stack[i] = temp;
641
+ }
642
+ }
643
+
644
+ /**
645
+ * Emit JavaScript for a decoded action.
646
+ */
647
+ _execOp({ op, data, nextPc: pos, bodyBytes = null, seekPlayback }) {
648
+ switch (op) {
649
+
650
+ // ---- Reserved action code ----
651
+ case OP.Reserved03:
652
+ // Reserved AVM1 action byte; no payload or stack effect. Some Boxhead 2
653
+ // branches land here inside an ActionPush length field, followed by End.
654
+ break;
655
+
656
+ // ---- Push ----
657
+ case OP.Push: {
658
+ let di = 0;
659
+ while (di < data.length) {
660
+ const type = data[di++];
661
+ switch (type) {
662
+ case PUSH_TYPE.STRING: {
663
+ const start = di;
664
+ while (di < data.length && data[di] !== 0) di++;
665
+ const s = decodeAvm1String(data.slice(start, di));
666
+ di++; // null terminator
667
+ this.stack.push(JSON.stringify(s));
668
+ break;
669
+ }
670
+ case PUSH_TYPE.FLOAT: {
671
+ const buf = new ArrayBuffer(4);
672
+ new Uint8Array(buf).set(data.slice(di, di + 4));
673
+ this.stack.push(String(new Float32Array(buf)[0]));
674
+ di += 4;
675
+ break;
676
+ }
677
+ case PUSH_TYPE.NULL:
678
+ this.stack.push('null');
679
+ break;
680
+ case PUSH_TYPE.UNDEFINED:
681
+ this.stack.push('undefined');
682
+ break;
683
+ case PUSH_TYPE.REGISTER: {
684
+ const reg = data[di++];
685
+ this.stack.push(this._reg(reg));
686
+ break;
687
+ }
688
+ case PUSH_TYPE.BOOLEAN:
689
+ this.stack.push(data[di++] ? 'true' : 'false');
690
+ break;
691
+ case PUSH_TYPE.DOUBLE: {
692
+ // AVM1 double is stored as two UI32 in reversed word order
693
+ const buf = new ArrayBuffer(8);
694
+ const view = new Uint8Array(buf);
695
+ view[4] = data[di]; view[5] = data[di+1]; view[6] = data[di+2]; view[7] = data[di+3];
696
+ view[0] = data[di+4]; view[1] = data[di+5]; view[2] = data[di+6]; view[3] = data[di+7];
697
+ di += 8;
698
+ this.stack.push(String(new Float64Array(buf)[0]));
699
+ break;
700
+ }
701
+ case PUSH_TYPE.INTEGER: {
702
+ const val = data[di] | (data[di+1] << 8) | (data[di+2] << 16) | (data[di+3] << 24);
703
+ di += 4;
704
+ this.stack.push(String(val));
705
+ break;
706
+ }
707
+ case PUSH_TYPE.CONSTANT8: {
708
+ const idx = data[di++];
709
+ this.stack.push(this._const(idx));
710
+ break;
711
+ }
712
+ case PUSH_TYPE.CONSTANT16: {
713
+ const idx = data[di] | (data[di+1] << 8);
714
+ di += 2;
715
+ this.stack.push(this._const(idx));
716
+ break;
717
+ }
718
+ default:
719
+ this.stack.push('undefined /* unknown push type ' + type + ' */');
720
+ }
721
+ }
722
+ break;
723
+ }
724
+
725
+ // ---- Constant pool ----
726
+ case OP.ConstantPool: {
727
+ this._snapshotPendingValues(true);
728
+ this.constantPool = this._decodePool(data);
729
+ this.lines.push(`_constantPool = ${JSON.stringify(this.constantPool)};`);
730
+ break;
731
+ }
732
+
733
+ // ---- Arithmetic ----
734
+ case OP.Add: this._binop('+', true); break;
735
+ case OP.Add2: this._binop('+', false, '_avm1Add2'); break;
736
+ case OP.Subtract: this._binop('-', true); break;
737
+ case OP.Multiply: this._binop('*', true); break;
738
+ case OP.Divide: this._binop('/', true); break;
739
+ case OP.Modulo: this._binop('%', true); break;
740
+ case OP.Increment: { const v = this._pop(); this.stack.push(`(${this._numberExpression(v)} + 1)`); break; }
741
+ case OP.Decrement: { const v = this._pop(); this.stack.push(`(${this._numberExpression(v)} - 1)`); break; }
742
+ case OP.ToInteger: {
743
+ const value = this._pop();
744
+ const number = this.useRuntimeNumbers ? `_avm1ObjectToNumber(${value})` : value;
745
+ this.stack.push(`((${number}) | 0)`);
746
+ break;
747
+ }
748
+ case OP.StoreRegister: {
749
+ const reg = data[0];
750
+ // The top stays on the stack, and older operands may refer to the
751
+ // register being written. Preserve their values before assignment.
752
+ this._snapshotPendingValues();
753
+ const top = this._peek();
754
+ // Enumerate leaves keys on runtime _stack; StoreRegister must peek, not pop.
755
+ if (top === '__ENUM_TOP__') {
756
+ this.lines.push(`${this._reg(reg)} = _stack[_stack.length - 1];`);
757
+ } else {
758
+ this.lines.push(`${this._reg(reg)} = ${top};`);
759
+ }
760
+ break;
761
+ }
762
+ case OP.Extends: {
763
+ const superCtor = this._pop();
764
+ const subCtor = this._pop();
765
+ this.lines.push(`_avm1Extend(${subCtor}, ${superCtor});`);
766
+ break;
767
+ }
768
+ case OP.CallFrame:
769
+ this.lines.push(`_avm1CallFrame(${this._targetScope()}, ${this._pop()});`);
770
+ break;
771
+ case OP.StringAdd: this._binop('+'); break;
772
+
773
+ // ---- Comparison ----
774
+ case OP.Equals: this._binop('==', false, '_avm1LegacyCompare'); break;
775
+ case OP.Equals2: this._binop('==', false, '_avm1Equals2'); break;
776
+ case OP.LessThan: this._binop('<', false, '_avm1LegacyCompare', true); break;
777
+ case OP.LessThan2: this._binop('<', false, '_avm1Less2'); break;
778
+ case OP.Greater: this._binop('>', false, '_avm1Less2', true); break;
779
+ case OP.StrictEquals: this._binop('==='); break;
780
+ case OP.StringEquals: this._binop('==='); break;
781
+ case OP.StringLessThan: this._binop('<'); break;
782
+ case OP.StringGreater: this._binop('>'); break;
783
+
784
+ // ---- Logic ----
785
+ case OP.And:
786
+ case OP.Or: {
787
+ const right = this._pop();
788
+ const left = this._pop();
789
+ if (this.useRuntimeNumbers) {
790
+ this.stack.push(`_avm1Logical(${left}, ${right}, '${op === OP.And ? 'and' : 'or'}')`);
791
+ } else {
792
+ const operator = op === OP.And ? '&' : '|';
793
+ this.stack.push(`Boolean(Boolean(${left}) ${operator} Boolean(${right}))`);
794
+ }
795
+ break;
796
+ }
797
+ case OP.Not: {
798
+ const v = this._pop();
799
+ this.stack.push(this.useRuntimeNumbers ? `_avm1Logical(${v}, undefined, 'not')` : `(!${v})`);
800
+ break;
801
+ }
802
+ case OP.BitAnd: this._bitwise('&'); break;
803
+ case OP.BitOr: this._bitwise('|'); break;
804
+ case OP.BitXor: this._bitwise('^'); break;
805
+ case OP.BitLShift: this._bitwise('<<'); break;
806
+ case OP.BitRShift: this._bitwise('>>'); break;
807
+ case OP.BitURShift:this._bitwise('>>>'); break;
808
+
809
+ // ---- Stack manipulation ----
810
+ case OP.Pop:
811
+ this.lines.push(this._pop() + ';');
812
+ break;
813
+ case OP.Dup: {
814
+ // Materialize non-trivial exprs — Dup of `new Foo()` / `(function(){})`
815
+ // must share one value. Re-emitting the string evaluates twice and breaks
816
+ // AS2 class install (methods land on a different object than .prototype).
817
+ let v = this._pop();
818
+ if (!_isSimpleStackExpr(v)) {
819
+ const t = this._tmp();
820
+ this.lines.push(`var ${t} = ${v};`);
821
+ v = t;
822
+ }
823
+ this.stack.push(v);
824
+ this.stack.push(v);
825
+ break;
826
+ }
827
+ case OP.Swap: {
828
+ const a = this._pop();
829
+ const b = this._pop();
830
+ this.stack.push(a);
831
+ this.stack.push(b);
832
+ break;
833
+ }
834
+
835
+ // ---- Variables ----
836
+ case OP.GetVariable: {
837
+ const name = this._pop();
838
+ this.stack.push(this._emitGetVar(name));
839
+ break;
840
+ }
841
+ case OP.SetVariable: {
842
+ const val = this._pop();
843
+ const name = this._pop();
844
+ // Earlier stack operands have already been read in AVM1. Preserve them
845
+ // before this write, including the old value of a postfix increment.
846
+ this._snapshotPendingValues();
847
+ this.lines.push(this._emitSetVar(name, val));
848
+ break;
849
+ }
850
+ case OP.DefineLocal:
851
+ case OP.DefineLocal2: {
852
+ const val = op === OP.DefineLocal ? this._pop() : 'undefined';
853
+ const name = this._canonicalNameOperand(this._pop());
854
+ if (this._timelineDeclarations) {
855
+ const scopes = this._hasWith ? '_avm1With' : 'null';
856
+ this.lines.push(`_avm1DefineTimelineVariable(${scopes}, _avm1Locals, ${this._targetScope()}, ${name}, ${val}, ${op === OP.DefineLocal2});`);
857
+ break;
858
+ }
859
+ const lit = this._resolveStringLiteral(name);
860
+ if (lit) {
861
+ this.locals.add(lit);
862
+ const local = this._localIdent(lit);
863
+ const binding = `function () { return ${local}; }, function (_v) { ${local} = _v; }`;
864
+ if (this._hasWith) {
865
+ this.lines.push(`var ${local};`);
866
+ this.lines.push(`_avm1DefineWithLocal(_avm1With, _avm1Locals, ${name}, ${val}, ${op === OP.DefineLocal2}, ${binding});`);
867
+ } else {
868
+ this.lines.push(op === OP.DefineLocal ? `var ${local} = ${val};` : `var ${local};`);
869
+ this.lines.push(`_avm1DefineLocal(_avm1Locals, ${JSON.stringify(lit)}, ${binding});`);
870
+ }
871
+ } else if (this._hasWith) {
872
+ this.lines.push(`_avm1DefineWithLocal(_avm1With, _avm1Locals, ${name}, ${val}, ${op === OP.DefineLocal2});`);
873
+ } else {
874
+ this.lines.push(`_avm1DefineLocalValue(_avm1Locals, ${name}, ${val});`);
875
+ }
876
+ break;
877
+ }
878
+ case OP.Delete: {
879
+ const name = this._canonicalNameOperand(this._pop());
880
+ const obj = this._pop();
881
+ this._snapshotPendingValues();
882
+ const result = this._tmp();
883
+ this.lines.push(`var ${result} = _avm1DeleteMember(${obj}, ${name});`);
884
+ this.stack.push(result);
885
+ break;
886
+ }
887
+ case OP.Delete2: {
888
+ const name = this._canonicalNameOperand(this._pop());
889
+ this._snapshotPendingValues();
890
+ const result = this._tmp();
891
+ const scopes = this._hasWith ? '_avm1With' : '[]';
892
+ this.lines.push(`var ${result} = _avm1DeleteWithVariable(${scopes}, _avm1Locals, ${name}, ${this._targetScope()}, this);`);
893
+ this.stack.push(result);
894
+ break;
895
+ }
896
+
897
+ // ---- Members ----
898
+ case OP.GetMember: {
899
+ const prop = this._canonicalNameOperand(this._pop());
900
+ const obj = this._pop();
901
+ const propLit = this._resolveStringLiteral(prop);
902
+ const jsProp = propLit != null && !isAvm1DisplayMemberName(propLit) ? propLit : null;
903
+ const objExpr = obj === '_root' ? 'root' : obj === '_global' ? 'globals' : obj;
904
+ // Only the current receiver and the movie root are guaranteed to exist.
905
+ if (jsProp && isSafeIdent(jsProp) && isKnownClipExpr(objExpr)) {
906
+ this.stack.push(`${objExpr}.${jsProp}`);
907
+ } else {
908
+ const propExpr = jsProp != null ? JSON.stringify(jsProp) : prop;
909
+ this.stack.push(`_member(${objExpr}, ${propExpr})`);
910
+ }
911
+ break;
912
+ }
913
+ case OP.SetMember: {
914
+ const val = this._pop();
915
+ const prop = this._canonicalNameOperand(this._pop());
916
+ const obj = this._pop();
917
+ // Earlier member reads have executed before this assignment in AVM1.
918
+ this._snapshotPendingValues();
919
+ const propLit = this._resolveStringLiteral(prop);
920
+ const jsProp = propLit != null && !isAvm1DisplayMemberName(propLit) ? propLit : null;
921
+ const objExpr = obj === '_root' ? 'root' : obj === '_global' ? 'globals' : obj;
922
+ if (isKnownClipExpr(objExpr) && jsProp) {
923
+ noteUsage(this.profile, 'assign', jsProp);
924
+ if (jsProp.startsWith('on') || typeof val === 'string' && val.includes('function')) {
925
+ noteUsage(this.profile, 'method', jsProp);
926
+ }
927
+ }
928
+ const propExpr = jsProp != null ? JSON.stringify(jsProp) : prop;
929
+ // A named child or register may be absent on the current frame.
930
+ if (jsProp && isSafeIdent(jsProp) && isKnownClipExpr(objExpr)) {
931
+ this.lines.push(`${objExpr}.${jsProp} = ${val};`);
932
+ } else {
933
+ const scope = this._usesSetTarget ? ', _avm1Target' : '';
934
+ this.lines.push(`_setMember(${objExpr}, ${propExpr}, ${val}${scope});`);
935
+ }
936
+ break;
937
+ }
938
+
939
+ // ---- Properties (numeric index) ----
940
+ // An empty path refers to the active timeline of the action.
941
+ case OP.GetProperty: {
942
+ const idx = this._pop();
943
+ const target = this._pop();
944
+ this.stack.push(this._emitGetProperty(target, idx));
945
+ break;
946
+ }
947
+ case OP.SetProperty: {
948
+ const val = this._pop();
949
+ const idx = this._pop();
950
+ const target = this._pop();
951
+ this._snapshotPendingValues();
952
+ this.lines.push(`_setProperty.call(${this._indexedPropertyTarget()}, ${target}, ${idx}, ${val});`);
953
+ break;
954
+ }
955
+
956
+ // ---- Object creation ----
957
+ case OP.NewObject: {
958
+ this._snapshotPendingValues();
959
+ const className = this._canonicalNameOperand(this._pop());
960
+ const args = this._variableActionArgs();
961
+ const resolved = this._resolveStringLiteral(className);
962
+ const name = this._isNumberBuiltin(resolved) ? '"Number"' : className;
963
+ const tmp = this._tmp();
964
+ const scopes = this._hasWith ? '_avm1With' : '[]';
965
+ this.lines.push(`var ${tmp} = _avm1NewObject(${name}, ${args}, ${scopes}, _avm1Locals, ${this._targetScope()}, this);`);
966
+ this.stack.push(tmp);
967
+ break;
968
+ }
969
+ case OP.NewMethod: {
970
+ this._snapshotPendingValues();
971
+ const methodName = this._canonicalNameOperand(this._pop());
972
+ const obj = this._pop();
973
+ const args = this._variableActionArgs();
974
+ const tmp = this._tmp();
975
+ this.lines.push(`var ${tmp} = _avm1NewMethod(${obj}, ${methodName}, ${args});`);
976
+ this.stack.push(tmp);
977
+ break;
978
+ }
979
+ case OP.InitArray: {
980
+ const count = Number(this._pop());
981
+ const items = this._popN(count);
982
+ this.stack.push(`[${items.join(', ')}]`);
983
+ break;
984
+ }
985
+ case OP.InitObject: {
986
+ const count = Number(this._pop());
987
+ const pairs = [];
988
+ for (let n = 0; n < count; n++) {
989
+ const val = this._pop();
990
+ const key = this._pop();
991
+ pairs.push(`[${key}]: ${val}`);
992
+ }
993
+ this.stack.push(`({${pairs.join(', ')}})`);
994
+ break;
995
+ }
996
+
997
+ // ---- Type operations ----
998
+ case OP.TypeOf: {
999
+ const v = this._pop();
1000
+ this.stack.push(`typeof ${v}`);
1001
+ break;
1002
+ }
1003
+ case OP.TargetPath: {
1004
+ this.stack.push(`_avm1TargetPath(${this._pop()})`);
1005
+ break;
1006
+ }
1007
+ case OP.InstanceOf: {
1008
+ const constr = this._pop();
1009
+ const obj = this._pop();
1010
+ this.stack.push(`_avm1InstanceOf(${obj}, ${constr})`);
1011
+ break;
1012
+ }
1013
+ case OP.ToNumber: {
1014
+ const v = this._pop();
1015
+ this.stack.push(this._numberExpression(v));
1016
+ break;
1017
+ }
1018
+ case OP.ToString: {
1019
+ const v = this._pop();
1020
+ this.stack.push(`String(${v})`);
1021
+ break;
1022
+ }
1023
+
1024
+ // ---- Function calls ----
1025
+ case OP.CallFunction: {
1026
+ const fnName = this._canonicalNameOperand(this._pop());
1027
+ const args = this._variableActionArgs();
1028
+ const tmp = this._tmp();
1029
+ const lit = this._resolveStringLiteral(fnName);
1030
+ // Resolve missing methods through the AVM1 runtime.
1031
+ let call;
1032
+ if (this._hasWith) {
1033
+ call = `_avm1CallWithFunction(_avm1With, _avm1Locals, ${fnName}, ${args}, ${this._targetScope()}, this)`;
1034
+ } else if (this._isNumberBuiltin(lit)) {
1035
+ call = `globals.Number(...${args})`;
1036
+ } else if (lit && AVM1_GLOBALS.has(lit)) {
1037
+ call = `${lit}(...${args})`;
1038
+ } else {
1039
+ call = `_callFunction.call(${this._targetScope()}, ${fnName}, ${args})`;
1040
+ }
1041
+ this.lines.push(`var ${tmp} = ${call};`);
1042
+ this.stack.push(tmp);
1043
+ break;
1044
+ }
1045
+ case OP.CallMethod: {
1046
+ const methodName = this._canonicalNameOperand(this._pop());
1047
+ const obj = this._pop();
1048
+ const args = this._variableActionArgs();
1049
+ const tmp = this._tmp();
1050
+ const call = methodName === '""' || methodName === "''" || methodName === 'undefined'
1051
+ ? `_callMethod(${obj}, null, ${args})`
1052
+ : `_callMethod(${obj}, ${methodName}, ${args})`;
1053
+ this.lines.push(`var ${tmp} = ${call};`);
1054
+ this.stack.push(tmp);
1055
+ break;
1056
+ }
1057
+ case OP.Return: {
1058
+ const val = this.stack.length > 0 ? this._pop() : 'undefined';
1059
+ this.lines.push(`return ${val};`);
1060
+ break;
1061
+ }
1062
+
1063
+ // ---- DefineFunction ----
1064
+ case OP.DefineFunction: {
1065
+ this._emitDefineFunction(data, bodyBytes);
1066
+ break;
1067
+ }
1068
+ case OP.DefineFunction2: {
1069
+ this._emitDefineFunction2(data, bodyBytes);
1070
+ break;
1071
+ }
1072
+
1073
+ // ---- Control flow ----
1074
+ case OP.Jump: {
1075
+ let offset = data[0] | (data[1] << 8);
1076
+ if (offset >= 0x8000) offset -= 0x10000;
1077
+ const target = pos + offset; // pos is already past the data
1078
+ this.lines.push(`/* JUMP → _L${target} (${offset >= 0 ? '+' : ''}${offset}) */`);
1079
+ break;
1080
+ }
1081
+ case OP.If: {
1082
+ let offset = data[0] | (data[1] << 8);
1083
+ if (offset >= 0x8000) offset -= 0x10000;
1084
+ const target = pos + offset;
1085
+ const cond = this._booleanExpression(this._pop());
1086
+ this.lines.push(`if (${cond}) { /* branch → _L${target} */ }`);
1087
+ break;
1088
+ }
1089
+
1090
+ // ---- Timeline control ----
1091
+ case OP.Play:
1092
+ this.lines.push(`${this._timelineTarget()}play();`);
1093
+ break;
1094
+ case OP.Stop:
1095
+ this.lines.push(`${this._timelineTarget()}stop();`);
1096
+ break;
1097
+ case OP.NextFrame:
1098
+ this.lines.push(`${this._timelineTarget()}nextFrame();`);
1099
+ break;
1100
+ case OP.PrevFrame:
1101
+ this.lines.push(`${this._timelineTarget()}prevFrame();`);
1102
+ break;
1103
+ case OP.StopSounds:
1104
+ this.lines.push(`(globals.__soundPlayer || { stopAll() {} }).stopAll();`);
1105
+ break;
1106
+ case OP.GotoFrame: {
1107
+ // SWF ActionGotoFrame is 0-based; ActionScript frame numbers are 1-based.
1108
+ const frame = (data[0] | (data[1] << 8)) + 1;
1109
+ const method = seekPlayback ? 'gotoAndPlay' : 'gotoAndStop';
1110
+ this.lines.push(`${this._timelineTarget()}${method}(${frame});`);
1111
+ break;
1112
+ }
1113
+ case OP.GotoFrame2: {
1114
+ const flags = data[0];
1115
+ const frame = this._pop();
1116
+ const play = flags & 1;
1117
+ const hasSceneBias = !!(flags & 2);
1118
+ const sceneBias = hasSceneBias ? ((data[1] || 0) | ((data[2] || 0) << 8)) : null;
1119
+ const args = hasSceneBias ? `${frame}, null, ${sceneBias}` : `${frame}`;
1120
+ const target = this._usesSetTarget && !this._catchPlayback ? `${this._targetScope()}.` : this._timelineTarget();
1121
+ this.lines.push(`${target}${play ? 'gotoAndPlay' : 'gotoAndStop'}(${args});`);
1122
+ break;
1123
+ }
1124
+ case OP.GotoLabel: {
1125
+ let label = '';
1126
+ for (let j = 0; j < data.length && data[j] !== 0; j++) label += String.fromCharCode(data[j]);
1127
+ const method = seekPlayback ? 'gotoAndPlay' : 'gotoAndStop';
1128
+ this.lines.push(`${this._timelineTarget()}${method}(${JSON.stringify(label)});`);
1129
+ break;
1130
+ }
1131
+
1132
+ // ---- URL ----
1133
+ case OP.GetURL: {
1134
+ const parts = [];
1135
+ let start = 0;
1136
+ for (let i = 0; i < 2; i++) {
1137
+ const end = data.indexOf(0, start);
1138
+ parts.push(JSON.stringify(decodeAvm1String(data.subarray(start, end < 0 ? data.length : end))));
1139
+ start = end < 0 ? data.length : end + 1;
1140
+ }
1141
+ this.lines.push(`_avm1GetURL(${this._targetScope()}, ${parts.join(', ')}, 0, _avm1Locals);`);
1142
+ break;
1143
+ }
1144
+ case OP.GetURL2: {
1145
+ const targetStr = this._pop();
1146
+ const urlStr = this._pop();
1147
+ this.lines.push(`_avm1GetURL(${this._targetScope()}, ${urlStr}, ${targetStr}, ${data[0] || 0}, _avm1Locals);`);
1148
+ break;
1149
+ }
1150
+
1151
+ // ---- Throw / Try / With ----
1152
+ case OP.Throw: {
1153
+ const val = this._pop();
1154
+ this.lines.push(`throw new Avm1ThrownValue(${val});`);
1155
+ break;
1156
+ }
1157
+ case OP.Try: {
1158
+ const parsed = parseTryAction(data, bodyBytes);
1159
+ if (!parsed) {
1160
+ this.diag?.warn?.('Malformed AVM1 ActionTry payload');
1161
+ this.lines.push(`/* malformed AVM1 ActionTry payload */`);
1162
+ break;
1163
+ }
1164
+ const sectionId = this._tmpCount++;
1165
+ const transpileBlock = (bytes, arm) => {
1166
+ const nested = new Avm1Context(bytes, this.diag, arm === 'try' ? this.constantPool : null, true, this.sharedAvm1Runtime, this.nameSpellings);
1167
+ nested.useRuntimeNumbers = this.useRuntimeNumbers;
1168
+ nested._inlineTry = true;
1169
+ nested._catchPlayback = arm === 'catch' || this._catchPlayback;
1170
+ nested._inheritedTargetBase = this._formalNames || this._inheritedTargetBase;
1171
+ nested._inheritsWith = this._hasWith;
1172
+ nested._scopeLookup = this._scopeLookup;
1173
+ nested._clipActionScope = this._clipActionScope;
1174
+ nested._timelineDeclarations = this._timelineDeclarations;
1175
+ nested.registerAliases = this.registerAliases;
1176
+ nested._sectionExit = `${this._sectionExit || '_avm1End'}_${sectionId}_${arm}`;
1177
+ const source = nested.transpile();
1178
+ this._needsRegisters ||= nested._needsRegisters;
1179
+ return source;
1180
+ };
1181
+ const tryJs = transpileBlock(parsed.tryBody, 'try');
1182
+ const catchJs = parsed.hasCatch ? transpileBlock(parsed.catchBody, 'catch') : '';
1183
+ const finallyJs = parsed.hasFinally ? transpileBlock(parsed.finallyBody, 'finally') : '';
1184
+ const errorName = `_avm1Caught${sectionId}`;
1185
+ const depth = `_avm1TryDepth${sectionId}`;
1186
+ let catchHeader = '';
1187
+ if (parsed.hasCatch) {
1188
+ this.lines.push(`const ${depth} = _avm1Stack.length;`);
1189
+ catchHeader = `_avm1Stack.length = Math.min(${depth}, _avm1Stack.length);\n`;
1190
+ if (parsed.catchRegister != null) {
1191
+ catchHeader += `${this._reg(parsed.catchRegister)} = ${errorName};\n`;
1192
+ } else if (parsed.catchName) {
1193
+ const name = JSON.stringify(parsed.catchName);
1194
+ catchHeader += this._hasWith
1195
+ ? `_avm1SetWithVariable(_avm1With, _avm1Locals, ${name}, ${errorName}, ${this._targetScope()}, this);\n`
1196
+ : `_avm1SetVariable(_avm1Locals, ${name}, ${errorName}, ${this._targetScope()}, this);\n`;
1197
+ }
1198
+ }
1199
+ // Catch enters a child activation. Keep the try's latest bindings
1200
+ // visible there without replacing the state used by finally.
1201
+ const catchPool = `_avm1CatchPool${sectionId}`, catchTarget = `_avm1CatchTarget${sectionId}`;
1202
+ const catchCode = `if (!(${errorName} instanceof Avm1ThrownValue)) throw ${errorName};\n` +
1203
+ `${errorName} = ${errorName}.value;\nconst ${catchPool} = _constantPool, ${catchTarget} = _avm1Target;\n{\n` +
1204
+ ` let _constantPool = ${catchPool}, _avm1Target = ${catchTarget}, _avm1PlaybackTarget = ${this._targetBase()};\n${indent(catchHeader + catchJs)}\n}`;
1205
+ this.lines.push(`${parsed.hasCatch || parsed.hasFinally ? 'try ' : ''}{\n${indent(tryJs)}\n}` +
1206
+ (parsed.hasCatch ? ` catch (${errorName}) {\n${indent(catchCode)}\n}` : '') +
1207
+ (parsed.hasFinally ? ` finally {\n${indent(finallyJs)}\n}` : ''));
1208
+ this.constantPool = null;
1209
+ break;
1210
+ }
1211
+ // ---- Enumerate ----
1212
+ // Keys go on runtime `_stack` (null-terminated). Compile stack holds
1213
+ // `__ENUM_TOP__` so StoreRegister peeks and Equals/Pop pops once per key.
1214
+ case OP.Enumerate:
1215
+ case OP.Enumerate2: {
1216
+ const operand = this._pop();
1217
+ const obj = op === OP.Enumerate2 ? operand
1218
+ : this._hasWith ? this._emitGetVar(operand)
1219
+ : `_scope.call(${this._targetScope()}, ${operand})`;
1220
+ const stackName = this._dynamicStack ? '_avm1Stack' : '_stack';
1221
+ this.lines.push(`${stackName} = _avm1Enumerate(${obj}, ${stackName});`);
1222
+ this.stack.push('__ENUM_TOP__');
1223
+ break;
1224
+ }
1225
+
1226
+ // ---- Misc ----
1227
+ case OP.Trace: {
1228
+ const val = this._pop();
1229
+ this.lines.push(`console.log(${val});`);
1230
+ break;
1231
+ }
1232
+ case OP.RandomNumber: {
1233
+ const max = this._pop();
1234
+ this.stack.push(this._utilityCall(_avm1RandomNumber, [this._numberExpression(max)]));
1235
+ break;
1236
+ }
1237
+ case OP.GetTime:
1238
+ this.stack.push(`Date.now()`);
1239
+ break;
1240
+ case OP.Chr: {
1241
+ const code = this._pop();
1242
+ this.stack.push(`String.fromCharCode(${code})`);
1243
+ break;
1244
+ }
1245
+ case OP.MBAsciiToChar: {
1246
+ const code = this._pop();
1247
+ this.stack.push(this._utilityCall(_avm1CodeToChar, [code]));
1248
+ break;
1249
+ }
1250
+ case OP.Ord: {
1251
+ const s = this._pop();
1252
+ this.stack.push(`(${s}).charCodeAt(0)`);
1253
+ break;
1254
+ }
1255
+ case OP.MBCharToAscii: {
1256
+ const s = this._pop();
1257
+ this.stack.push(this._utilityCall(_avm1CharToCode, [s]));
1258
+ break;
1259
+ }
1260
+ case OP.StringLength: {
1261
+ const s = this._pop();
1262
+ this.stack.push(`String(${s}).length`);
1263
+ break;
1264
+ }
1265
+ case OP.MBStringLength: {
1266
+ const s = this._pop();
1267
+ this.stack.push(`(typeof SWF_VERSION === 'number' && SWF_VERSION >= 6 ? String(${s}).length : Array.from(String(${s})).length)`);
1268
+ break;
1269
+ }
1270
+ case OP.StringExtract:
1271
+ case OP.MBStringExtract: {
1272
+ const len = this._pop();
1273
+ const start = this._pop();
1274
+ const str = this._pop();
1275
+ // SWF 6 switched multibyte strings to UTF-16 code units.
1276
+ const codePoints = op === OP.MBStringExtract
1277
+ ? "(typeof SWF_VERSION !== 'number' || SWF_VERSION < 6)" : 'false';
1278
+ this.stack.push(this._utilityCall(_avm1Substring, [
1279
+ `String(${str})`, start, len, codePoints,
1280
+ ]));
1281
+ break;
1282
+ }
1283
+ case OP.SetTarget2:
1284
+ case OP.SetTarget: {
1285
+ const terminator = data?.indexOf(0) ?? -1;
1286
+ const operand = op === OP.SetTarget2 ? this._pop()
1287
+ : JSON.stringify(decodeAvm1String(terminator < 0 ? data : data.subarray(0, terminator)));
1288
+ if (!this._dynamicStack) {
1289
+ // Stack expressions already evaluated in AVM1 must retain their old receiver.
1290
+ this.stack = this.stack.map(value => {
1291
+ if (!value.includes('_avm1Target') && !value.includes('_avm1With')) return value;
1292
+ const temp = this._tmp();
1293
+ this.lines.push(`var ${temp} = ${value};`);
1294
+ return temp;
1295
+ });
1296
+ }
1297
+ const playback = this._catchPlayback ? '_avm1PlaybackTarget = ' : '';
1298
+ this.lines.push(`${playback}_avm1Target = _avm1ResolveTarget(${this._targetBase()}, ${operand});`);
1299
+ break;
1300
+ }
1301
+ case OP.CloneSprite: {
1302
+ const depth = this._pop();
1303
+ const target = this._pop();
1304
+ const src = this._pop();
1305
+ this.lines.push(`_avm1CloneSprite(${this._targetScope()}, ${src}, ${target}, ${depth});`);
1306
+ break;
1307
+ }
1308
+ case OP.RemoveSprite: {
1309
+ const target = this._pop();
1310
+ this.lines.push(`_avm1RemoveSprite(${this._targetScope()}, ${target});`);
1311
+ break;
1312
+ }
1313
+ case OP.StartDrag: {
1314
+ const target = this._pop();
1315
+ const lockCenter = this._pop();
1316
+ const constrained = this._pop();
1317
+ if (this._dynamicStack) {
1318
+ // The bounds may be present at runtime even when the branch that
1319
+ // pushed the constraint flag was unknown at compile time.
1320
+ this.stack.values.length = 0;
1321
+ this.lines.push(`_avm1StartDrag(${this._targetScope()}, ${target}, ${lockCenter}, ${constrained}, _avm1Stack);`);
1322
+ } else if (/^(?:true|false|-?\d+(?:\.\d+)?)$/.test(constrained)) {
1323
+ const bounds = (constrained === 'true' || (Number(constrained) | 0))
1324
+ ? this._popN(4).reverse() : [];
1325
+ this.lines.push(`_avm1StartDrag(${this._targetScope()}, ${target}, ${lockCenter}, ${constrained}, [${bounds.join(', ')}]);`);
1326
+ } else {
1327
+ this._stackDepthConflict = true;
1328
+ }
1329
+ break;
1330
+ }
1331
+ case OP.StopDrag:
1332
+ this.lines.push('_avm1StopDrag();');
1333
+ break;
1334
+ case OP.ToggleQuality:
1335
+ this.lines.push('_avm1ToggleQuality();');
1336
+ break;
1337
+ case OP.Cast: {
1338
+ const obj = this._pop();
1339
+ const type = this._pop();
1340
+ this.stack.push(`_avm1Cast(${type}, ${obj})`);
1341
+ break;
1342
+ }
1343
+ case OP.Implements: {
1344
+ const ctor = this._pop();
1345
+ const interfaces = this._variableActionArgs();
1346
+ this.lines.push(`_avm1Implements(${ctor}, ${interfaces});`);
1347
+ break;
1348
+ }
1349
+ case OP.FSCommand2: {
1350
+ const args = this._variableActionArgs();
1351
+ const result = this._tmp();
1352
+ const scopes = this._hasWith ? '_avm1With' : 'null';
1353
+ this.lines.push(`var ${result} = _avm1FSCommand2(${args}, _avm1Locals, ${this._targetScope()}, ${scopes}, this);`);
1354
+ this.stack.push(result);
1355
+ break;
1356
+ }
1357
+
1358
+ default: {
1359
+ const hex = op.toString(16).padStart(2, '0');
1360
+ this.diag.warn(`Unsupported AVM1 opcode 0x${hex}`, 'transpile', { opcode: op });
1361
+ this.lines.push(`throw new Error("Unsupported AVM1 opcode 0x${hex}");`);
1362
+ }
1363
+ }
1364
+
1365
+ return pos;
1366
+ }
1367
+
1368
+ // ---- DefineFunction helpers ----
1369
+
1370
+ /**
1371
+ * @param {Uint8Array} data - header payload (includes codeSize field, not body)
1372
+ * @param {Uint8Array|null} bodyBytes - body that follows in the parent stream
1373
+ */
1374
+ _emitDefineFunction(data, bodyBytes) {
1375
+ let di = 0;
1376
+ let name = '';
1377
+ while (di < data.length && data[di] !== 0) name += String.fromCharCode(data[di++]);
1378
+ di++;
1379
+ name = this._canonicalName(name);
1380
+
1381
+ const paramCount = data[di] | (data[di + 1] << 8);
1382
+ di += 2;
1383
+
1384
+ const params = [];
1385
+ const paramNames = [];
1386
+ const seenParams = new Set();
1387
+ for (let p = 0; p < paramCount; p++) {
1388
+ let pname = '';
1389
+ while (di < data.length && data[di] !== 0) pname += String.fromCharCode(data[di++]);
1390
+ di++;
1391
+ pname = this._canonicalName(pname);
1392
+ let safe = _safeIdent(pname) || `_p${p}`;
1393
+ if (seenParams.has(safe)) safe = `${safe}_${p}`;
1394
+ seenParams.add(safe);
1395
+ params.push(safe);
1396
+ paramNames.push(pname);
1397
+ }
1398
+
1399
+ // codeSize is last field; body lives in bodyBytes (after header in stream)
1400
+ if (name) this.functionNames.add(name);
1401
+ const bodyBytecode = bodyBytes || new Uint8Array(0);
1402
+ const bodyCtx = new Avm1Context(bodyBytecode, this.diag, this.constantPool, true, this.sharedAvm1Runtime, this.nameSpellings);
1403
+ bodyCtx.useRuntimeNumbers = this.useRuntimeNumbers;
1404
+ bodyCtx._scopeLookup = true;
1405
+ bodyCtx._spriteFrameScope = this._spriteFrameScope;
1406
+ bodyCtx._formalNames = paramNames;
1407
+ bodyCtx._capturesWith = bodyCtx._inheritsWith = this._hasWith;
1408
+ bodyCtx.locals = new Set(this.locals);
1409
+ for (const name of this.locals) bodyCtx.scopeLocalBindings.set(name, this.scopeLocalBindings.get(name) ?? this._localIdent(name));
1410
+ bodyCtx.functionNames = new Set(this.functionNames);
1411
+ for (let i = 0; i < paramNames.length; i++) {
1412
+ bodyCtx.locals.add(paramNames[i]);
1413
+ bodyCtx.scopeLocalBindings.set(paramNames[i], params[i]);
1414
+ }
1415
+ const body = bodyCtx.transpile();
1416
+
1417
+ const safeName = _safeIdent(name);
1418
+ const inner = name
1419
+ ? `function ${safeName}(${params.join(', ')}) {\n var _constantPool = _capturedConstantPool.slice();\n${indent(body)}\n}`
1420
+ : `function (${params.join(', ')}) {\n var _constantPool = _capturedConstantPool.slice();\n${indent(body)}\n}`;
1421
+ const fnExpr = this._captureFunction(inner, bodyCtx._needsTargetBase);
1422
+
1423
+ if (name) {
1424
+ // AVM1 named functions are timeline/scope vars — expose on the clip
1425
+ this.lines.push(`var ${safeName} = ${fnExpr};`);
1426
+ if (this._hasWith) {
1427
+ this.lines.push(this._emitSetVar(JSON.stringify(name), safeName));
1428
+ } else if (isAvm1DisplayMemberName(name)) {
1429
+ this.lines.push(`_setMember(this, ${JSON.stringify(name)}, ${safeName});`);
1430
+ } else {
1431
+ this.lines.push(`this.${safeName} = ${safeName};`);
1432
+ }
1433
+ if (!this._hasWith && name !== safeName) {
1434
+ // Keep the original AVM1 name reachable too. Sanitizing names only for
1435
+ // JavaScript declarations otherwise breaks GetVariable/CallFunction
1436
+ // lookups for obfuscated names such as control characters.
1437
+ this.lines.push(`this[${JSON.stringify(name)}] = ${safeName};`);
1438
+ }
1439
+ noteUsage(this.profile, 'method', safeName);
1440
+ } else {
1441
+ this.stack.push(`(${fnExpr})`);
1442
+ }
1443
+ }
1444
+
1445
+ /**
1446
+ * @param {Uint8Array} data
1447
+ * @param {Uint8Array|null} bodyBytes
1448
+ */
1449
+ _emitDefineFunction2(data, bodyBytes) {
1450
+ let di = 0;
1451
+ let name = '';
1452
+ while (di < data.length && data[di] !== 0) name += String.fromCharCode(data[di++]);
1453
+ di++;
1454
+ name = this._canonicalName(name);
1455
+
1456
+ const paramCount = data[di] | (data[di + 1] << 8); di += 2;
1457
+ const registerCount = data[di++];
1458
+ const flags = data[di] | (data[di + 1] << 8); di += 2;
1459
+
1460
+ const { aliases, preamble } = materializePreloadAliases(flags);
1461
+ const params = [];
1462
+ const paramNames = [];
1463
+ const seenParams = new Set();
1464
+
1465
+ for (let p = 0; p < paramCount; p++) {
1466
+ const reg = data[di++];
1467
+ let pname = '';
1468
+ while (di < data.length && data[di] !== 0) pname += String.fromCharCode(data[di++]);
1469
+ di++;
1470
+ pname = this._canonicalName(pname);
1471
+ let safe = _safeIdent(pname) || `_p${p}`;
1472
+ if (seenParams.has(safe)) safe = `${safe}_${p}`;
1473
+ seenParams.add(safe);
1474
+ params.push(safe);
1475
+ paramNames.push(pname);
1476
+ if (reg > 0) {
1477
+ // Param already in a register — bind local name to that slot
1478
+ if (aliases.has(reg)) {
1479
+ preamble.push(`var ${safe} = ${aliases.get(reg)};`);
1480
+ } else {
1481
+ const local = `_r${reg}`;
1482
+ preamble.push(`var ${local} = ${safe};`);
1483
+ aliases.set(reg, local);
1484
+ }
1485
+ }
1486
+ }
1487
+
1488
+ if (name) this.functionNames.add(name);
1489
+ const bodyBytecode = bodyBytes || new Uint8Array(0);
1490
+ const bodyCtx = new Avm1Context(bodyBytecode, this.diag, this.constantPool, true, this.sharedAvm1Runtime, this.nameSpellings);
1491
+ bodyCtx.useRuntimeNumbers = this.useRuntimeNumbers;
1492
+ bodyCtx._scopeLookup = true;
1493
+ bodyCtx._spriteFrameScope = this._spriteFrameScope;
1494
+ bodyCtx._formalNames = paramNames;
1495
+ bodyCtx._capturesWith = bodyCtx._inheritsWith = this._hasWith;
1496
+ bodyCtx.locals = new Set(this.locals);
1497
+ for (const name of this.locals) bodyCtx.scopeLocalBindings.set(name, this.scopeLocalBindings.get(name) ?? this._localIdent(name));
1498
+ bodyCtx.functionNames = new Set(this.functionNames);
1499
+ for (let i = 0; i < paramNames.length; i++) {
1500
+ bodyCtx.locals.add(paramNames[i]);
1501
+ bodyCtx.scopeLocalBindings.set(paramNames[i], params[i]);
1502
+ }
1503
+ bodyCtx.registerCount = registerCount;
1504
+ bodyCtx.registerAliases = aliases;
1505
+
1506
+ let body = bodyCtx.transpile();
1507
+ // Merge nested profile into parent (handlers defined on this clip)
1508
+ for (const p of bodyCtx.profile.props) this.profile.props.add(p);
1509
+ for (const p of bodyCtx.profile.assigns) this.profile.assigns.add(p);
1510
+ for (const p of bodyCtx.profile.methods) this.profile.methods.add(p);
1511
+
1512
+ const head = preamble.length ? preamble.map(l => ' ' + l).join('\n') + '\n' : '';
1513
+ const safeName = _safeIdent(name);
1514
+ const inner = name
1515
+ ? `function ${safeName}(${params.join(', ')}) {\n var _constantPool = _capturedConstantPool.slice();\n${head}${indent(body)}\n}`
1516
+ : `function (${params.join(', ')}) {\n var _constantPool = _capturedConstantPool.slice();\n${head}${indent(body)}\n}`;
1517
+ const fnExpr = this._captureFunction(inner, bodyCtx._needsTargetBase, flags & DF2.PRELOAD_SUPER);
1518
+
1519
+ if (name) {
1520
+ this.lines.push(`var ${safeName} = ${fnExpr};`);
1521
+ if (this._hasWith) {
1522
+ this.lines.push(this._emitSetVar(JSON.stringify(name), safeName));
1523
+ } else if (isAvm1DisplayMemberName(name)) {
1524
+ this.lines.push(`_setMember(this, ${JSON.stringify(name)}, ${safeName});`);
1525
+ } else {
1526
+ this.lines.push(`this.${safeName} = ${safeName};`);
1527
+ }
1528
+ if (!this._hasWith && name !== safeName) {
1529
+ this.lines.push(`this[${JSON.stringify(name)}] = ${safeName};`);
1530
+ }
1531
+ noteUsage(this.profile, 'method', safeName);
1532
+ } else {
1533
+ this.stack.push(`(${fnExpr})`);
1534
+ }
1535
+ }
1536
+
1537
+ // ---- Stack helpers ----
1538
+
1539
+ /** @returns {string} */
1540
+ _pop() {
1541
+ if (this._dynamicStack) {
1542
+ const local = `_avm1Pop${this._dynamicPopCount++}`;
1543
+ this.lines.push(`var ${local} = _avm1Stack.pop();`);
1544
+ const known = this.stack.values.pop();
1545
+ return typeof known === 'string' && /^-?(?:\d+\.?\d*|\.\d+)$/.test(known) ? known : local;
1546
+ }
1547
+ const v = this.stack.length > 0 ? this.stack.pop() : 'undefined';
1548
+ return v === '__ENUM_TOP__' ? '_stack.pop()' : v;
1549
+ }
1550
+
1551
+ /** @returns {string} */
1552
+ _peek() {
1553
+ if (this._dynamicStack) return '_avm1Stack[_avm1Stack.length - 1]';
1554
+ return this.stack.length > 0 ? this.stack[this.stack.length - 1] : 'undefined';
1555
+ }
1556
+
1557
+ /**
1558
+ * Pop n args for CallMethod/CallFunction/NewObject.
1559
+ * AVM1 leaves arg1 on top of the stack (pushed last by the compiler in practice
1560
+ * for CallMethod) — pop in order to build [arg1, arg2, …].
1561
+ * (Previous unshift produced fully reversed registerClass/attachMovie/ASSetPropFlags.)
1562
+ * @param {number} n
1563
+ * @returns {string[]}
1564
+ */
1565
+ _popN(n) {
1566
+ const args = [];
1567
+ for (let i = 0; i < n; i++) args.push(this._pop());
1568
+ return args;
1569
+ }
1570
+
1571
+ _variableActionArgs() {
1572
+ const count = this._pop();
1573
+ if (this._dynamicStack) {
1574
+ this.stack.values.length = 0;
1575
+ return `_avm1ActionArgs(_avm1Stack, ${count})`;
1576
+ }
1577
+ if (!/^\d+$/.test(count) || Number(count) > 0x7fffffff) {
1578
+ this._stackDepthConflict = true;
1579
+ return '[]';
1580
+ }
1581
+ return `[${this._popN(Math.min(Number(count), this.stack.length)).join(', ')}]`;
1582
+ }
1583
+
1584
+ _bitwise(op) {
1585
+ if (this.useRuntimeNumbers) {
1586
+ const right = this._pop();
1587
+ const left = this._pop();
1588
+ this.stack.push(`_avm1Bitwise(${left}, ${right}, '${op}')`);
1589
+ } else {
1590
+ this._binop(op);
1591
+ }
1592
+ }
1593
+
1594
+ _booleanExpression(value) {
1595
+ if (!this.useRuntimeNumbers || /^(?:true|false|null|undefined|-?[0-9]+(?:[.][0-9]+)?)$/.test(value)) return value;
1596
+ return `_avm1ToBoolean(${value})`;
1597
+ }
1598
+
1599
+ _numberExpression(value) {
1600
+ if (/^-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/.test(value)) return value;
1601
+ return `${this.useRuntimeNumbers ? '_avm1ToNumber' : 'Number'}(${value})`;
1602
+ }
1603
+
1604
+ /** @param {string} op */
1605
+ _binop(op, numeric = false, runtimeOperator, runtimeFlag = false) {
1606
+ let right = this._pop();
1607
+ let left = this._pop();
1608
+ if (left === '__ENUM_TOP__') left = '_stack.pop()';
1609
+ if (right === '__ENUM_TOP__') right = '_stack.pop()';
1610
+ if (runtimeOperator && this.useRuntimeNumbers) {
1611
+ this.stack.push(`${runtimeOperator}(${left}, ${right}${runtimeFlag ? ', true' : ''})`);
1612
+ return;
1613
+ }
1614
+ if (numeric && (this.useRuntimeNumbers || op === '+')) {
1615
+ left = this._numberExpression(left);
1616
+ right = this._numberExpression(right);
1617
+ }
1618
+ this.stack.push(`(${left} ${op} ${right})`);
1619
+ }
1620
+
1621
+ _createRuntimeStack() {
1622
+ const context = this;
1623
+ return {
1624
+ values: [],
1625
+ get length() { return this.values.length; },
1626
+ push(value) {
1627
+ if (value !== '__ENUM_TOP__') context.lines.push(`_avm1Stack.push(${value});`);
1628
+ this.values.push(value);
1629
+ return this.values.length;
1630
+ },
1631
+ };
1632
+ }
1633
+
1634
+ /** @returns {string} - unique temp variable name */
1635
+ _tmp() {
1636
+ return `_t${this._tmpCount++}`;
1637
+ }
1638
+
1639
+ /**
1640
+ * @param {number} reg
1641
+ * @returns {string}
1642
+ */
1643
+ _reg(reg) {
1644
+ if (this.registerAliases.has(reg)) {
1645
+ return /** @type {string} */ (this.registerAliases.get(reg));
1646
+ }
1647
+ this._needsRegisters = true;
1648
+ return `_registers[${reg}]`;
1649
+ }
1650
+
1651
+ /**
1652
+ * @param {string} nameExpr - JS expression for the variable name
1653
+ * @returns {string}
1654
+ */
1655
+ _targetScope() {
1656
+ return this._usesSetTarget ? '(_avm1Target || root)' : 'this';
1657
+ }
1658
+
1659
+ _timelineTarget() {
1660
+ if (this._catchPlayback) return '_avm1PlaybackTarget?.';
1661
+ if (this._usesSetTarget) return '_avm1Target?.';
1662
+ if (!this._formalNames) return 'this.';
1663
+ // Timeline opcodes in a callback keep its defining target. Explicit
1664
+ // GetVariable("this") still refers to the object that invoked it.
1665
+ this._needsTargetBase = true;
1666
+ return '_avm1TargetBase?.';
1667
+ }
1668
+
1669
+ _targetBase() {
1670
+ return this._formalNames || this._inheritedTargetBase ? '_avm1TargetBase' : 'this';
1671
+ }
1672
+
1673
+ _indexedPropertyTarget() {
1674
+ if (this._usesSetTarget) return this._targetScope();
1675
+ // A method's receiver can be an ordinary object. Relative paths still
1676
+ // start from the timeline where its bytecode was defined.
1677
+ if (this._formalNames) this._needsTargetBase = true;
1678
+ return this._targetBase();
1679
+ }
1680
+
1681
+ _utilityCall(helper, args) {
1682
+ const target = this.sharedAvm1Runtime ? helper.name : `(${helper})`;
1683
+ return `${target}(${args.join(', ')})`;
1684
+ }
1685
+
1686
+ _emitGetVar(nameExpr) {
1687
+ nameExpr = this._canonicalNameOperand(nameExpr);
1688
+ const lit = this._resolveStringLiteral(nameExpr);
1689
+ if (lit === null) this._dynamicLocalLookup = true;
1690
+ const clipScope = this._clipActionScope ? ', true' : '';
1691
+ const pathKeyword = this.nameSpellings && lit ? lit.toLowerCase() : lit;
1692
+ if (pathKeyword === '_level0' || pathKeyword === '_root' || lit === 'root') return 'root';
1693
+ if (pathKeyword === '_global' || lit === 'globals') return 'globals';
1694
+ if (pathKeyword === 'this') return 'this';
1695
+ if (pathKeyword === '_parent' && this.nameSpellings) return `(${this._targetScope()}.parent || root)`;
1696
+ if (this._hasWith) {
1697
+ if (lit && isSafeIdent(lit) && !this.locals.has(lit)) noteUsage(this.profile, 'prop', flashPropToJs(lit));
1698
+ return `_avm1GetWithVariable(_avm1With, _avm1Locals, ${nameExpr}, ${this._targetScope()}, this${clipScope})`;
1699
+ }
1700
+ if (lit === '_parent' || lit === 'parent') return `(${this._targetScope()}.parent || root)`;
1701
+ // AS2 packages live on _global.
1702
+ if (lit && AVM1_PACKAGES.has(lit)) return `_pkg(${JSON.stringify(lit)})`;
1703
+ if (!this._usesSetTarget && !this._clipActionScope && lit && /[./:]/.test(lit)) return `_scope.call(this, ${nameExpr})`;
1704
+ if (this._isNumberBuiltin(lit)) return 'globals.Number';
1705
+ if (lit === 'Math' || this.nameSpellings && pathKeyword === 'math') return 'globals.Math';
1706
+ if (lit === 'Mouse' || this.nameSpellings && pathKeyword === 'mouse') return 'globals.Mouse';
1707
+ if (lit === 'Key') return 'globals.Key';
1708
+ if (lit === 'Stage' || this.nameSpellings && pathKeyword === 'stage') return 'globals.Stage';
1709
+ // Player classes live on `globals` — bare `MovieClip` throws under strict when
1710
+ // swflib did not define a global binding (DepthManager patches MovieClip.prototype).
1711
+ if (lit === 'Object' || lit === 'MovieClip' || lit === 'TextField' || lit === 'TextFormat' || lit === 'Sound' ||
1712
+ lit === 'Color' || lit === 'XML' || lit === 'XMLNode' || lit === 'LoadVars') {
1713
+ return `globals[${JSON.stringify(lit)}]`;
1714
+ }
1715
+ if (lit && AVM1_GLOBALS.has(lit)) return lit;
1716
+ if (lit && this.locals.has(lit)) return this._deletesLocals
1717
+ ? `_avm1GetVariable(_avm1Locals, ${nameExpr}, ${this._targetScope()}, this${clipScope})` : this._localIdent(lit);
1718
+ if (this._hasCaseVariantLocal(lit)) return `_avm1GetVariable(_avm1Locals, ${nameExpr}, ${this._targetScope()}, this${clipScope})`;
1719
+ if (this._usesSetTarget || this._clipActionScope || isAvm1DisplayMemberName(lit)) {
1720
+ if (lit && isSafeIdent(lit)) noteUsage(this.profile, 'prop', flashPropToJs(lit));
1721
+ const name = this._caseVariantFunctionName(lit);
1722
+ return `_avm1GetVariable(_avm1Locals, ${name ? JSON.stringify(name) : nameExpr}, ${this._targetScope()}, this${clipScope})`;
1723
+ }
1724
+ if (lit === '$version' || lit === 'getVersion' || lit === 'targetPath' ||
1725
+ lit === 'isNaN' || this.nameSpellings && pathKeyword === 'isnan') {
1726
+ return `_avm1GetVariable(_avm1Locals, ${nameExpr}, this)`;
1727
+ }
1728
+ const functionCaseMatch = lit && this._caseVariantFunctionName(lit);
1729
+ if (functionCaseMatch) return `this[${JSON.stringify(functionCaseMatch)}]`;
1730
+ if (lit && isSafeIdent(lit)) {
1731
+ const jsName = flashPropToJs(lit);
1732
+ noteUsage(this.profile, 'prop', jsName);
1733
+ if (this._scopeLookup) {
1734
+ // Functions and library initializers can read names from the movie globals.
1735
+ const spriteScope = this._spriteFrameScope && this._formalNames ? ', false, true' : '';
1736
+ return `_avm1GetVariable(_avm1Locals, ${JSON.stringify(lit)}, this, this${spriteScope})`;
1737
+ }
1738
+ return `this.${jsName}`;
1739
+ }
1740
+ return `_avm1GetVariable(_avm1Locals, ${nameExpr}, this)`;
1741
+ }
1742
+
1743
+ /**
1744
+ * @param {string} nameExpr
1745
+ * @param {string} val
1746
+ * @returns {string}
1747
+ */
1748
+ _emitSetVar(nameExpr, val) {
1749
+ nameExpr = this._canonicalNameOperand(nameExpr);
1750
+ const lit = this._resolveStringLiteral(nameExpr);
1751
+ if (lit === null) this._dynamicLocalLookup = true;
1752
+ if (this._hasWith) {
1753
+ if (lit && isSafeIdent(lit) && !this.locals.has(lit)) noteUsage(this.profile, 'assign', flashPropToJs(lit));
1754
+ return `_avm1SetWithVariable(_avm1With, _avm1Locals, ${nameExpr}, ${val}, ${this._targetScope()}, this);`;
1755
+ }
1756
+ if (lit && this.locals.has(lit)) return this._deletesLocals
1757
+ ? `_avm1SetVariable(_avm1Locals, ${nameExpr}, ${val}, ${this._targetScope()}, this);` : `${this._localIdent(lit)} = ${val};`;
1758
+ if (this._hasCaseVariantLocal(lit)) return `_avm1SetVariable(_avm1Locals, ${nameExpr}, ${val}, ${this._targetScope()}, this);`;
1759
+ if (lit && AVM1_PACKAGES.has(lit)) return `_pkg(${JSON.stringify(lit)}); globals[${JSON.stringify(lit)}] = ${val};`;
1760
+ if (this._usesSetTarget || isAvm1DisplayMemberName(lit)) {
1761
+ if (lit && isSafeIdent(lit)) noteUsage(this.profile, 'assign', flashPropToJs(lit));
1762
+ const receiverOnly = !this._usesSetTarget && this._formalNames ? ', true' : '';
1763
+ return `_avm1SetVariable(_avm1Locals, ${nameExpr}, ${val}, ${this._targetScope()}, this${receiverOnly});`;
1764
+ }
1765
+ if (lit && /[./:]/.test(lit)) return `_setScope.call(this, ${nameExpr}, ${val});`;
1766
+ if (lit && isSafeIdent(lit)) {
1767
+ const jsName = flashPropToJs(lit);
1768
+ noteUsage(this.profile, 'assign', jsName);
1769
+ if (jsName.startsWith('on')) noteUsage(this.profile, 'method', jsName);
1770
+ if (this._formalNames) {
1771
+ // A name absent during compilation can be declared before this closure runs.
1772
+ return `_avm1SetVariable(_avm1Locals, ${nameExpr}, ${val}, this, this, true);`;
1773
+ }
1774
+ return `this.${jsName} = ${val};`;
1775
+ }
1776
+ return `_avm1SetVariable(_avm1Locals, ${nameExpr}, ${val}, this);`;
1777
+ }
1778
+
1779
+ _captureFunction(inner, needsTargetBase, captureIdentity) {
1780
+ const withParameter = this._hasWith ? ', _capturedWith' : '';
1781
+ const withArgument = this._hasWith ? ', _avm1CaptureWith(_avm1With)' : '';
1782
+ const targetParameter = needsTargetBase ? ', _capturedTargetBase' : '';
1783
+ const inherited = this._formalNames || this._inheritedTargetBase;
1784
+ if (needsTargetBase && this._formalNames) this._needsTargetBase = true;
1785
+ const targetArgument = needsTargetBase ? inherited ? ', _avm1TargetBase' : ', this' : '';
1786
+ const factoryBody = captureIdentity ? `var _avm1Function = ${inner}; return _avm1Function;` : `return ${inner};`;
1787
+ return `_avm1MarkBytecodeFunction((function (_capturedConstantPool, _capturedLocals${withParameter}${targetParameter}) { ${factoryBody} })(_constantPool, _avm1Locals${withArgument}${targetArgument}))`;
1788
+ }
1789
+
1790
+ _localIdent(name) {
1791
+ if (this.localIdentifiers.has(name)) return this.localIdentifiers.get(name);
1792
+ const base = _safeIdent(name) || '_avm1Local';
1793
+ let ident = base, suffix = 1;
1794
+ while (this.localIdentifierNames.has(ident)) ident = `${base}_${suffix++}`;
1795
+ this.localIdentifiers.set(name, ident);
1796
+ this.localIdentifierNames.add(ident);
1797
+ return ident;
1798
+ }
1799
+
1800
+ _isNumberBuiltin(name) {
1801
+ return this.useRuntimeNumbers && (name === 'Number' || this.nameSpellings && name?.toLowerCase() === 'number');
1802
+ }
1803
+
1804
+ _canonicalNameOperand(operand) {
1805
+ if (!this.nameSpellings) return operand;
1806
+ const name = this._resolveStringLiteral(operand);
1807
+ const first = this._canonicalName(name);
1808
+ return first !== name ? JSON.stringify(first) : operand;
1809
+ }
1810
+
1811
+ _canonicalName(name) {
1812
+ if (!this.nameSpellings || !name || !isSafeIdent(name)) return name;
1813
+ const folded = name.toLowerCase();
1814
+ if (!this.nameSpellings.has(folded)) this.nameSpellings.set(folded, name);
1815
+ return this.nameSpellings.get(folded);
1816
+ }
1817
+
1818
+ _hasCaseVariantLocal(name) {
1819
+ if (!name) return false;
1820
+ const folded = name.toLowerCase();
1821
+ for (const local of this.locals) {
1822
+ if (local.toLowerCase() === folded) return true;
1823
+ }
1824
+ return false;
1825
+ }
1826
+
1827
+ _resolveStringLiteral(expr) {
1828
+ const literal = parseStringLiteral(expr);
1829
+ if (literal != null) return literal;
1830
+ const match = /^_constantPool\[(\d+)\]$/.exec(String(expr).trim());
1831
+ return match ? (this.constantPool?.[Number(match[1])] ?? null) : null;
1832
+ }
1833
+
1834
+ _decodePool(data) {
1835
+ const pool = [];
1836
+ const count = data[0] | (data[1] << 8);
1837
+ let pos = 2;
1838
+ for (let index = 0; index < count; index++) {
1839
+ let value = '';
1840
+ while (pos < data.length && data[pos] !== 0) value += String.fromCharCode(data[pos++]);
1841
+ pos++;
1842
+ pool.push(value);
1843
+ }
1844
+ return pool;
1845
+ }
1846
+
1847
+ /**
1848
+ * Keep the historical unambiguous function lookup for unversioned bytecode.
1849
+ * Movie compilation uses the SWF version and the shared spelling map instead.
1850
+ * @param {string} name
1851
+ * @returns {string|null}
1852
+ */
1853
+ _caseVariantFunctionName(name) {
1854
+ if (this.nameSpellings !== undefined || !name || this.functionNames.has(name)) return null;
1855
+ const folded = name.toLowerCase();
1856
+ let match = null;
1857
+ for (const candidate of this.functionNames) {
1858
+ if (candidate.toLowerCase() !== folded) continue;
1859
+ if (match !== null) return null;
1860
+ match = candidate;
1861
+ }
1862
+ return match;
1863
+ }
1864
+
1865
+ /**
1866
+ * @param {string} target
1867
+ * @param {string} idx
1868
+ * @returns {string}
1869
+ */
1870
+ _emitGetProperty(target, idx) {
1871
+ const scope = this._indexedPropertyTarget();
1872
+ if (this._usesSetTarget) return `_getProperty.call(${scope}, ${target}, ${idx})`;
1873
+ const t = (target === '""' || target === "''") ? scope : target === '_root' ? 'root' : target;
1874
+ const prop = /^\d+$/.test(String(idx).trim()) ? PROP_INDEX[Number(idx)] : null;
1875
+ if (prop && Number(idx) !== 13 && Number(idx) < 19 && (t === 'this' || t === 'root' || /^_r\d+$/.test(t))) {
1876
+ return `${t}.${prop}`;
1877
+ }
1878
+ return `_getProperty.call(${scope}, ${target}, ${idx})`;
1879
+ }
1880
+
1881
+ /**
1882
+ * @param {number} idx
1883
+ * @returns {string}
1884
+ */
1885
+ _const(idx) {
1886
+ return `_constantPool[${idx}]`;
1887
+ }
1888
+ }
1889
+
1890
+ // ---- Utilities ----
1891
+
1892
+ const JS_RESERVED = new Set([
1893
+ 'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default',
1894
+ 'delete', 'do', 'else', 'enum', 'export', 'extends', 'false', 'finally', 'for',
1895
+ 'function', 'if', 'import', 'in', 'instanceof', 'new', 'null', 'return', 'super',
1896
+ 'switch', 'this', 'throw', 'true', 'try', 'typeof', 'var', 'void', 'while',
1897
+ 'with', 'yield', 'let', 'static', 'implements', 'interface', 'package', 'private',
1898
+ 'protected', 'public', 'await', 'eval', 'arguments',
1899
+ ]);
1900
+
1901
+ /** Well-known AS2 / JS globals available as runtime bindings. */
1902
+ const AVM1_GLOBALS = new Set([
1903
+ 'String', 'Array', 'Object', 'Number', 'Boolean', 'Date', 'int', 'uint',
1904
+ 'Key', 'System', 'SharedObject', 'TextField', 'MovieClip',
1905
+ 'Sound', 'XML', 'LoadVars', 'Color', 'AsBroadcaster', 'Selection', 'TextFormat',
1906
+ 'ASSetPropFlags', 'ASnative', 'ASconstructor',
1907
+ ]);
1908
+
1909
+ /** Top-level AS2 packages resolve via _global. */
1910
+ const AVM1_PACKAGES = new Set(['mx', 'flash']);
1911
+
1912
+ /** Expressions safe to Dup without materializing to a temp */
1913
+ function _isSimpleStackExpr(v) {
1914
+ if (!v || typeof v !== 'string') return false;
1915
+ const s = v.trim();
1916
+ if (/^(?:null|undefined|true|false|-?\d+(?:\.\d+)?)$/.test(s)) return true;
1917
+ if (/^[_a-zA-Z$][\w$]*$/.test(s)) return true;
1918
+ if (/^_registers\[\d+\]$/.test(s)) return true;
1919
+ if (/^_r\d+$/.test(s) || /^_t\d+$/.test(s) || /^_s\d+$/.test(s)) return true;
1920
+ if (parseStringLiteral(s) != null) return true;
1921
+ // this.foo.bar — property path only (no calls / new)
1922
+ if (/^(?:this|root|globals)(?:\.[a-zA-Z_$][\w$]*)*$/.test(s)) return true;
1923
+ return false;
1924
+ }
1925
+
1926
+ /** AS1 GetProperty / SetProperty numeric indices → browser JS clip fields */
1927
+ const PROP_INDEX = {
1928
+ 0: 'x', 1: 'y', 2: 'scaleX', 3: 'scaleY', 4: 'currentFrame', 5: 'totalFrames',
1929
+ 6: 'alpha', 7: 'visible', 8: 'width', 9: 'height', 10: 'rotation', 11: '_target',
1930
+ 12: 'framesLoaded', 13: 'name', 14: 'dropTarget', 15: 'url', 16: 'highQuality',
1931
+ 17: 'focusRect', 18: 'soundBufTime', 19: 'quality', 20: 'mouseX', 21: 'mouseY',
1932
+ };
1933
+
1934
+ /**
1935
+ * @param {string} name
1936
+ * @returns {string}
1937
+ */
1938
+ function _safeIdent(name) {
1939
+ if (!name) return '';
1940
+ let s = String(name).replace(/[^a-zA-Z0-9_$]/g, '_').replace(/^(\d)/, '_$1');
1941
+ if (JS_RESERVED.has(s)) s = '_' + s;
1942
+ return s;
1943
+ }
1944
+
1945
+ /** Receivers available for every ActionScript frame script. */
1946
+ function isKnownClipExpr(expr) {
1947
+ return expr === 'this' || expr === 'root';
1948
+ }
1949
+
1950
+ /**
1951
+ * @param {string} expr
1952
+ * @returns {string|null}
1953
+ */
1954
+ function parseStringLiteral(expr) {
1955
+ if (!expr || typeof expr !== 'string') return null;
1956
+ const s = expr.trim();
1957
+ if (s.length >= 2 && s[0] === '"' && s[s.length - 1] === '"') {
1958
+ try { return JSON.parse(s); } catch { return null; }
1959
+ }
1960
+ if (s.length >= 2 && s[0] === "'" && s[s.length - 1] === "'") {
1961
+ try { return JSON.parse('"' + s.slice(1, -1).replace(/\\'/g, "'").replace(/"/g, '\\"') + '"'); } catch { return null; }
1962
+ }
1963
+ return null;
1964
+ }
1965
+
1966
+ /**
1967
+ * @param {string} name
1968
+ * @returns {boolean}
1969
+ */
1970
+ function isSafeIdent(name) {
1971
+ return typeof name === 'string' && /^[a-zA-Z_$][\w$]*$/.test(name) && !JS_RESERVED.has(name);
1972
+ }
1973
+
1974
+ /** Decode the conditional catch binding and code blocks in an ActionTry record. */
1975
+ function tryBodySize(data) {
1976
+ return (data[1] | (data[2] << 8)) + (data[3] | (data[4] << 8)) + (data[5] | (data[6] << 8));
1977
+ }
1978
+
1979
+ function parseTryAction(data, body) {
1980
+ if (!data || data.length < 7 || !body) return null;
1981
+ const flags = data[0];
1982
+ const trySize = data[1] | (data[2] << 8);
1983
+ const catchSize = data[3] | (data[4] << 8);
1984
+ const finallySize = data[5] | (data[6] << 8);
1985
+ let offset = 7;
1986
+ let catchName = '';
1987
+ let catchRegister = null;
1988
+ if (flags & 4) {
1989
+ if (offset >= data.length) return null;
1990
+ catchRegister = data[offset++];
1991
+ } else {
1992
+ while (offset < data.length && data[offset] !== 0) {
1993
+ catchName += String.fromCharCode(data[offset++]);
1994
+ }
1995
+ if (offset >= data.length) return null;
1996
+ offset++;
1997
+ }
1998
+ const tryEnd = trySize;
1999
+ const catchEnd = tryEnd + catchSize;
2000
+ const finallyEnd = catchEnd + finallySize;
2001
+ if (offset !== data.length || finallyEnd !== body.length) return null;
2002
+ return {
2003
+ hasCatch: Boolean(flags & 1),
2004
+ hasFinally: Boolean(flags & 2),
2005
+ catchName,
2006
+ catchRegister,
2007
+ tryBody: body.subarray(0, tryEnd),
2008
+ catchBody: body.subarray(tryEnd, catchEnd),
2009
+ finallyBody: body.subarray(catchEnd, finallyEnd),
2010
+ };
2011
+ }
2012
+
2013
+ /**
2014
+ * Read codeSize from a DefineFunction / DefineFunction2 header payload.
2015
+ * @param {number} op
2016
+ * @param {Uint8Array} data
2017
+ * @returns {number}
2018
+ */
2019
+ function readDefineFunctionCodeSize(op, data) {
2020
+ let di = 0;
2021
+ while (di < data.length && data[di] !== 0) di++;
2022
+ di++; // name NUL
2023
+ if (di >= data.length) return 0;
2024
+
2025
+ if (op === OP.DefineFunction) {
2026
+ if (di + 2 > data.length) return 0;
2027
+ const paramCount = data[di] | (data[di + 1] << 8);
2028
+ di += 2;
2029
+ for (let p = 0; p < paramCount; p++) {
2030
+ while (di < data.length && data[di] !== 0) di++;
2031
+ di++;
2032
+ }
2033
+ } else {
2034
+ if (di + 5 > data.length) return 0;
2035
+ const paramCount = data[di] | (data[di + 1] << 8);
2036
+ di += 2;
2037
+ di += 1; // registerCount
2038
+ di += 2; // flags
2039
+ for (let p = 0; p < paramCount; p++) {
2040
+ if (di >= data.length) return 0;
2041
+ di++; // register
2042
+ while (di < data.length && data[di] !== 0) di++;
2043
+ di++;
2044
+ }
2045
+ }
2046
+ if (di + 2 > data.length) return 0;
2047
+ return data[di] | (data[di + 1] << 8);
2048
+ }
2049
+
2050
+ /**
2051
+ * Light post-pass: member dots already preferred at emit; collapse dead temps.
2052
+ * @param {string} src
2053
+ * @returns {string}
2054
+ */
2055
+ export function cleanupAvm1Js(src) {
2056
+ if (!src) return src;
2057
+ let out = src;
2058
+ // var _tN = expr;\n _tN; → expr;
2059
+ out = out.replace(/var (_t\d+) = ([^;]+);\n(\s*)\1;/g, '$3$2;');
2060
+ // Drop empty lines left behind excessively (keep single blanks)
2061
+ out = out.replace(/\n{3,}/g, '\n\n');
2062
+ return out;
2063
+ }
2064
+
2065
+ function _simplifyAvm1Cond(expr) {
2066
+ let s = expr.trim();
2067
+ while (s.startsWith('(') && s.endsWith(')')) {
2068
+ let depth = 0, wraps = true;
2069
+ for (let k = 0; k < s.length - 1; k++) {
2070
+ if (s[k] === '(') depth++;
2071
+ else if (s[k] === ')') depth--;
2072
+ if (depth === 0) { wraps = false; break; }
2073
+ }
2074
+ if (wraps) s = s.slice(1, -1).trim();
2075
+ else break;
2076
+ }
2077
+ return s;
2078
+ }
2079
+
2080
+ function indent(src) {
2081
+ return src.split('\n').map(l => ' ' + l).join('\n');
2082
+ }