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,596 @@
1
+ /**
2
+ * @fileoverview Bundle_Emitter — writes index.html + bundle.js + asset files
3
+ * for a transpiled SWF.
4
+ */
5
+
6
+ import { mkdirSync, writeFileSync, rmSync } from 'fs';
7
+ import { basename, join } from 'path';
8
+ import { createHash } from 'node:crypto';
9
+ import { encodeBitmap, encodeSound, encodeSoundStreamSegments } from './asset-encoder.js';
10
+ import { encodeBrowserFont } from './font-encoder.js';
11
+ import { encodeTimelineDataScript, openPackedTimeline } from './timeline-data-codec.js';
12
+ import { companionSwfKey, embeddedSwfFactorySource } from './embedded-swf.js';
13
+ import { AVM1_RUNTIME_BOOTSTRAP, AVM1_RUNTIME_FACTORY_SOURCE, AVM1_RUNTIME_STUB, SWFLIB_SOURCE } from '../runtime/index.js';
14
+ import { AVM2_RUNTIME_BOOTSTRAP, AVM2_RUNTIME_STUB } from '../runtime/avm2-runtime.js';
15
+ import { createEmbeddedMovieRuntime } from '../runtime/embedded-movie-runtime.js';
16
+ import { installMovieRuntime } from '../runtime/movie-runtime.js';
17
+ import { decodeTag } from '../decoder/tag-decoder.js';
18
+ import { TAG } from '../decoder/tag-types.js';
19
+ import { buildDisplayList, buildSymbolClasses, buildExportAssets } from '../transpiler/timeline/display-list.js';
20
+ import { emitButtonActionTable, generateTimelineEngine, serializeTimelineData, timelineBridgeSource, timelineEngineFactorySource, timelineFactoryBindings, timelineHelpersSource } from '../transpiler/timeline/timeline-codegen.js';
21
+
22
+ /** @import { DiagnosticsCollector } from '../util/diagnostics.js' */
23
+ /** @import { SymbolTable } from '../decoder/symbol-table.js' */
24
+
25
+ /**
26
+ * @typedef {Object} EmitInput
27
+ * @property {import('../model/swf-document.js').SwfHeader} header
28
+ * @property {object[]} tags - decoded tags
29
+ * @property {SymbolTable} symbolTable
30
+ * @property {import('../transpiler/actionscript.js').CompiledActionScript} actionScript
31
+ * @property {object[]} [embeddedSwfs] - precompiled DefineBinaryData movies
32
+ * @property {object[]} [companionSwfs] - precompiled package-relative movies
33
+ * @property {string|null} [backgroundColor] - CSS hex, e.g. "#000000"
34
+ */
35
+
36
+ /**
37
+ * Resolve a unique output folder for `<name>.swf` under `outputDir`.
38
+ * Re-runs overwrite the same folder. Within one CLI invocation, duplicate
39
+ * basenames become name_2, name_3, … (pass `usedNames` to track them).
40
+ *
41
+ * @param {string} swfPath
42
+ * @param {string} outputDir
43
+ * @param {Set<string>} [usedNames]
44
+ * @returns {string} path to the bundle folder
45
+ */
46
+ export function resolveBundleDir(swfPath, outputDir, usedNames) {
47
+ const base = basename(swfPath).replace(/\.swf$/i, '') || 'bundle';
48
+ let name = base;
49
+ if (usedNames) {
50
+ if (usedNames.has(name)) {
51
+ let n = 2;
52
+ while (usedNames.has(`${base}_${n}`)) n++;
53
+ name = `${base}_${n}`;
54
+ }
55
+ usedNames.add(name);
56
+ }
57
+ return join(outputDir, name);
58
+ }
59
+
60
+ /**
61
+ * Collect SetBackgroundColor as a CSS hex string.
62
+ * @param {object[]} tags
63
+ * @returns {string|null}
64
+ */
65
+ export function backgroundFromTags(tags) {
66
+ const bg = tags.find(t => t.type === 'SetBackgroundColor');
67
+ if (!bg || !bg.color) return null;
68
+ const { r, g, b } = bg.color;
69
+ return `#${[r, g, b].map(v => v.toString(16).padStart(2, '0')).join('')}`;
70
+ }
71
+
72
+ /**
73
+ * Emit a runnable bundle folder.
74
+ *
75
+ * @param {EmitInput} input
76
+ * @param {string} swfPath
77
+ * @param {string} outputDir - parent directory (bundle goes in a basename subfolder)
78
+ * @param {DiagnosticsCollector} diagnostics
79
+ * @param {{ usedNames?: Set<string>, externalTimelineData?: boolean, timelineDataMode?: 'plain'|'auto'|'packed', omitEmbeddedSwfBytes?: boolean }} [opts]
80
+ * @returns {{ bundleDir: string, assetCount: number, htmlPath: string, jsPath: string, swflibPath: string, timelineDataPath: string|null, binaryDataPath: string|null, packedTimelineData: boolean }}
81
+ */
82
+ export function emit(input, swfPath, outputDir, diagnostics, opts = {}) {
83
+ const { header, tags, symbolTable, actionScript } = input;
84
+ const backgroundColor = input.backgroundColor ?? backgroundFromTags(tags) ?? '#000000';
85
+
86
+ const bundleDir = resolveBundleDir(swfPath, outputDir, opts.usedNames);
87
+ // Fresh assets folder each emit so deleted characters do not linger
88
+ rmSync(join(bundleDir, 'assets'), { recursive: true, force: true });
89
+ const assetsDir = join(bundleDir, 'assets');
90
+ const stageW = Math.max(1, Math.round((header.frameSize.xMax - header.frameSize.xMin) / 20));
91
+ const stageH = Math.max(1, Math.round((header.frameSize.yMax - header.frameSize.yMin) / 20));
92
+ const frameRate = header.frameRate || 24;
93
+ const frameCount = header.frameCount || 1;
94
+
95
+ const displayList = buildDisplayList(tags, symbolTable, diagnostics, {
96
+ sharedAvm1Runtime: true, swfVersion: header.version, legacyButtonScripts: actionScript.legacyButtonScripts,
97
+ });
98
+ const assetManifest = writeMovieAssets(tags, symbolTable, displayList, assetsDir, 'assets', diagnostics);
99
+ const symbolClasses = buildSymbolClasses(tags);
100
+ const binaryPayloads = [];
101
+ const binaryIndices = new Map();
102
+ function indexBinaryPayload(bytes) {
103
+ if (binaryIndices.has(bytes)) return binaryIndices.get(bytes);
104
+ const index = binaryPayloads.length;
105
+ binaryPayloads.push(bytes);
106
+ binaryIndices.set(bytes, index);
107
+ return index;
108
+ }
109
+ const linkedBinaryData = linkedBinaryDataFor(symbolClasses, symbolTable, indexBinaryPayload);
110
+ const exportAssets = buildExportAssets(tags);
111
+ const externalTimelineData = !!opts.externalTimelineData;
112
+ const childMovies = emitEmbeddedMovies([...(input.embeddedSwfs || []), ...(input.companionSwfs || [])],
113
+ symbolClasses, assetsDir, 'assets', diagnostics, indexBinaryPayload);
114
+ bindImportedSounds(tags, symbolTable, symbolClasses, assetManifest, displayList, childMovies.companionSounds);
115
+ const retainFontLayout = !!(actionScript.needsSwflib || actionScript.avm2Blocks?.length);
116
+ const timelineData = serializeTimelineData(displayList, { frameCount, retainFontLayout });
117
+ const timelineDataScript = externalTimelineData ? encodeTimelineDataScript(timelineData, opts.timelineDataMode) : null;
118
+ if (opts.omitEmbeddedSwfBytes) {
119
+ for (const [index] of childMovies.registrations) {
120
+ if (index !== null) binaryPayloads[index] = null;
121
+ }
122
+ if (binaryPayloads.every(payload => payload == null)) binaryPayloads.length = 0;
123
+ }
124
+ const externalBinaryData = externalTimelineData && binaryPayloads.length > 0;
125
+
126
+ const title = basename(swfPath).replace(/\.swf$/i, '');
127
+ const html = buildHtml({ title, stageW, stageH, backgroundColor, externalTimelineData, externalBinaryData,
128
+ packedTimelineData: !!timelineDataScript?.packed });
129
+ const bundleJs = buildBundleJs({
130
+ stageW,
131
+ stageH,
132
+ frameRate,
133
+ swfVersion: header.version,
134
+ swfBytesTotal: header.fileLength,
135
+ backgroundColor,
136
+ assetManifest,
137
+ actionScriptJs: bundledActionScript(actionScript),
138
+ timelineData,
139
+ buttonActions: emitButtonActionTable(displayList.characters),
140
+ symbolClasses,
141
+ linkedBinaryData,
142
+ binaryPayloads,
143
+ embeddedRegistrations: childMovies.registrations,
144
+ externalTimelineData,
145
+ externalBinaryData,
146
+ exportAssets,
147
+ });
148
+
149
+ const htmlPath = join(bundleDir, 'index.html');
150
+ const jsPath = join(bundleDir, 'bundle.js');
151
+ const swflibPath = join(bundleDir, 'swflib.js');
152
+ const timelineDataPath = externalTimelineData ? join(bundleDir, 'timeline-data.js') : null;
153
+ const binaryDataPath = externalBinaryData ? join(bundleDir, 'binary-data.js') : null;
154
+ writeFileSync(htmlPath, html, 'utf8');
155
+ writeFileSync(jsPath, bundleJs, 'utf8');
156
+ writeFileSync(swflibPath, sharedPlayerSource(), 'utf8');
157
+ if (timelineDataPath) writeFileSync(timelineDataPath, timelineDataScript.source, 'utf8');
158
+
159
+ if (binaryDataPath) {
160
+ writeFileSync(binaryDataPath, `globalThis.__swoofBinaryData = ${JSON.stringify(binaryPayloads)};\n`, 'utf8');
161
+ } else {
162
+ rmSync(join(bundleDir, 'binary-data.js'), { force: true });
163
+ }
164
+
165
+ return {
166
+ bundleDir,
167
+ assetCount: assetManifest.filter(a => a.path).length + childMovies.assetCount,
168
+ htmlPath,
169
+ jsPath,
170
+ swflibPath,
171
+ timelineDataPath,
172
+ binaryDataPath,
173
+ packedTimelineData: !!timelineDataScript?.packed,
174
+ };
175
+ }
176
+
177
+ function sharedPlayerSource() {
178
+ return `${SWFLIB_SOURCE}
179
+ globalThis.__swoof_swflib.createAvm1Runtime = ${AVM1_RUNTIME_FACTORY_SOURCE};
180
+ globalThis.__swoof_swflib.timelineHelpers = ${timelineHelpersSource()};
181
+ globalThis.__swoof_swflib.createTimelineEngine = ${timelineEngineFactorySource()};
182
+ globalThis.__swoof_swflib.createEmbeddedMovieRuntime = ${createEmbeddedMovieRuntime.toString()};
183
+ globalThis.__swoof_swflib.openPackedTimeline = ${openPackedTimeline.toString()};
184
+ (${installMovieRuntime.toString()})(globalThis.__swoof_swflib, globalThis);
185
+ `;
186
+ }
187
+
188
+ function bundledActionScript(actionScript) {
189
+ const source = (actionScript.fullJs || '').replace(AVM1_RUNTIME_STUB, () => AVM1_RUNTIME_BOOTSTRAP);
190
+ return actionScript.avm2Blocks?.length ? source.replace(AVM2_RUNTIME_STUB, () => AVM2_RUNTIME_BOOTSTRAP) : source;
191
+ }
192
+
193
+ function linkedBinaryDataFor(symbolClasses, symbolTable, indexBinaryPayload) {
194
+ const result = [];
195
+ for (const { id, name } of symbolClasses) {
196
+ const character = symbolTable.get(id);
197
+ if (character?.type === 'DefineBinaryData') {
198
+ result.push([name, indexBinaryPayload(Buffer.from(character.rawData).toString('base64'))]);
199
+ }
200
+ }
201
+ return result;
202
+ }
203
+
204
+ function embeddedMovieSlug(linkage) {
205
+ if (!linkage) return '';
206
+ const name = linkage.split('.').pop()
207
+ .replace(/(?:_SWF)?_dataClass$/i, '')
208
+ .replace(/^(?:ressources|resources|embedder)_/i, '')
209
+ .replace(/^Embedder(?=[A-Z])/, '')
210
+ .replace(/^([^_]+)_\1$/i, '$1');
211
+ return name.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase()
212
+ .replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 72);
213
+ }
214
+
215
+ function bindImportedSounds(tags, symbolTable, symbolClasses, assetManifest, displayList, companionSounds) {
216
+ const soundClasses = new Map();
217
+ const occupied = new Set(symbolTable.ids());
218
+ const localClasses = new Set(symbolClasses.map(({ name }) => name.replace('::', '.')));
219
+ for (const tag of tags) {
220
+ if (tag?.type !== 'ImportAssets' && tag?.type !== 'ImportAssets2') continue;
221
+ let key;
222
+ try { key = companionSwfKey(tag.url); } catch (_) { continue; }
223
+ const library = companionSounds.get(key);
224
+ if (!library) continue;
225
+ for (const { id, name } of tag.assets) {
226
+ const className = name.replace('::', '.');
227
+ const asset = library.get(className);
228
+ if (!asset || occupied.has(id)) continue;
229
+ occupied.add(id);
230
+ assetManifest.push({ ...asset, id });
231
+ if (!localClasses.has(className) && !soundClasses.has(className)) soundClasses.set(className, id);
232
+ }
233
+ }
234
+ if (!soundClasses.size) return;
235
+ function bindFrameSounds(frames) {
236
+ for (const frame of frames || []) {
237
+ for (const cue of frame.sounds || []) {
238
+ if (!cue.soundClassName) continue;
239
+ const id = soundClasses.get(cue.soundClassName.replace('::', '.'));
240
+ if (id !== undefined) cue.soundId = id;
241
+ }
242
+ }
243
+ }
244
+ bindFrameSounds(displayList.frames);
245
+ for (const character of Object.values(displayList.characters)) bindFrameSounds(character.frames);
246
+ }
247
+
248
+ function emitEmbeddedMovies(movies, parentSymbolClasses, parentAssetsDir, parentAssetPrefix, diagnostics, indexBinaryPayload) {
249
+ const registrations = [];
250
+ const companionSounds = new Map();
251
+ const usedFolders = new Set();
252
+ const linkages = new Map(parentSymbolClasses.map(({ id, name }) => [id, name]));
253
+ let assetCount = 0;
254
+ for (const movie of movies) {
255
+ const slug = movie.companionUrl
256
+ ? `companion-${embeddedMovieSlug(decodeURIComponent(movie.companionUrl.split('/').at(-1)).replace(/\.swf$/i, '')) || 'movie'}`
257
+ : embeddedMovieSlug(linkages.get(movie.characterId));
258
+ const base = slug || `embedded_${movie.characterId}`;
259
+ let folder = base;
260
+ for (let suffix = 2; usedFolders.has(folder); suffix++) folder = `${base}-${suffix}`;
261
+ usedFolders.add(folder);
262
+ const fileName = slug ? `${folder}.js` : 'movie.js';
263
+ const assetsDir = join(parentAssetsDir, folder);
264
+ const assetPrefix = `${parentAssetPrefix}/${folder}`;
265
+ const script = `${assetPrefix}/${fileName}`;
266
+ if (movie.factorySource != null) {
267
+ mkdirSync(assetsDir, { recursive: true });
268
+ writeFileSync(join(assetsDir, fileName), movie.factorySource, 'utf8');
269
+ registrations.push([null, script, 0, 0, movie.companionUrl]);
270
+ continue;
271
+ }
272
+ const { header, tags, symbolTable, actionScript } = movie;
273
+ const stageW = Math.max(1, Math.round((header.frameSize.xMax - header.frameSize.xMin) / 20));
274
+ const stageH = Math.max(1, Math.round((header.frameSize.yMax - header.frameSize.yMin) / 20));
275
+ const frameRate = header.frameRate || 24;
276
+ const frameCount = header.frameCount || 1;
277
+ const displayList = buildDisplayList(tags, symbolTable, diagnostics, {
278
+ sharedAvm1Runtime: true, swfVersion: header.version, legacyButtonScripts: actionScript.legacyButtonScripts,
279
+ });
280
+ const assetManifest = writeMovieAssets(tags, symbolTable, displayList, assetsDir, assetPrefix, diagnostics);
281
+ assetCount += assetManifest.filter(asset => asset.path).length;
282
+ const symbolClasses = buildSymbolClasses(tags);
283
+ const exportAssets = buildExportAssets(tags);
284
+ if (movie.companionUrl) {
285
+ const audio = new Map(assetManifest.filter(asset => asset.type === 'audio').map(asset => [asset.id, asset]));
286
+ const sounds = new Map();
287
+ for (const { id, name } of [...exportAssets, ...symbolClasses]) {
288
+ if (audio.has(id)) sounds.set(name.replace('::', '.'), audio.get(id));
289
+ }
290
+ companionSounds.set(movie.companionUrl, sounds);
291
+ }
292
+ const children = emitEmbeddedMovies(movie.embeddedSwfs, symbolClasses, assetsDir, assetPrefix, diagnostics, indexBinaryPayload);
293
+ assetCount += children.assetCount;
294
+ registrations.push(...children.registrations);
295
+ const factory = embeddedSwfFactorySource({
296
+ stageW, stageH, frameRate, frameCount, assetManifest, symbolClasses,
297
+ swfVersion: header.version,
298
+ sourceBytes: header.fileLength || movie.bytes?.length || 0,
299
+ linkedBinaryData: linkedBinaryDataFor(symbolClasses, symbolTable, indexBinaryPayload),
300
+ exportAssets,
301
+ timelineJs: generateTimelineEngine(displayList, { frameRate, frameCount, stageW, stageH, embedded: true, sharedFactory: true }),
302
+ actionScriptJs: bundledActionScript(actionScript),
303
+ });
304
+ writeFileSync(join(assetsDir, fileName), `document.currentScript._swoofMovieFactory = ${factory};\n`, 'utf8');
305
+ const registration = [
306
+ movie.bytes ? indexBinaryPayload(Buffer.from(movie.bytes).toString('base64')) : null,
307
+ script, movie.bytes?.length ?? 0, header.version,
308
+ ];
309
+ if (movie.companionUrl) registration.push(movie.companionUrl);
310
+ registrations.push(registration);
311
+ }
312
+ return { registrations, assetCount, companionSounds };
313
+ }
314
+
315
+ function writeMovieAssets(tags, symbolTable, displayList, assetsDir, assetPrefix, diagnostics) {
316
+ mkdirSync(assetsDir, { recursive: true });
317
+ const jpegTablesTag = tags.find(t => t.type === 'JPEGTables');
318
+ const jpegTables = jpegTablesTag ? jpegTablesTag.data : null;
319
+
320
+ const outlineFonts = new Set(Object.values(displayList.characters)
321
+ .filter(character => character.kind === 'edit' && character.outlineFontId != null)
322
+ .map(character => character.outlineFontId));
323
+ const bitmapLeaves = new Set();
324
+ function addBitmapLeaves(placements) {
325
+ for (const { characterId } of placements || []) {
326
+ if (displayList.characters[characterId]?.type === 'bitmap') bitmapLeaves.add(characterId);
327
+ }
328
+ }
329
+ for (const frame of displayList.frames) addBitmapLeaves(frame.places);
330
+ for (const info of Object.values(displayList.characters)) {
331
+ for (const frame of info.frames || []) addBitmapLeaves(frame.places);
332
+ for (const records of Object.values(info.buttonStates || {})) addBitmapLeaves(records);
333
+ }
334
+ const fontFiles = new Map();
335
+ const assetManifest = [];
336
+
337
+ for (const id of symbolTable.ids()) {
338
+ const char = symbolTable.get(id);
339
+ if (!char) continue;
340
+
341
+ try {
342
+ if (char.type === 'Bitmap') {
343
+ const encoded = encodeBitmap(char, jpegTables, bitmapLeaves.has(id));
344
+ const fileName = `bitmap_${id}.${encoded.ext}`;
345
+ const relPath = `${assetPrefix}/${fileName}`;
346
+ writeFileSync(join(assetsDir, fileName), encoded.data);
347
+ let alphaPath;
348
+ if (encoded.alphaData) {
349
+ const alphaName = `bitmap_${id}.alpha.${encoded.alphaExt || 'png'}`;
350
+ alphaPath = `${assetPrefix}/${alphaName}`;
351
+ writeFileSync(join(assetsDir, alphaName), encoded.alphaData);
352
+ }
353
+ assetManifest.push({
354
+ id,
355
+ type: 'bitmap',
356
+ mimeType: encoded.mimeType,
357
+ path: relPath,
358
+ alphaPath,
359
+ width: encoded.width || char.width,
360
+ height: encoded.height || char.height,
361
+ maskCoverage: encoded.maskCoverage,
362
+ });
363
+ } else if (char.type === 'Sound') {
364
+ const encoded = encodeSound(char);
365
+ if (encoded.warning) {
366
+ diagnostics.warn(encoded.warning, 'emit', { characterId: id, codecId: char.codecId });
367
+ }
368
+ const fileName = `sound_${id}.${encoded.ext}`;
369
+ const relPath = `${assetPrefix}/${fileName}`;
370
+ writeFileSync(join(assetsDir, fileName), encoded.data);
371
+ assetManifest.push({
372
+ id,
373
+ type: 'audio',
374
+ mimeType: encoded.mimeType,
375
+ path: relPath,
376
+ sampleRate: encoded.sampleRate ?? (char.sampleRate || 44100),
377
+ sampleCount: encoded.sampleCount ?? (char.sampleCount || 0),
378
+ });
379
+ } else if (char.type === 'Font' && (outlineFonts.has(id) || (char.version === 4 && char.fontData))) {
380
+ const bytes = encodeBrowserFont(char);
381
+ if (!bytes) continue;
382
+ const family = 'swoof-' + createHash('sha256').update(bytes).digest('hex').slice(0, 24);
383
+ let fileName = fontFiles.get(family);
384
+ if (!fileName) {
385
+ const name = embeddedMovieSlug(char.name);
386
+ fileName = name ? `font-${name}-${id}.js` : `font-${id}.js`;
387
+ const data = JSON.stringify(bytes.toString('base64'));
388
+ // A classic script carries the bytes through file:// as well as HTTP.
389
+ writeFileSync(join(assetsDir, fileName), `document.currentScript._swoofFontBytes = ${data};\n`, 'utf8');
390
+ fontFiles.set(family, fileName);
391
+ }
392
+ assetManifest.push({ id, type: 'font', path: `${assetPrefix}/${fileName}`, family, fontName: char.name, fontVersion: char.version,
393
+ bold: !!(char.flags & 0x01), italic: !!(char.flags & 0x02) });
394
+ }
395
+ } catch (err) {
396
+ if (char.type === 'Font') {
397
+ diagnostics.warn(`Failed to package font ${id}: ${err.message}`, 'emit', { characterId: id });
398
+ continue;
399
+ }
400
+ diagnostics.error(
401
+ `Failed to encode asset character ${id}: ${err.message}`,
402
+ 'emit',
403
+ { characterId: id, type: char.type }
404
+ );
405
+ assetManifest.push({
406
+ id,
407
+ type: char.type === 'Sound' ? 'audio' : 'bitmap',
408
+ mimeType: 'application/octet-stream',
409
+ path: '',
410
+ });
411
+ }
412
+ }
413
+
414
+ let nextSegmentId = -2000000;
415
+ function emitStreamSegments(segments, prefix, baseId, spriteId) {
416
+ for (const [index, segment] of segments.entries()) {
417
+ const { start, end, encoded } = segment;
418
+ if (!encoded) continue;
419
+ if (encoded.warning) diagnostics.warn(encoded.warning, 'emit', spriteId == null
420
+ ? undefined : { characterId: spriteId, stream: true });
421
+ if (!encoded.data.length) continue;
422
+ const fileName = `${prefix}${index ? '_' + index : ''}.${encoded.ext}`;
423
+ writeFileSync(join(assetsDir, fileName), encoded.data);
424
+ assetManifest.push({
425
+ id: index ? nextSegmentId-- : baseId,
426
+ type: 'audio', mimeType: encoded.mimeType, path: `${assetPrefix}/${fileName}`,
427
+ stream: true, ...(spriteId == null ? {} : { spriteStream: spriteId }),
428
+ streamSync: encoded.streamSync,
429
+ ...(segments.length > 1 ? { streamStart: start, streamEnd: end } : {}),
430
+ });
431
+ }
432
+ }
433
+ emitStreamSegments(encodeSoundStreamSegments(tags), 'sound_stream', -1);
434
+ const streamTags = new Set([TAG.SoundStreamHead, TAG.SoundStreamHead2, TAG.SoundStreamBlock, TAG.ShowFrame]);
435
+ for (const [id, info] of Object.entries(displayList.characters)) {
436
+ if (info?.type !== 'sprite' || !info.hasStream) continue;
437
+ const spriteId = Number(id) | 0;
438
+ // Frame summaries retain the current header only. The raw tags retain
439
+ // its exact position relative to the packet within a shared frame.
440
+ const ordered = symbolTable.get(spriteId).tags.filter(tag => streamTags.has(tag.code))
441
+ .map(tag => decodeTag(tag, null, diagnostics));
442
+ emitStreamSegments(encodeSoundStreamSegments(ordered), `sound_stream_sprite_${id}`,
443
+ -1000000 - spriteId, spriteId);
444
+ }
445
+ return assetManifest;
446
+ }
447
+
448
+ /**
449
+ * @param {{ title: string, stageW: number, stageH: number, backgroundColor: string, includeSwflib?: boolean, externalTimelineData?: boolean, externalBinaryData?: boolean, packedTimelineData?: boolean }} opts
450
+ * @returns {string}
451
+ */
452
+ function buildHtml(opts) {
453
+ const { title, stageW, stageH, backgroundColor,
454
+ externalTimelineData, externalBinaryData, packedTimelineData } = opts;
455
+ const scriptFiles = ['swflib.js',
456
+ ...(externalBinaryData ? ['binary-data.js'] : []),
457
+ ...(externalTimelineData ? ['timeline-data.js'] : []),
458
+ ...(packedTimelineData ? [] : ['bundle.js'])];
459
+ const scripts = scriptFiles.map(file => ` <script src="${file}"></script>`).join('\n');
460
+ return `<!DOCTYPE html>
461
+ <html lang="en">
462
+ <head>
463
+ <meta charset="utf-8">
464
+ <meta name="viewport" content="width=device-width, initial-scale=1">
465
+ <title>${escapeHtml(title)}</title>
466
+ <style>
467
+ * { box-sizing: border-box; margin: 0; padding: 0; }
468
+ html, body {
469
+ width: 100%; height: 100%;
470
+ background: #111;
471
+ display: flex;
472
+ align-items: center;
473
+ justify-content: center;
474
+ overflow: hidden;
475
+ }
476
+ #stage-wrap {
477
+ position: relative;
478
+ aspect-ratio: ${stageW} / ${stageH};
479
+ width: min(100vw, ${stageW}px, calc(100vh * ${stageW} / ${stageH}));
480
+ height: auto;
481
+ max-height: 100vh;
482
+ background: ${backgroundColor};
483
+ }
484
+ #stage {
485
+ display: block;
486
+ width: 100%;
487
+ height: 100%;
488
+ }
489
+ /* HTML overlay in stage-pixel space, scaled to match the canvas CSS box */
490
+ #stage-hud {
491
+ position: absolute;
492
+ left: 0; top: 0;
493
+ width: ${stageW}px;
494
+ height: ${stageH}px;
495
+ transform-origin: 0 0;
496
+ pointer-events: none;
497
+ overflow: hidden;
498
+ }
499
+ #stage-hud .swoof-hud {
500
+ position: absolute;
501
+ pointer-events: auto;
502
+ box-sizing: border-box;
503
+ line-height: 1.15;
504
+ white-space: pre-wrap;
505
+ overflow: hidden;
506
+ border: none;
507
+ background: transparent;
508
+ color: #f0f0f0;
509
+ font-family: Arial, Helvetica, sans-serif;
510
+ margin: 0;
511
+ padding: 0;
512
+ cursor: default;
513
+ }
514
+ #stage-hud button.swoof-hud {
515
+ cursor: pointer;
516
+ background: rgba(255,255,255,0.08);
517
+ border: 1px solid rgba(255,255,255,0.35);
518
+ color: #fff;
519
+ }
520
+ #stage-hud button.swoof-hud:hover {
521
+ background: rgba(255,255,255,0.18);
522
+ }
523
+ #stage-hud input.swoof-hud, #stage-hud textarea.swoof-hud {
524
+ background: rgba(0,0,0,0.35);
525
+ border: 1px solid rgba(255,255,255,0.25);
526
+ color: #fff;
527
+ padding: 2px 4px;
528
+ }
529
+ #stage-hud textarea.swoof-hud {
530
+ resize: none;
531
+ }
532
+ </style>
533
+ </head>
534
+ <body>
535
+ <div id="stage-wrap">
536
+ <canvas id="stage" width="${stageW}" height="${stageH}" aria-label="${escapeHtml(title)}"></canvas>
537
+ <div id="stage-hud" aria-hidden="false"></div>
538
+ </div>
539
+ ${scripts}
540
+ </body>
541
+ </html>
542
+ `;
543
+ }
544
+
545
+ /**
546
+ * @param {object} opts
547
+ * @returns {string}
548
+ */
549
+ function buildBundleJs(opts) {
550
+ const {
551
+ stageW, stageH, frameRate, swfVersion, swfBytesTotal, backgroundColor,
552
+ assetManifest, actionScriptJs, timelineData, buttonActions,
553
+ symbolClasses = [], linkedBinaryData = [], binaryPayloads = [], embeddedRegistrations = [],
554
+ externalTimelineData = false, externalBinaryData = false, exportAssets = [],
555
+ } = opts;
556
+ const movie = {
557
+ stageWidth: stageW, stageHeight: stageH, frameRate, background: backgroundColor,
558
+ swfVersion: swfVersion || 0, swfBytesTotal: swfBytesTotal || 0,
559
+ assets: assetManifest, symbolClasses, exportAssets, linkedBinaryData,
560
+ embeddedMovies: embeddedRegistrations,
561
+ binaryPayloads: externalBinaryData ? null : binaryPayloads,
562
+ };
563
+ const data = externalTimelineData ? 'null' :
564
+ `{ frames: ${timelineData.frames}, characters: ${timelineData.characters}, frameCount: ${timelineData.frameCount}, scenes: ${timelineData.scenes} }`;
565
+ const bindings = `${timelineFactoryBindings}, root, loaded, ctx, canvas,
566
+ bindConstructingDocument, resolveLinkedClass, STAGE_WIDTH, STAGE_HEIGHT, FRAME_RATE, BACKGROUND,
567
+ ASSETS, SYMBOL_CLASSES, EXPORT_ASSETS`;
568
+ return `/* swoof generated movie */
569
+ globalThis.__swoof_swflib.mountMovie({
570
+ ...${JSON.stringify(movie, null, 2)},
571
+ timelineData: ${data},
572
+ }, function (connect) {
573
+ 'use strict';
574
+ var { ${bindings} } = connect({
575
+ ${timelineBridgeSource()},
576
+ get getDefinition() { return typeof _getDefinition === 'function' ? _getDefinition : undefined; },
577
+ }, ${buttonActions});
578
+ var __swoof_root = root;
579
+ var SWF_VERSION = ${Number(swfVersion) || 0};
580
+
581
+ ${actionScriptJs}
582
+ });
583
+ `;
584
+ }
585
+
586
+ /**
587
+ * @param {string} s
588
+ * @returns {string}
589
+ */
590
+ function escapeHtml(s) {
591
+ return String(s)
592
+ .replace(/&/g, '&amp;')
593
+ .replace(/</g, '&lt;')
594
+ .replace(/>/g, '&gt;')
595
+ .replace(/"/g, '&quot;');
596
+ }