@swf2es/web 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +43 -2
  3. package/dist/air-files.d.ts +40 -0
  4. package/dist/air-files.d.ts.map +1 -0
  5. package/dist/air-files.js +304 -0
  6. package/dist/air-files.js.map +1 -0
  7. package/dist/air-items.d.ts +28 -0
  8. package/dist/air-items.d.ts.map +1 -0
  9. package/dist/air-items.js +186 -0
  10. package/dist/air-items.js.map +1 -0
  11. package/dist/air.d.ts +81 -0
  12. package/dist/air.d.ts.map +1 -0
  13. package/dist/air.js +409 -0
  14. package/dist/air.js.map +1 -0
  15. package/dist/config.d.ts +123 -0
  16. package/dist/config.d.ts.map +1 -0
  17. package/dist/config.js +127 -0
  18. package/dist/config.js.map +1 -0
  19. package/dist/element.d.ts +80 -0
  20. package/dist/element.d.ts.map +1 -0
  21. package/dist/element.js +725 -0
  22. package/dist/element.js.map +1 -0
  23. package/dist/external.d.ts +49 -0
  24. package/dist/external.d.ts.map +1 -0
  25. package/dist/external.js +268 -0
  26. package/dist/external.js.map +1 -0
  27. package/dist/index.d.ts +9 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +18 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/layout.d.ts +47 -0
  32. package/dist/layout.d.ts.map +1 -0
  33. package/dist/layout.js +75 -0
  34. package/dist/layout.js.map +1 -0
  35. package/dist/playback.d.ts +107 -0
  36. package/dist/playback.d.ts.map +1 -0
  37. package/dist/playback.js +308 -0
  38. package/dist/playback.js.map +1 -0
  39. package/dist/replace.d.ts +22 -0
  40. package/dist/replace.d.ts.map +1 -0
  41. package/dist/replace.js +141 -0
  42. package/dist/replace.js.map +1 -0
  43. package/dist/stage3d.d.ts +25 -0
  44. package/dist/stage3d.d.ts.map +1 -0
  45. package/dist/stage3d.js +90 -0
  46. package/dist/stage3d.js.map +1 -0
  47. package/package.json +38 -3
  48. package/src/air-files.ts +371 -0
  49. package/src/air-items.ts +217 -0
  50. package/src/air.ts +497 -0
  51. package/src/config.ts +244 -0
  52. package/src/element.ts +902 -0
  53. package/src/external.ts +338 -0
  54. package/src/index.ts +33 -0
  55. package/src/layout.ts +127 -0
  56. package/src/playback.ts +388 -0
  57. package/src/replace.ts +166 -0
  58. package/src/stage3d.ts +112 -0
@@ -0,0 +1,725 @@
1
+ // <swf2es-player>: a SWF on a page as an <embed> showed one, with the
2
+ // embedding's attributes, a load() and destroy() of its own, and the
3
+ // SWF's ExternalInterface callbacks as methods on the element.
4
+ import { isAs3, readActions, readSwf, tags } from "@swf2es/format";
5
+ import { Avm1, Player, Scripting, } from "@swf2es/player";
6
+ import { AIR_DIRECTORIES, AirApp, airAppForSwf, elementWindow, namesAir } from "./air.js";
7
+ import { airFiles } from "./air-files.js";
8
+ import { airItems } from "./air-items.js";
9
+ import { codegenForPlayer, configuration, moduleCacheOptions, playerLibraries, socketHost, workerHostForPlayer, } from "./config.js";
10
+ import { externalInterfaceHost } from "./external.js";
11
+ import { scaleMode } from "./layout.js";
12
+ import { Playback } from "./playback.js";
13
+ export const TAG = "swf2es-player";
14
+ /** In node, which has no DOM, the module still loads, for its other exports. */
15
+ const ElementBase = (globalThis.HTMLElement ?? class {
16
+ });
17
+ /**
18
+ * The DOM's own methods, taken as the module loads and called on the
19
+ * element, never looked up on it: a SWF's callbacks live on the element,
20
+ * and must not reach what it does for itself.
21
+ */
22
+ const dom = globalThis.HTMLElement
23
+ ? {
24
+ getAttribute: Element.prototype.getAttribute,
25
+ hasAttribute: Element.prototype.hasAttribute,
26
+ setAttribute: Element.prototype.setAttribute,
27
+ dispatchEvent: EventTarget.prototype.dispatchEvent,
28
+ focus: HTMLElement.prototype.focus,
29
+ isConnected: Object.getOwnPropertyDescriptor(Node.prototype, "isConnected")?.get,
30
+ id: Object.getOwnPropertyDescriptor(Element.prototype, "id")?.get,
31
+ }
32
+ : null;
33
+ const attribute = (e, name) => dom?.getAttribute.call(e, name) ?? null;
34
+ const hasAttribute = (e, name) => dom?.hasAttribute.call(e, name) ?? false;
35
+ const setAttribute = (e, name, value) => dom?.setAttribute.call(e, name, value);
36
+ const dispatch = (e, event) => dom?.dispatchEvent.call(e, event);
37
+ const focus = (e) => dom?.focus.call(e, { preventScroll: true });
38
+ const connected = (e) => Boolean(dom?.isConnected?.call(e));
39
+ const idOf = (e) => String(dom?.id?.call(e) ?? "");
40
+ function deferred() {
41
+ let resolve;
42
+ let reject;
43
+ const promise = new Promise((ok, fail) => {
44
+ resolve = ok;
45
+ reject = fail;
46
+ });
47
+ // A page that never awaits `ready` should not hear of its failure as unhandled.
48
+ promise.catch(() => { });
49
+ const d = {
50
+ promise,
51
+ settled: false,
52
+ resolve: () => {
53
+ d.settled = true;
54
+ resolve();
55
+ },
56
+ reject: (error) => {
57
+ d.settled = true;
58
+ reject(error);
59
+ },
60
+ };
61
+ return d;
62
+ }
63
+ /** "550" is pixels, as an <embed>'s width is; "100%" and other CSS lengths are themselves. */
64
+ function cssLength(value) {
65
+ if (value === null || value.trim() === "") {
66
+ return null;
67
+ }
68
+ return /^\s*\d+(\.\d+)?\s*$/.test(value) ? `${Number(value)}px` : value.trim();
69
+ }
70
+ /** A colour as Flash's bgcolor gives it, "#RRGGBB" or "RRGGBB"; null for none or another form. */
71
+ export function parseColor(value) {
72
+ const hex = /^\s*#?([0-9a-f]{6})\s*$/i.exec(value ?? "")?.[1];
73
+ return hex ? Number.parseInt(hex, 16) : null;
74
+ }
75
+ /** FlashVars, "name=value&...", URL-encoded, as Flash read them. */
76
+ export function parseFlashVars(value) {
77
+ const vars = {};
78
+ for (const [name, text] of new URLSearchParams(value ?? "")) {
79
+ vars[name] = text;
80
+ }
81
+ return vars;
82
+ }
83
+ /**
84
+ * Whether a SWF from `swfUrl` may script its page, by allowScriptAccess as
85
+ * Flash read it: "always", "never", or by default "sameDomain", the SWF's
86
+ * origin the page's.
87
+ */
88
+ export function scriptAccess(value, swfUrl, pageUrl) {
89
+ switch (value?.toLowerCase()) {
90
+ case "always":
91
+ return true;
92
+ case "never":
93
+ return false;
94
+ default:
95
+ try {
96
+ const origin = new URL(swfUrl, pageUrl).origin;
97
+ // An opaque origin ("null": data:, a sandboxed frame) is no one's domain, not even its own.
98
+ return origin !== "null" && origin === new URL(pageUrl).origin;
99
+ }
100
+ catch {
101
+ return false;
102
+ }
103
+ }
104
+ }
105
+ /** The bytes of "WorkerDomain", the class a SWF's ActionScript names to start a worker. */
106
+ const WORKER_DOMAIN = new TextEncoder().encode("WorkerDomain");
107
+ /**
108
+ * Whether a SWF's ActionScript names WorkerDomain, in its ABCs' strings:
109
+ * one that does may start a worker and wait for it in the same script,
110
+ * which only a Web Worker started ahead can answer.
111
+ */
112
+ export function namesWorkers(swf) {
113
+ const bytes = swf.bytes;
114
+ const first = WORKER_DOMAIN[0];
115
+ for (const tag of swf.tags) {
116
+ if (tag.code !== tags.DoABC && tag.code !== tags.DoABC2) {
117
+ continue;
118
+ }
119
+ const end = tag.offset + tag.length - WORKER_DOMAIN.length;
120
+ for (let at = bytes.indexOf(first, tag.offset); at !== -1 && at <= end;) {
121
+ let k = 1;
122
+ while (k < WORKER_DOMAIN.length && bytes[at + k] === WORKER_DOMAIN[k]) {
123
+ k++;
124
+ }
125
+ if (k === WORKER_DOMAIN.length) {
126
+ return true;
127
+ }
128
+ at = bytes.indexOf(first, at + 1);
129
+ }
130
+ }
131
+ return false;
132
+ }
133
+ /**
134
+ * How long a SWF that names workers waits for the Web Workers started
135
+ * ahead before its first frame: past it, it plays on, and a worker it
136
+ * starts takes one still loading.
137
+ */
138
+ const READY_WAIT = 10_000;
139
+ /** A player's Web Workers, or none where their module does not load, as under an import map that does not name it. */
140
+ async function workersOrNone(ahead) {
141
+ try {
142
+ return await workerHostForPlayer(ahead);
143
+ }
144
+ catch (error) {
145
+ console.warn(`swf2es: workers are off, as their host did not load: ${error}`);
146
+ return null;
147
+ }
148
+ }
149
+ /** Flash's quality names; the auto ones as what they start at. */
150
+ function quality(value) {
151
+ const named = (value ?? "high").toUpperCase();
152
+ if (named === "AUTOLOW") {
153
+ return "LOW";
154
+ }
155
+ return ["LOW", "MEDIUM", "HIGH", "BEST"].includes(named) ? named : "HIGH";
156
+ }
157
+ /** The SWF at `url`, by the embedder's fetch where it gave one, and the URL a redirect took it to. */
158
+ async function fetchMovie(url, signal) {
159
+ const fetchOf = configuration().fetch;
160
+ if (fetchOf) {
161
+ const result = await fetchOf({ url, method: "GET", headers: [], body: null, purpose: "movie" }, signal);
162
+ if (!result.bytes) {
163
+ throw new Error(`swf2es: ${result.status} for ${url}`);
164
+ }
165
+ return { bytes: result.bytes, url: result.url ?? url };
166
+ }
167
+ const response = await fetch(url, { signal });
168
+ if (!response.ok) {
169
+ throw new Error(`swf2es: ${response.status} for ${url}`);
170
+ }
171
+ return { bytes: new Uint8Array(await response.arrayBuffer()), url: response.url || url };
172
+ }
173
+ /**
174
+ * What a session's SWFs load by: its AIR application's files, then the
175
+ * embedder's fetch or the browser's; `offline` (allowNetworking "none"),
176
+ * nothing past the application's own files, which are no network.
177
+ */
178
+ function fetchFor(session, offline) {
179
+ const fetchOf = offline
180
+ ? () => Promise.reject(new Error("allowNetworking is none"))
181
+ : (configuration().fetch ?? browserFetch);
182
+ const app = session.air?.app;
183
+ if (!app) {
184
+ return fetchOf;
185
+ }
186
+ return (request, signal) => {
187
+ const local = app.fetch(request, session.air?.files);
188
+ if (!local) {
189
+ return fetchOf(request, signal);
190
+ }
191
+ // A file the application does not hold, from the directory it came from.
192
+ const remote = local.bytes ? null : app.remote(request.url);
193
+ return remote ? fetchOf({ ...request, url: remote }, signal) : Promise.resolve(local);
194
+ };
195
+ }
196
+ /** The host's fetch for what a SWF loads: the browser's, its status and headers as they come. */
197
+ async function browserFetch(request, signal) {
198
+ const response = await fetch(request.url, {
199
+ signal,
200
+ method: request.method,
201
+ headers: request.headers.map(([name, value]) => [name, value]),
202
+ body: request.body ? new Uint8Array(request.body).buffer : null,
203
+ });
204
+ const headers = [];
205
+ response.headers.forEach((value, name) => {
206
+ headers.push([name, value]);
207
+ });
208
+ return {
209
+ bytes: response.ok ? new Uint8Array(await response.arrayBuffer()) : null,
210
+ status: response.status,
211
+ headers,
212
+ // Where a redirect took it: the SWF is judged and named by that.
213
+ ...(response.redirected ? { url: response.url } : {}),
214
+ };
215
+ }
216
+ /**
217
+ * Callback names the element refuses though it has no such property:
218
+ * protocols other code looks for on any object. A `then` would make the
219
+ * element a thenable, so that awaiting it, or Promise.resolve(it), would
220
+ * call into the SWF and hang; `toJSON` would answer JSON.stringify, and
221
+ * `handleEvent` would take every event the element is added as a listener for.
222
+ */
223
+ const RESERVED = new Set(["then", "toJSON", "handleEvent"]);
224
+ export class Swf2esPlayerElement extends ElementBase {
225
+ static observedAttributes = [
226
+ "src",
227
+ "width",
228
+ "height",
229
+ "scale",
230
+ "salign",
231
+ "wmode",
232
+ "bgcolor",
233
+ "quality",
234
+ "menu",
235
+ ];
236
+ #session = null;
237
+ #readiness = deferred();
238
+ /** The source the element last loaded, to tell a new src from the one playing. */
239
+ #loaded = null;
240
+ #box;
241
+ #sizing;
242
+ /** The stage's size once a SWF is read, the element's own where the page gives it none. */
243
+ #stageSize = null;
244
+ constructor() {
245
+ super();
246
+ const shadow = this.attachShadow({ mode: "open" });
247
+ const style = document.createElement("style");
248
+ // :host's rules give way to the page's, which may size it as it likes.
249
+ style.textContent =
250
+ ":host { display: inline-block; position: relative; overflow: hidden; outline: none }" +
251
+ " .box { position: absolute; inset: 0; overflow: hidden }";
252
+ this.#sizing = document.createElement("style");
253
+ this.#box = document.createElement("div");
254
+ this.#box.className = "box";
255
+ shadow.append(style, this.#sizing, this.#box);
256
+ this.#size();
257
+ this.addEventListener("pointerdown", () => focus(this));
258
+ }
259
+ /** Resolves once the SWF loading, or the next one asked for, plays; rejects if it fails. */
260
+ get ready() {
261
+ return this.#readiness.promise;
262
+ }
263
+ /** The player playing, for a host that needs more than the element gives; null before a load and after destroy. */
264
+ get player() {
265
+ return this.#session?.player ?? null;
266
+ }
267
+ /**
268
+ * The WebGL context the player draws with, for a host that measures it (the demo site counts its
269
+ * draw calls); null before a load and after destroy. A lost context comes back as the same
270
+ * object, its extensions anew.
271
+ */
272
+ get gl() {
273
+ return this.#session?.playback?.gl ?? null;
274
+ }
275
+ get src() {
276
+ return attribute(this, "src") ?? "";
277
+ }
278
+ set src(value) {
279
+ setAttribute(this, "src", value);
280
+ }
281
+ connectedCallback() {
282
+ // Focusable, for the keys, as a plug-in's object was.
283
+ if (!hasAttribute(this, "tabindex")) {
284
+ setAttribute(this, "tabindex", "0");
285
+ }
286
+ const src = attribute(this, "src");
287
+ if (src && !this.#session) {
288
+ void this.#load(src);
289
+ }
290
+ }
291
+ disconnectedCallback() {
292
+ // Moved within the page, it is back by the time this runs; taken away, it stops.
293
+ queueMicrotask(() => {
294
+ if (!connected(this)) {
295
+ this.#destroy();
296
+ }
297
+ });
298
+ }
299
+ attributeChangedCallback(name, old, value) {
300
+ if (old === value) {
301
+ return;
302
+ }
303
+ if (name === "src") {
304
+ if (value && connected(this) && value !== this.#loaded) {
305
+ void this.#load(value);
306
+ }
307
+ return;
308
+ }
309
+ if (name === "width" || name === "height") {
310
+ this.#size();
311
+ }
312
+ if (name === "quality" && this.#session?.player) {
313
+ this.#session.player.quality = quality(value);
314
+ }
315
+ if (name === "menu" && this.#session?.player) {
316
+ this.#session.player.showDefaultContextMenu = value?.toLowerCase() !== "false";
317
+ }
318
+ this.#session?.playback?.changed();
319
+ }
320
+ /**
321
+ * Play `source` in place of what plays now: a URL, relative to the page,
322
+ * or the SWF's bytes. Resolves once it plays, and rejects with what kept
323
+ * it from playing, as `ready` does; a load asked for before it played
324
+ * settles it in its place.
325
+ */
326
+ load(source) {
327
+ return this.#load(source);
328
+ }
329
+ /**
330
+ * Play `app`, an AIR application (`openAirApp`), in place of what plays
331
+ * now, as adl runs it: its descriptor's content SWF under AIR's API and
332
+ * its application sandbox, `args` its launch's arguments, this element
333
+ * its window. What it writes outside its directory is kept in IndexedDB
334
+ * by its id for the next time it plays, unless `keepFiles` is false.
335
+ * Resolves and rejects as `load` does. Its NativeApplication's exit stops
336
+ * it, and the element dispatches `airexit` with the code.
337
+ */
338
+ loadAir(app, options = {}) {
339
+ return this.#load(app, options.arguments ?? [], options.keepFiles ?? true);
340
+ }
341
+ #load(source, args = [], keep = true) {
342
+ this.#release();
343
+ if (this.#readiness.settled) {
344
+ this.#readiness = deferred();
345
+ }
346
+ const ready = this.#readiness;
347
+ const session = {
348
+ scripting: null,
349
+ player: null,
350
+ playback: null,
351
+ stage3D: null,
352
+ callbacks: new Set(),
353
+ workers: null,
354
+ abort: new AbortController(),
355
+ air: null,
356
+ };
357
+ if (source instanceof AirApp) {
358
+ this.#playAsAir(session, source, args, keep);
359
+ }
360
+ this.#session = session;
361
+ this.#loaded = typeof source === "string" || source instanceof URL ? String(source) : null;
362
+ void this.#start(source instanceof AirApp ? null : source, session, ready);
363
+ return ready.promise;
364
+ }
365
+ /**
366
+ * `session` playing `app`, with `args` its launch's arguments and this
367
+ * element its window, its files kept in IndexedDB where `keep`.
368
+ */
369
+ #playAsAir(session, app, args, keep) {
370
+ const exit = (code) => {
371
+ // After the script that called it, which a destroy would pull from under it.
372
+ queueMicrotask(() => {
373
+ if (this.#session === session) {
374
+ this.#destroy();
375
+ dispatch(this, new CustomEvent("airexit", { detail: { code } }));
376
+ }
377
+ });
378
+ };
379
+ const files = airFiles(app.descriptor.id, AIR_DIRECTORIES, keep);
380
+ const items = airItems(app.descriptor.id);
381
+ session.air = {
382
+ app,
383
+ application: app.application(elementWindow(this, app.descriptor.title), args, exit),
384
+ fileSystem: app.fileSystem(files.files),
385
+ files: files.files,
386
+ items: items.items,
387
+ release: () => {
388
+ files.release();
389
+ items.release();
390
+ },
391
+ };
392
+ }
393
+ async #start(source, session, ready) {
394
+ const current = () => this.#session === session;
395
+ try {
396
+ const pageUrl = document.baseURI;
397
+ const base = attribute(this, "base");
398
+ let bytes;
399
+ let url;
400
+ if (session.air) {
401
+ // The content SWF, by the app: URL adl names it with.
402
+ const content = session.air.app.descriptor.content;
403
+ bytes = session.air.app.read(content);
404
+ url = `app:/${content.split("/").map(encodeURIComponent).join("/")}`;
405
+ }
406
+ else if (source === null) {
407
+ throw new Error("swf2es: nothing to play");
408
+ }
409
+ else if (typeof source === "string" || source instanceof URL) {
410
+ ({ bytes, url } = await fetchMovie(new URL(source, pageUrl).href, session.abort.signal));
411
+ }
412
+ else {
413
+ // A copy: the page may reuse its buffer.
414
+ bytes = new Uint8Array(source instanceof Uint8Array ? source : new Uint8Array(source));
415
+ url = base ? new URL(base, pageUrl).href : pageUrl;
416
+ }
417
+ if (!current()) {
418
+ return;
419
+ }
420
+ const swf = readSwf(bytes);
421
+ // A SWF that names what only AIR has plays as an AIR application, as
422
+ // adl would run it, rather than fail as Flash Player's plugin does.
423
+ if (!session.air && !configuration().air && isAs3(swf) && namesAir(swf)) {
424
+ const app = airAppForSwf(bytes, url);
425
+ this.#playAsAir(session, app, [], true);
426
+ url = `app:/${encodeURIComponent(app.descriptor.content)}`;
427
+ }
428
+ // What the application wrote and kept when it last played, before it plays.
429
+ if (session.air) {
430
+ await Promise.all([session.air.files.ready, session.air.items.ready]);
431
+ if (!current()) {
432
+ return;
433
+ }
434
+ }
435
+ // An AIR application's window is the size its descriptor gives, where it gives one.
436
+ const descriptor = session.air?.app.descriptor;
437
+ this.#stageSize = [
438
+ descriptor?.width ?? Math.round((swf.frameSize.xMax - swf.frameSize.xMin) / 20),
439
+ descriptor?.height ?? Math.round((swf.frameSize.yMax - swf.frameSize.yMin) / 20),
440
+ ];
441
+ this.#size();
442
+ const scripted = isAs3(swf) && swf.tags.some((t) => t.code === tags.DoABC || t.code === tags.DoABC2);
443
+ if (scripted) {
444
+ const [codegen, abcs] = await Promise.all([
445
+ codegenForPlayer(),
446
+ playerLibraries(session.air !== null || !!configuration().air),
447
+ ]);
448
+ if (!current()) {
449
+ return;
450
+ }
451
+ const host = this.#workers() ? await workersOrNone(namesWorkers(swf)) : null;
452
+ if (!current()) {
453
+ host?.release?.();
454
+ return;
455
+ }
456
+ session.workers = host;
457
+ session.scripting = this.#scripting(session, codegen, url, pageUrl, host);
458
+ const stage3D = configuration().stage3D;
459
+ if (stage3D) {
460
+ const { Stage3DSession } = await import("./stage3d.js");
461
+ if (!current()) {
462
+ return;
463
+ }
464
+ session.stage3D = new Stage3DSession(this.#box, session.scripting, stage3D, () => session.playback?.invalidate());
465
+ }
466
+ await session.scripting.loadLibraries(abcs);
467
+ if (!current()) {
468
+ return;
469
+ }
470
+ }
471
+ // An AVM1 SWF's actions, compiled by the same codegen.
472
+ let avm1 = null;
473
+ if (!isAs3(swf) && readActions(swf).blocks.length > 0) {
474
+ const codegen = await codegenForPlayer();
475
+ if (!current()) {
476
+ return;
477
+ }
478
+ // Its URL keys its SharedObjects, as a page's AS3 SWFs' are. Its
479
+ // fscommand, getURL and ExternalInterface reach the page as an AS3
480
+ // SWF's do: "quit" goes to the page, as a plug-in's did, and stops
481
+ // nothing.
482
+ const { internal, offline, allows, objectID } = this.#access(pageUrl);
483
+ const base = attribute(this, "base");
484
+ avm1 = new Avm1(codegen, {
485
+ url,
486
+ base: base ? new URL(base, pageUrl).href : undefined,
487
+ // XML, LoadVars and XMLSocket reach the network as an AS3 SWF's loads and sockets do.
488
+ fetch: fetchFor(session, offline),
489
+ socket: offline ? undefined : socketHost(),
490
+ sendToUrl: !internal,
491
+ onUncaught: (error) => this.#report(session, error),
492
+ // Asked of the calling SWF, as for an AS3 SWF: a child from another origin is not the main one.
493
+ fsCommand: (command, args, callers) => {
494
+ if (callers.every(allows)) {
495
+ this.#fsCommand(objectID, command, args);
496
+ }
497
+ },
498
+ navigate: internal ? null : undefined,
499
+ fileHost: configuration().fileHost,
500
+ externalInterface: this.#externalInterface(session, objectID, allows),
501
+ });
502
+ }
503
+ session.player = new Player(bytes, session.scripting, avm1);
504
+ session.player.quality = quality(attribute(this, "quality"));
505
+ session.player.showDefaultContextMenu = attribute(this, "menu")?.toLowerCase() !== "false";
506
+ session.player.build = configuration().build ?? null;
507
+ const playback = await Playback.create(this.#box, session.player, session.scripting, () => this.#look(), (error) => this.#report(session, error), session.stage3D);
508
+ if (!current()) {
509
+ playback.destroy();
510
+ return;
511
+ }
512
+ session.playback = playback;
513
+ // The workers started ahead, loaded before a script may wait for one;
514
+ // a script that never says it loaded does not keep the SWF from playing.
515
+ if (session.workers) {
516
+ await Promise.race([
517
+ session.workers.ready,
518
+ new Promise((done) => setTimeout(done, READY_WAIT)),
519
+ ]);
520
+ }
521
+ if (!current()) {
522
+ return;
523
+ }
524
+ await session.player.start();
525
+ if (!current()) {
526
+ return;
527
+ }
528
+ playback.run();
529
+ ready.resolve();
530
+ dispatch(this, new Event("load"));
531
+ }
532
+ catch (error) {
533
+ if (!current()) {
534
+ return;
535
+ }
536
+ this.#release();
537
+ ready.reject(error);
538
+ dispatch(this, new CustomEvent("error", { detail: { error } }));
539
+ }
540
+ }
541
+ /** The scripting of a load from `url`, its ExternalInterface and fscommand the page's only for the SWFs it lets script it. */
542
+ #scripting(session, codegen, url, pageUrl, workerHost) {
543
+ const { internal, offline, allows, objectID } = this.#access(pageUrl);
544
+ const base = attribute(this, "base");
545
+ const scripting = new Scripting(codegen, {
546
+ url,
547
+ base: base ? new URL(base, pageUrl).href : undefined,
548
+ parameters: parseFlashVars(attribute(this, "flashvars")),
549
+ fetch: fetchFor(session, offline),
550
+ loadPolicyFile: configuration().loadPolicyFile,
551
+ sandboxType: session.air ? "application" : configuration().sandboxType,
552
+ // An AIR application's: AIR's API, its application and its file system.
553
+ air: session.air !== null || !!configuration().air,
554
+ application: session.air?.application ?? configuration().air?.application,
555
+ fileSystem: session.air?.fileSystem ?? configuration().air?.fileSystem,
556
+ encryptedStore: session.air?.items ?? configuration().air?.encryptedStore,
557
+ socket: offline ? undefined : socketHost(),
558
+ webSocket: offline ? null : undefined,
559
+ navigate: internal ? null : undefined,
560
+ fileHost: configuration().fileHost,
561
+ sendToUrl: !internal,
562
+ externalInterface: this.#externalInterface(session, objectID, allows),
563
+ fsCommand: (command, args, callers) => {
564
+ if (callers.every(allows)) {
565
+ this.#fsCommand(objectID, command, args);
566
+ }
567
+ },
568
+ onUncaught: (error) => this.#report(session, error),
569
+ lazyCompilation: configuration().lazyCompilation,
570
+ workerHost,
571
+ ...moduleCacheOptions(),
572
+ });
573
+ return scripting;
574
+ }
575
+ /** Whether the SWFs the element plays next have workers: its `workers` attribute, else the page's configuration. */
576
+ #workers() {
577
+ switch (attribute(this, "workers")?.trim().toLowerCase()) {
578
+ case "false":
579
+ return false;
580
+ case "true":
581
+ return true;
582
+ default:
583
+ return configuration().workers !== false;
584
+ }
585
+ }
586
+ /** What the element's attributes let a SWF reach of its page and the network. */
587
+ #access(pageUrl) {
588
+ const access = attribute(this, "allowscriptaccess");
589
+ // Flash's allowNetworking: "internal" takes the page's scripting and
590
+ // navigation away, "none" every network access besides.
591
+ const networking = (attribute(this, "allownetworking") ?? "all").toLowerCase();
592
+ const internal = networking === "internal" || networking === "none";
593
+ return {
594
+ internal,
595
+ offline: networking === "none",
596
+ // Asked of the calling SWF, as Flash asked: a child from another origin is not the main SWF.
597
+ allows: (swfUrl) => !internal && scriptAccess(access, swfUrl, pageUrl),
598
+ objectID: idOf(this) || attribute(this, "name") || null,
599
+ };
600
+ }
601
+ /** The page's ExternalInterface for a load, an AS3 or an AVM1 SWF's alike, for the SWFs `allows` lets script it. */
602
+ #externalInterface(session, objectID, allows) {
603
+ const bridge = {
604
+ objectID,
605
+ callback: (name, call) => this.#callback(session, name, call),
606
+ alive: () => this.#session === session,
607
+ };
608
+ return externalInterfaceHost(bridge, (error) => this.#report(session, error), allows);
609
+ }
610
+ /** The SWF's callback `name` on the element, or taken off it, while its load is the one playing. */
611
+ #callback(session, name, call) {
612
+ if (this.#session !== session) {
613
+ return;
614
+ }
615
+ if (call) {
616
+ // Never over what the element is or does, its own methods or the DOM's.
617
+ if ((name in this || RESERVED.has(name)) && !session.callbacks.has(name)) {
618
+ console.warn(`swf2es: the SWF's ExternalInterface callback "${name}" is the element's own; left out`);
619
+ return;
620
+ }
621
+ Object.defineProperty(this, name, {
622
+ value: call,
623
+ configurable: true,
624
+ writable: true,
625
+ enumerable: false,
626
+ });
627
+ session.callbacks.add(name);
628
+ }
629
+ else if (session.callbacks.delete(name)) {
630
+ Reflect.deleteProperty(this, name);
631
+ }
632
+ }
633
+ /** fscommand as Flash's plug-in delivered it, to the page's `<id>_DoFSCommand`, and as an event. */
634
+ #fsCommand(objectID, command, args) {
635
+ dispatch(this, new CustomEvent("fscommand", { detail: { command, args } }));
636
+ const handler = objectID
637
+ ? globalThis[`${objectID}_DoFSCommand`]
638
+ : undefined;
639
+ if (typeof handler === "function") {
640
+ handler(command, args);
641
+ }
642
+ }
643
+ /** An error the SWF's code threw and nothing caught: told, as Flash's debugger told it, and played on. */
644
+ #report(session, error) {
645
+ let text;
646
+ try {
647
+ text = session.scripting ? session.scripting.rt.toString(error) : String(error);
648
+ }
649
+ catch {
650
+ text = String(error);
651
+ }
652
+ console.error(`swf2es: ${text}`);
653
+ }
654
+ #look() {
655
+ return {
656
+ scale: scaleMode(attribute(this, "scale")),
657
+ salign: attribute(this, "salign"),
658
+ wmode: (attribute(this, "wmode") ?? "window").toLowerCase(),
659
+ bgcolor: parseColor(attribute(this, "bgcolor")),
660
+ };
661
+ }
662
+ /** The element's size: its width and height attributes, else its SWF's stage, else Flash's default stage. */
663
+ #size() {
664
+ const [w, h] = this.#stageSize ?? [550, 400];
665
+ const width = cssLength(attribute(this, "width")) ?? `${w}px`;
666
+ const height = cssLength(attribute(this, "height")) ?? `${h}px`;
667
+ this.#sizing.textContent = `:host { width: ${width}; height: ${height} }`;
668
+ }
669
+ /**
670
+ * Stop the SWF and let go of everything it holds: its frames, sounds and
671
+ * audio device, its open sockets and fetches, the renderer and its GL
672
+ * context, the pointer, the keys, and its callbacks on the element. The
673
+ * element stays, and may load another.
674
+ */
675
+ destroy() {
676
+ this.#destroy();
677
+ }
678
+ #destroy() {
679
+ const loading = this.#session !== null && !this.#readiness.settled;
680
+ this.#release();
681
+ this.#loaded = null;
682
+ if (loading) {
683
+ this.#readiness.reject(new Error("swf2es: destroyed before it played"));
684
+ }
685
+ }
686
+ #release() {
687
+ const session = this.#session;
688
+ if (!session) {
689
+ return;
690
+ }
691
+ this.#session = null;
692
+ for (const name of session.callbacks) {
693
+ Reflect.deleteProperty(this, name);
694
+ }
695
+ session.callbacks.clear();
696
+ session.abort.abort();
697
+ session.playback?.destroy();
698
+ session.stage3D?.destroy();
699
+ session.player?.destroy();
700
+ session.scripting?.destroy();
701
+ // Its scripting let it go already, if it had any: a release counts once.
702
+ session.workers?.release?.();
703
+ session.air?.release();
704
+ this.#box.style.background = "";
705
+ }
706
+ }
707
+ /**
708
+ * Define the element as `name`, once; what a page or extension calls
709
+ * before using it, if index.js has not. Whether it is defined: not where
710
+ * there is no registry, as in node or an extension's isolated world,
711
+ * whose `customElements` is null.
712
+ */
713
+ export function defineElement(name = TAG) {
714
+ const registry = globalThis.customElements;
715
+ if (typeof registry !== "object" || registry === null) {
716
+ return false;
717
+ }
718
+ if (!registry.get(name)) {
719
+ // A class of its own for each name: a registry takes a constructor once.
720
+ registry.define(name, class extends Swf2esPlayerElement {
721
+ });
722
+ }
723
+ return true;
724
+ }
725
+ //# sourceMappingURL=element.js.map