-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInterfaceHelper.js
More file actions
445 lines (409 loc) · 13.5 KB
/
Copy pathInterfaceHelper.js
File metadata and controls
445 lines (409 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
'use strict'
/** Resolved while this classic script loads (opaque iframe origins cannot use ES module import). */
const interfaceColorHelperUrl = (() => {
try {
const src = document.currentScript?.src
return src ? new URL('ColorHelper.js', src).href : '/ColorHelper.js'
} catch {
return '/ColorHelper.js'
}
})()
class InterfaceHelper {
static #initiated = false
static #wired = false
static #onInit = null
static #onWorkerAdded = null
static #workers = new Map()
static #pendingPosts = new Map()
static #colorApi = null
static #colorApiPromise = null
static #colorContext = null
static #loadClassicScript(src) {
return new Promise((resolve, reject) => {
for (const existing of document.getElementsByTagName('script')) {
if (existing.src === src) {
if (globalThis.ColorHelper) {
resolve()
return
}
existing.addEventListener('load', () => resolve(), { once: true })
existing.addEventListener('error', () => reject(new Error(`Failed to load ${src}`)), {
once: true,
})
return
}
}
const script = document.createElement('script')
script.src = src
script.onload = () => resolve()
script.onerror = () => reject(new Error(`Failed to load ${src}`))
document.head.appendChild(script)
})
}
static #ensureColorApi() {
if (InterfaceHelper.#colorApi) {
return Promise.resolve(InterfaceHelper.#colorApi)
}
if (globalThis.ColorHelper) {
InterfaceHelper.#colorApi = globalThis.ColorHelper
return Promise.resolve(InterfaceHelper.#colorApi)
}
if (!InterfaceHelper.#colorApiPromise) {
InterfaceHelper.#colorApiPromise = InterfaceHelper.#loadClassicScript(interfaceColorHelperUrl).then(() => {
InterfaceHelper.#colorApi = globalThis.ColorHelper
return InterfaceHelper.#colorApi
})
}
return InterfaceHelper.#colorApiPromise
}
static #refreshColorContext(init) {
const apply = (ColorHelper) => {
InterfaceHelper.#colorContext = ColorHelper.buildInterfaceColorContext(init)
}
if (InterfaceHelper.#colorApi) {
apply(InterfaceHelper.#colorApi)
return Promise.resolve()
}
if (globalThis.ColorHelper) {
InterfaceHelper.#colorApi = globalThis.ColorHelper
apply(InterfaceHelper.#colorApi)
return Promise.resolve()
}
return InterfaceHelper.#ensureColorApi().then(apply)
}
/**
* Arena team/member color aligned with replay colors. When opponent members are not disclosed,
* `memberIndex` is ignored and the team color is returned.
* @param {number} teamIndex
* @param {number} [memberIndex]
* @returns {{ hue: number, saturation: number, lightness: number, R: number, G: number, B: number, RGB: string }}
*/
static GetColor(teamIndex, memberIndex) {
const ColorHelper = InterfaceHelper.#colorApi ?? globalThis.ColorHelper
const context = InterfaceHelper.#colorContext ?? {
layout: { teamCount: 1, membersPerTeam: [1], onlySingleTeams: true },
discloseMembers: 'No',
}
return ColorHelper.getInterfaceColor(teamIndex, memberIndex, context)
}
static preInit() {
if (InterfaceHelper.#initiated) {
console.error('InterfaceHelper is already initiated.')
return
}
InterfaceHelper.#initiated = true
void InterfaceHelper.#ensureColorApi()
const globalStyle = document.createElement('link')
globalStyle.rel = 'stylesheet'
globalStyle.href = '/global.css'
document.head.prepend(globalStyle)
const fallbackStyle = document.createElement('style')
fallbackStyle.textContent = 'html { background-color: var(--main-background-color); }'
document.head.prepend(fallbackStyle)
}
/** Coordinator shell: popup opener or `/join` parent. */
static #target() {
return globalThis.opener ?? globalThis.parent
}
static #ensureWired() {
if (InterfaceHelper.#wired) {
return
}
InterfaceHelper.#wired = true
globalThis.addEventListener('message', InterfaceHelper.#onWindowMessage)
}
/**
* Called once with cloned match settings (`{ settings, opponents, … }`).
* Register workers with the `workerAdded` callback (slot `0` after this handler returns, then each `{ type: 'WorkerAdded', slot }`).
* @param {(init: unknown, workerAdded: (participant: InterfaceHelperWorker) => void) => void} handler
*/
static onInit(handler) {
InterfaceHelper.#onInit = handler
InterfaceHelper.#ensureWired()
}
/**
* @deprecated Register workers via the `workerAdded` argument to {@link InterfaceHelper.onInit} instead.
* @param {(worker: InterfaceHelperWorker) => void} handler
*/
static workerAdded(handler) {
InterfaceHelper.#onWorkerAdded = handler
InterfaceHelper.#ensureWired()
}
static #registerWorker(handler) {
InterfaceHelper.#onWorkerAdded = handler
}
static #dispatchInit(init) {
void InterfaceHelper.#refreshColorContext(init)
.catch((error) => {
console.error(error)
})
.then(() => {
InterfaceHelper.#onInit?.(init, InterfaceHelper.#registerWorker)
InterfaceHelper.#attachWorker(0)
})
}
/** Tell the coordinator the interface applied init and is listening. */
static signalReady() {
const t = InterfaceHelper.#target()
if (t) {
t.postMessage(null, '*')
}
}
/** Coordinator init: `{ settings, opponents }` (see `cloneInterfaceWorkerInit`). */
static #isInit(data) {
if (typeof data !== 'object' || data === null) {
return false
}
const type = data.type
if (
type === 'Post' || type === 'Kill' || type === 'WorkerAdded' || type === 'Response' ||
type === 'Arena-Interface-Ready' || type === 'Arena-Interface-Disconnected'
) {
return false
}
const settings = data.settings
if (settings !== undefined && typeof settings === 'object' && settings !== null) {
return true
}
return data.general !== undefined && typeof data.general === 'object' && data.general !== null
}
static #unwrapPostEnvelope(data) {
if (
typeof data === 'object' &&
data !== null &&
data.type !== 'Post' &&
typeof data.message === 'object' &&
data.message !== null &&
data.message.type === 'Post'
) {
return data.message
}
return data
}
static #isPost(data) {
return typeof data === 'object' && data !== null && data.type === 'Post'
}
static #isDisconnected(data) {
return typeof data === 'object' && data !== null && data.type === 'Arena-Interface-Disconnected'
}
static #showDisconnectedState(label) {
const lock = document.getElementById('lock')
if (!lock) {
return
}
lock.classList.add('engaged')
lock.classList.remove('booting')
const span = lock.querySelector('span')
if (span) {
span.textContent = label
}
}
static #coerceWorkerSlot(value) {
if (typeof value === 'number' && Number.isFinite(value)) {
return value
}
if (typeof value === 'string' && value !== '') {
const n = Number(value)
return Number.isFinite(n) ? n : 0
}
return 0
}
static #workerSlotFromEnvelope(data) {
if (typeof data.workerSlot === 'number') {
return data.workerSlot
}
if (typeof data.workerSlot === 'string') {
return InterfaceHelper.#coerceWorkerSlot(data.workerSlot)
}
if (typeof data.workerName === 'string') {
return data.workerName === '' ? 0 : InterfaceHelper.#coerceWorkerSlot(data.workerName)
}
if (data.type === 'Kill' && typeof data.slot === 'number') {
return InterfaceHelper.#coerceWorkerSlot(data.slot)
}
return 0
}
static #sendResponse(value, options, messageIndex, workerSlot) {
const t = InterfaceHelper.#target()
if (!t) {
return
}
const executionSteps = options?.executionSteps ?? { toRespond: 0, toTerminate: 0 }
const idx = options?.messageIndex ?? messageIndex
const slot = typeof options?.workerSlot === 'number' ? options.workerSlot : workerSlot
t.postMessage({
type: 'Response',
response: {
value,
executionSteps,
...(typeof idx === 'number' ? { messageIndex: idx } : {}),
...(typeof slot === 'number' ? { workerSlot: slot } : {}),
...(options?.console ? { console: options.console } : {}),
},
}, '*')
}
static #createWorker(workerSlot) {
/** @type {number | null} */
let lastMessageIndex = null
const worker = {
onMessage: null,
onKilled: null,
respond(value, options) {
InterfaceHelper.#sendResponse(value, options, options?.messageIndex ?? lastMessageIndex, workerSlot)
},
}
Object.defineProperty(worker, '_lastMessageIndex', {
get: () => lastMessageIndex,
set: (v) => {
lastMessageIndex = v
},
})
return worker
}
static #attachWorker(workerSlot) {
if (!InterfaceHelper.#onWorkerAdded) {
return
}
let worker = InterfaceHelper.#workers.get(workerSlot)
if (worker) {
return worker
}
worker = InterfaceHelper.#createWorker(workerSlot)
InterfaceHelper.#workers.set(workerSlot, worker)
InterfaceHelper.#onWorkerAdded(worker)
const pending = InterfaceHelper.#pendingPosts.get(workerSlot)
if (pending) {
InterfaceHelper.#pendingPosts.delete(workerSlot)
for (const post of pending) {
InterfaceHelper.#deliverPost(post)
}
}
return worker
}
static #deliverPost(data) {
const workerSlot = InterfaceHelper.#workerSlotFromEnvelope(data)
const worker = InterfaceHelper.#workers.get(workerSlot)
if (!worker) {
let pending = InterfaceHelper.#pendingPosts.get(workerSlot)
if (!pending) {
pending = []
InterfaceHelper.#pendingPosts.set(workerSlot, pending)
}
pending.push(data)
return
}
worker._lastMessageIndex = typeof data.messageIndex === 'number' ? data.messageIndex : null
const message = {
data: data.message,
respond(value, options) {
InterfaceHelper.#sendResponse(value, options, data.messageIndex, workerSlot)
},
}
worker.onMessage?.(message)
}
static #onWindowMessage(messageEvent) {
const data = InterfaceHelper.#unwrapPostEnvelope(messageEvent.data)
if (InterfaceHelper.#isDisconnected(data)) {
const label = typeof data.message === 'string' && data.message.trim() ? data.message.trim() : 'Match has ended'
InterfaceHelper.#showDisconnectedState(label)
return
}
if (InterfaceHelper.#isInit(data)) {
InterfaceHelper.#dispatchInit(data)
return
}
if (data.type === 'WorkerAdded' && typeof data.slot === 'number') {
InterfaceHelper.#attachWorker(data.slot)
return
}
if (data.type === 'Kill') {
const workerSlot = InterfaceHelper.#workerSlotFromEnvelope(data)
const worker = InterfaceHelper.#workers.get(workerSlot)
if (!worker) {
InterfaceHelper.#sendResponse('Dead', {}, data.messageIndex, workerSlot)
return
}
let responded = false
const priorRespond = worker.respond
worker.respond = function (value, options) {
responded = true
return priorRespond.call(
this,
value,
{ ...options, messageIndex: options?.messageIndex ?? data.messageIndex },
)
}
worker.onKilled?.()
worker.respond = priorRespond
if (!responded) {
priorRespond.call(worker, 'Dead', { messageIndex: data.messageIndex, workerSlot })
}
return
}
if (InterfaceHelper.#isPost(data)) {
InterfaceHelper.#deliverPost(data)
}
}
static #SEEDRANDOM_URL = 'https://cdnjs.cloudflare.com/ajax/libs/seedrandom/3.0.5/seedrandom.min.js'
static #PARTICIPANT_HELPER_URL = '/ParticipantHelper.js'
static #escapeJsString(value) {
return value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")
}
static #buildNativeParticipantBootstrap(seed) {
return `
ParticipantHelper.preInit();
Math.seedrandom('${InterfaceHelper.#escapeJsString(seed)}');
delete Math.seedrandom;
`.split('\n').map((line) => line.trim()).join('')
}
static #parseParticipantHeader(source) {
try {
return JSON.parse(source.substring(source.indexOf('/**') + 3, source.indexOf('**/')))
} catch {
return {}
}
}
/** Unwrap {@link CreateParticipantWorker} `Response` envelopes for {@link InterfaceHelperWorker.respond}. */
static participantWorkerResponse(data) {
if (typeof data === 'object' && data !== null && data.type === 'Response' && typeof data.response === 'object' && data.response !== null && 'value' in data.response) {
return data.response.value
}
return data
}
/**
* Fetch a participant script, load {@link ParticipantHelper}, and spawn a worker.
* @param {string} url Participant script URL
* @param {{ seed?: string, system?: string[] }} [options]
* @returns {Promise<Worker>}
*/
static CreateParticipantWorker(url, options = {}) {
const seed = options.seed ?? ''
const systemScripts = options.system ?? [InterfaceHelper.#SEEDRANDOM_URL]
return Promise.all([
fetch(url).then((response) => response.text()),
fetch(InterfaceHelper.#PARTICIPANT_HELPER_URL).then((response) => response.text()),
]).then(async ([participantSource, participantHelperSource]) => {
const header = InterfaceHelper.#parseParticipantHeader(participantSource)
const scope = url.slice(0, url.lastIndexOf('/') + 1)
const dependencyUrls = (header.dependencies ?? []).map((dependency) => scope + dependency)
const dependencySources = await Promise.all(dependencyUrls.map((dependencyUrl) => fetch(dependencyUrl).then((response) => response.text())))
let script = ''
if (systemScripts.length) {
script += `importScripts(${systemScripts.map((systemUrl) => JSON.stringify(systemUrl)).join(', ')});\n`
}
script += participantHelperSource + '\n'
script += InterfaceHelper.#buildNativeParticipantBootstrap(seed) + '\n'
for (const dependencySource of dependencySources) {
script += dependencySource + '\n'
}
script += participantSource + '\n'
script += 'ParticipantHelper.signalReady();\n'
const blobUrl = URL.createObjectURL(new Blob([script], { type: 'application/javascript' }))
const worker = new Worker(blobUrl)
worker.addEventListener('message', () => URL.revokeObjectURL(blobUrl), { once: true })
return worker
})
}
}
globalThis.InterfaceHelper = InterfaceHelper
InterfaceHelper.preInit()