-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInterfaceHelper.js
More file actions
282 lines (256 loc) · 7.8 KB
/
InterfaceHelper.js
File metadata and controls
282 lines (256 loc) · 7.8 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
'use strict'
class InterfaceHelper {
static #initiated = false
static #wired = false
static #onInit = null
static #onWorkerAdded = null
static #workers = new Map()
static preInit() {
if (InterfaceHelper.#initiated) {
console.error('InterfaceHelper is already initiated.')
return
}
InterfaceHelper.#initiated = true
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) {
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 === '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 #isSystemPost(data) {
return typeof data === 'object' && data !== null && data.type === 'Post' && data.systemMessage === true
}
static #isPost(data) {
return typeof data === 'object' && data !== null && data.type === 'Post' && data.systemMessage !== true
}
static #isWorkerAddedMessage(message) {
return (
typeof message === 'object' &&
message !== null &&
message.type === 'WorkerAdded' &&
typeof message.slot === 'number'
)
}
static #isKillMessage(message) {
return message === 'Kill' || (typeof message === 'object' && message !== null && message.type === 'Kill')
}
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 (InterfaceHelper.#isKillMessage(data.message) && typeof data.message === 'object' && data.message !== null) {
return InterfaceHelper.#coerceWorkerSlot(data.message.slot ?? 0)
}
return 0
}
static #sendResponse(value, options, messageIndex) {
const t = InterfaceHelper.#target()
if (!t) {
return
}
const executionSteps = options?.executionSteps ?? { toRespond: 0, toTerminate: 0 }
const idx = options?.messageIndex ?? messageIndex
t.postMessage({
type: 'Response',
response: {
value,
executionSteps,
...(typeof idx === 'number' ? { messageIndex: idx } : {}),
...(options?.console ? { console: options.console } : {}),
},
}, '*')
}
static #createWorker() {
/** @type {number | null} */
let lastMessageIndex = null
const worker = {
onMessage: null,
onKilled: null,
respond(value, options) {
InterfaceHelper.#sendResponse(value, options, options?.messageIndex ?? lastMessageIndex)
},
}
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()
InterfaceHelper.#workers.set(workerSlot, worker)
InterfaceHelper.#onWorkerAdded(worker)
return worker
}
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 (InterfaceHelper.#isSystemPost(data)) {
const workerSlot = InterfaceHelper.#workerSlotFromEnvelope(data)
if (InterfaceHelper.#isWorkerAddedMessage(data.message)) {
InterfaceHelper.#attachWorker(data.message.slot)
return
}
if (InterfaceHelper.#isKillMessage(data.message)) {
const worker = InterfaceHelper.#workers.get(workerSlot)
if (!worker) {
InterfaceHelper.#sendResponse('Dead', {}, data.messageIndex)
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 })
}
}
return
}
if (InterfaceHelper.#isPost(data)) {
const workerSlot = InterfaceHelper.#workerSlotFromEnvelope(data)
const worker = InterfaceHelper.#workers.get(workerSlot)
if (!worker) {
return
}
worker._lastMessageIndex = typeof data.messageIndex === 'number' ? data.messageIndex : null
const message = {
data: data.message,
respond(value, options) {
InterfaceHelper.#sendResponse(value, options, data.messageIndex)
},
}
worker.onMessage?.(message)
}
}
}
globalThis.InterfaceHelper = InterfaceHelper
InterfaceHelper.preInit()