asma-core-helpers 0.41.0 → 0.41.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 (46) hide show
  1. package/lib/collaboration/applyOperation.d.ts.map +1 -1
  2. package/lib/collaboration/applyOperation.js +108 -0
  3. package/lib/collaboration/applyOperation.js.map +1 -1
  4. package/lib/collaboration/index.d.ts +1 -0
  5. package/lib/collaboration/index.d.ts.map +1 -1
  6. package/lib/collaboration/index.js +1 -0
  7. package/lib/collaboration/index.js.map +1 -1
  8. package/lib/collaboration/narrativePresence.d.ts +12 -0
  9. package/lib/collaboration/narrativePresence.d.ts.map +1 -0
  10. package/lib/collaboration/narrativePresence.js +34 -0
  11. package/lib/collaboration/narrativePresence.js.map +1 -0
  12. package/lib/collaboration/operations.d.ts +26 -1
  13. package/lib/collaboration/operations.d.ts.map +1 -1
  14. package/lib/collaboration/operations.js +1 -0
  15. package/lib/collaboration/operations.js.map +1 -1
  16. package/lib/collaboration/schemas.d.ts +44 -1
  17. package/lib/collaboration/schemas.d.ts.map +1 -1
  18. package/lib/collaboration/schemas.js +18 -1
  19. package/lib/collaboration/schemas.js.map +1 -1
  20. package/lib/collaboration/templateAuthoringMeta.d.ts +4 -4
  21. package/lib/collaboration/templateAuthoringMeta.d.ts.map +1 -1
  22. package/lib/collaboration/templateAuthoringMeta.js +103 -5
  23. package/lib/collaboration/templateAuthoringMeta.js.map +1 -1
  24. package/lib/collaboration/templateDocument.d.ts +9 -2
  25. package/lib/collaboration/templateDocument.d.ts.map +1 -1
  26. package/lib/collaboration/templateDocument.js.map +1 -1
  27. package/lib/g-definitions.d.ts +5 -0
  28. package/lib/g-definitions.d.ts.map +1 -1
  29. package/lib/g-definitions.js +6 -0
  30. package/lib/g-definitions.js.map +1 -1
  31. package/lib/overlayBack.d.ts +103 -0
  32. package/lib/overlayBack.d.ts.map +1 -0
  33. package/lib/overlayBack.js +540 -0
  34. package/lib/overlayBack.js.map +1 -0
  35. package/package.json +2 -1
  36. package/src/collaboration/applyOperation.ts +114 -0
  37. package/src/collaboration/index.ts +1 -0
  38. package/src/collaboration/narrativePresence.test.ts +328 -0
  39. package/src/collaboration/narrativePresence.ts +42 -0
  40. package/src/collaboration/operations.ts +11 -0
  41. package/src/collaboration/schemas.ts +27 -2
  42. package/src/collaboration/templateAuthoringMeta.ts +107 -6
  43. package/src/collaboration/templateDocument.ts +14 -4
  44. package/src/g-definitions.ts +13 -0
  45. package/src/overlayBack.test.ts +742 -0
  46. package/src/overlayBack.ts +647 -0
@@ -0,0 +1,742 @@
1
+ import assert from 'node:assert/strict'
2
+ import { describe, it } from 'node:test'
3
+
4
+ import { createBrowserHistory } from 'history'
5
+ import type { History } from 'history'
6
+ import { JSDOM } from 'jsdom'
7
+
8
+ import {
9
+ __inspectOverlayBackForTests__,
10
+ finishOverlayBackInstall,
11
+ installOverlayBackPopstateListener,
12
+ } from './overlayBack.ts'
13
+
14
+ function createTestWindow(url: string): Window {
15
+ const dom = new JSDOM('', { url, pretendToBeVisual: true })
16
+ return dom.window as unknown as Window
17
+ }
18
+
19
+ /** Mirrors `getHistory()`'s own ordering: the popstate listener must be installed before
20
+ * `createBrowserHistory()` runs (CON-002). Each test gets its own fresh window, which is itself
21
+ * how the global singleton is reset between tests. Does not simulate a gesture, so the arming
22
+ * gate fails by default — use `setUp()` for tests that need an armed guard. */
23
+ function setUpAdapter(url: string) {
24
+ const win = createTestWindow(url)
25
+ const adapter = installOverlayBackPopstateListener(win)
26
+ const history: History = createBrowserHistory({ window: win as unknown as Window & typeof globalThis })
27
+ finishOverlayBackInstall(win, history)
28
+ return { win, adapter, history }
29
+ }
30
+
31
+ /** jsdom cannot dispatch a genuinely trusted event, so the arming gate's gesture side is
32
+ * simulated by writing directly to the live internal state (see
33
+ * `__inspectOverlayBackForTests__`'s doc comment). */
34
+ function simulateTrustedGesture(win: Window): void {
35
+ const internal = __inspectOverlayBackForTests__(win)
36
+ if (internal) {
37
+ internal.lastGestureAt = Date.now()
38
+ }
39
+ }
40
+
41
+ /** Same as `setUpAdapter`, plus a simulated trusted gesture, so `register()` passes the arming
42
+ * gate — the shape every non-gate-focused test in this suite needs. */
43
+ function setUp(url: string) {
44
+ const result = setUpAdapter(url)
45
+ simulateTrustedGesture(result.win)
46
+ return result
47
+ }
48
+
49
+ async function waitUntil(predicate: () => boolean, timeoutMs = 2000): Promise<void> {
50
+ const start = Date.now()
51
+ while (!predicate()) {
52
+ if (Date.now() - start > timeoutMs) {
53
+ throw new Error('waitUntil: timed out waiting for condition')
54
+ }
55
+ await new Promise((resolve) => setTimeout(resolve, 0))
56
+ }
57
+ }
58
+
59
+ function dispatchPersistedPageShow(win: Window): void {
60
+ const event = new win.Event('pageshow')
61
+ Object.defineProperty(event, 'persisted', { value: true })
62
+ win.dispatchEvent(event)
63
+ }
64
+
65
+ describe('overlayBack adapter', () => {
66
+ it('TEST-001: arm clones usr, key and idx, keeps unknown fields, and leaves the URL unchanged', () => {
67
+ const { win, adapter } = setUp('https://example.test/orders')
68
+ win.history.replaceState(
69
+ { usr: { foo: 'bar' }, key: 'base-key', idx: 3, customField: 'keep-me' },
70
+ '',
71
+ win.location.href,
72
+ )
73
+ const hrefBefore = win.location.href
74
+
75
+ adapter.enabled = true
76
+ const unregister = adapter.register(() => {})
77
+
78
+ const state = win.history.state as Record<string, unknown>
79
+ assert.deepEqual(state.usr, { foo: 'bar' })
80
+ assert.equal(state.key, 'base-key')
81
+ assert.equal(state.idx, 3)
82
+ assert.equal(state.customField, 'keep-me')
83
+ assert.equal(win.location.href, hrefBefore)
84
+
85
+ const marker = state.__asmaOverlayBack as { v: number; s: string; m: string }
86
+ assert.equal(marker.v, 1)
87
+ assert.equal(typeof marker.s, 'string')
88
+ assert.equal(typeof marker.m, 'string')
89
+
90
+ unregister()
91
+ })
92
+
93
+ it('TEST-002: owned hops bypass history.listen and history.block; a foreign popstate passes through', async () => {
94
+ const { win, adapter, history } = setUp('https://example.test/list')
95
+ adapter.enabled = true
96
+
97
+ let listenCalls = 0
98
+ history.listen(() => {
99
+ listenCalls += 1
100
+ })
101
+ let blockCalls = 0
102
+ const unblock = history.block(() => {
103
+ blockCalls += 1
104
+ })
105
+
106
+ let closeCalls = 0
107
+ const unregister = adapter.register(() => {
108
+ closeCalls += 1
109
+ })
110
+
111
+ // Registered after the adapter and after history@5, so it only stays silent when the adapter
112
+ // actually stops the event. history.listen stays at 0 either way: the guard clones idx, so
113
+ // history@5 sees a zero delta and ignores the pop on its own.
114
+ let lateCalls = 0
115
+ win.addEventListener('popstate', () => {
116
+ lateCalls += 1
117
+ })
118
+
119
+ win.history.back()
120
+ await waitUntil(() => closeCalls === 1)
121
+
122
+ assert.equal(listenCalls, 0)
123
+ assert.equal(blockCalls, 0)
124
+ assert.equal(lateCalls, 0)
125
+
126
+ const forgedState = {
127
+ ...(win.history.state as Record<string, unknown>),
128
+ key: 'forged-key',
129
+ __asmaOverlayBack: { v: 1, s: 'forged-session', m: 'forged-marker' },
130
+ }
131
+ win.history.pushState(forgedState, '', win.location.href)
132
+ win.dispatchEvent(new win.PopStateEvent('popstate'))
133
+ assert.equal(lateCalls, 1)
134
+ assert.equal(closeCalls, 2)
135
+
136
+ unblock()
137
+ unregister()
138
+ await waitUntil(() => __inspectOverlayBackForTests__(win)?.guard === null)
139
+
140
+ let foreignListenCalls = 0
141
+ history.listen(() => {
142
+ foreignListenCalls += 1
143
+ })
144
+ history.push('/other')
145
+ // The push itself notifies listeners synchronously — isolate the baseline from it so the
146
+ // assertion below can only be satisfied by the back()'s popstate, not by this push.
147
+ const listenCallsAfterPush = foreignListenCalls
148
+ assert.equal(listenCallsAfterPush, 1)
149
+
150
+ history.back()
151
+ await waitUntil(() => foreignListenCalls === listenCallsAfterPush + 1)
152
+ assert.equal(foreignListenCalls, listenCallsAfterPush + 1)
153
+ })
154
+
155
+ it('ignores a single-spa popstate even when its state resembles the live guard', () => {
156
+ const { win, adapter } = setUp('https://example.test/list')
157
+ adapter.enabled = true
158
+ let closeCalls = 0
159
+ const unregister = adapter.register(() => {
160
+ closeCalls += 1
161
+ })
162
+ const guardBefore = __inspectOverlayBackForTests__(win)?.guard
163
+ let lateCalls = 0
164
+ win.addEventListener('popstate', () => {
165
+ lateCalls += 1
166
+ })
167
+
168
+ const event = new win.PopStateEvent('popstate') as PopStateEvent & { singleSpa?: boolean }
169
+ event.singleSpa = true
170
+ win.dispatchEvent(event)
171
+
172
+ assert.equal(closeCalls, 0)
173
+ assert.equal(lateCalls, 1)
174
+ assert.equal(__inspectOverlayBackForTests__(win)?.guard, guardBefore)
175
+ unregister()
176
+ })
177
+
178
+ it('does not consume or close anything while pagehide has suspended the adapter', () => {
179
+ const { win, adapter } = setUp('https://example.test/list')
180
+ adapter.enabled = true
181
+ let closeCalls = 0
182
+ const unregister = adapter.register(() => {
183
+ closeCalls += 1
184
+ })
185
+ const guardBefore = __inspectOverlayBackForTests__(win)?.guard
186
+ let lateCalls = 0
187
+ win.addEventListener('popstate', () => {
188
+ lateCalls += 1
189
+ })
190
+
191
+ win.dispatchEvent(new win.Event('pagehide'))
192
+ win.dispatchEvent(new win.PopStateEvent('popstate'))
193
+
194
+ assert.equal(closeCalls, 0)
195
+ assert.equal(lateCalls, 1)
196
+ assert.equal(__inspectOverlayBackForTests__(win)?.guard, guardBefore)
197
+ unregister()
198
+ })
199
+
200
+ it('reconciles the exact marker identity after a bfcache restore', () => {
201
+ const exact = setUp('https://example.test/list')
202
+ exact.adapter.enabled = true
203
+ exact.adapter.register(() => {})
204
+ const exactInternal = __inspectOverlayBackForTests__(exact.win)!
205
+ const exactGuard = exactInternal.guard
206
+ exact.win.dispatchEvent(new exact.win.Event('pagehide'))
207
+ dispatchPersistedPageShow(exact.win)
208
+ assert.equal(exactInternal.guard, exactGuard)
209
+ assert.equal(exactInternal.suspended, false)
210
+
211
+ const mismatch = setUp('https://example.test/list')
212
+ mismatch.adapter.enabled = true
213
+ mismatch.adapter.register(() => {})
214
+ const mismatchInternal = __inspectOverlayBackForTests__(mismatch.win)!
215
+ const marker = (mismatch.win.history.state as Record<string, unknown>).__asmaOverlayBack as Record<
216
+ string,
217
+ unknown
218
+ >
219
+ mismatch.win.history.replaceState(
220
+ { ...mismatch.win.history.state, __asmaOverlayBack: { ...marker, v: 2 } },
221
+ '',
222
+ mismatch.win.location.href,
223
+ )
224
+ mismatchInternal.pendingNav = { kind: 'PUSH', to: '/stale', state: undefined }
225
+ mismatch.win.dispatchEvent(new mismatch.win.Event('pagehide'))
226
+ dispatchPersistedPageShow(mismatch.win)
227
+
228
+ assert.equal(mismatchInternal.guard, null)
229
+ assert.equal(mismatchInternal.pendingNav, null)
230
+ assert.equal(mismatchInternal.suspended, false)
231
+ })
232
+
233
+ it('BACK-6: Forward bounces off a retired guard marker without reopening an overlay', async () => {
234
+ const { win, adapter } = setUp('https://example.test/list')
235
+ adapter.enabled = true
236
+ const unregister = adapter.register(() => {})
237
+ unregister()
238
+ const internal = __inspectOverlayBackForTests__(win)!
239
+ await waitUntil(() => internal.guard === null)
240
+
241
+ let lateCalls = 0
242
+ win.addEventListener('popstate', () => {
243
+ lateCalls += 1
244
+ })
245
+ win.history.forward()
246
+ await waitUntil(() => internal.retiredBouncePending)
247
+ await waitUntil(() => !internal.retiredBouncePending)
248
+
249
+ assert.equal(lateCalls, 0)
250
+ assert.equal((win.history.state as Record<string, unknown>).__asmaOverlayBack, undefined)
251
+ })
252
+
253
+ it('does not suppress markers whose version, session or marker id differs from the retired guard', async () => {
254
+ for (const field of ['v', 's', 'm'] as const) {
255
+ const { win, adapter } = setUp('https://example.test/list')
256
+ adapter.enabled = true
257
+ const unregister = adapter.register(() => {})
258
+ unregister()
259
+ const internal = __inspectOverlayBackForTests__(win)!
260
+ await waitUntil(() => internal.guard === null)
261
+ const retired = internal.retiredMarker!
262
+ const forged = { ...retired, [field]: field === 'v' ? 2 : `forged-${field}` }
263
+ win.history.pushState({ ...win.history.state, __asmaOverlayBack: forged }, '', win.location.href)
264
+ let lateCalls = 0
265
+ win.addEventListener('popstate', () => {
266
+ lateCalls += 1
267
+ })
268
+
269
+ win.dispatchEvent(new win.PopStateEvent('popstate'))
270
+
271
+ assert.equal(lateCalls, 1)
272
+ assert.equal(internal.retiredBouncePending, false)
273
+ }
274
+ })
275
+
276
+ it('does not suppress a forged marker when there is no matching retired guard', () => {
277
+ const { win } = setUp('https://example.test/list')
278
+ win.history.pushState(
279
+ { ...win.history.state, __asmaOverlayBack: { v: 1, s: 'forged-session', m: 'forged-marker' } },
280
+ '',
281
+ win.location.href,
282
+ )
283
+ let lateCalls = 0
284
+ win.addEventListener('popstate', () => {
285
+ lateCalls += 1
286
+ })
287
+
288
+ win.dispatchEvent(new win.PopStateEvent('popstate'))
289
+
290
+ assert.equal(lateCalls, 1)
291
+ assert.deepEqual((win.history.state as Record<string, unknown>).__asmaOverlayBack, {
292
+ v: 1,
293
+ s: 'forged-session',
294
+ m: 'forged-marker',
295
+ })
296
+ })
297
+
298
+ it('disabling the feature drains an armed guard without closing the overlay', async () => {
299
+ const { win, adapter } = setUp('https://example.test/list')
300
+ adapter.enabled = true
301
+ let closeCalls = 0
302
+ const unregister = adapter.register(() => {
303
+ closeCalls += 1
304
+ })
305
+ assert.ok(__inspectOverlayBackForTests__(win)?.guard)
306
+
307
+ adapter.enabled = false
308
+ await waitUntil(() => __inspectOverlayBackForTests__(win)?.guard === null)
309
+
310
+ assert.equal(closeCalls, 0)
311
+ assert.equal((win.history.state as Record<string, unknown>).__asmaOverlayBack, undefined)
312
+ unregister()
313
+ })
314
+
315
+ it('drains instead of calling a stale closer when the last overlay unregisters during rearm', async () => {
316
+ const { win, adapter } = setUp('https://example.test/list')
317
+ adapter.enabled = true
318
+ let closeCalls = 0
319
+ const unregister = adapter.register(() => {
320
+ closeCalls += 1
321
+ })
322
+ const internal = __inspectOverlayBackForTests__(win)!
323
+ internal.phase = 'rearming'
324
+ unregister()
325
+
326
+ win.dispatchEvent(new win.PopStateEvent('popstate'))
327
+ await waitUntil(() => internal.guard === null)
328
+
329
+ assert.equal(closeCalls, 0)
330
+ assert.equal(internal.openCount, 0)
331
+ assert.equal((win.history.state as Record<string, unknown>).__asmaOverlayBack, undefined)
332
+ })
333
+
334
+ it('cancels a pending rearm when its replacement overlay unregisters during drain', () => {
335
+ const { win, adapter } = setUp('https://example.test/list')
336
+ adapter.enabled = true
337
+ const unregisterOriginal = adapter.register(() => {})
338
+ const internal = __inspectOverlayBackForTests__(win)!
339
+ unregisterOriginal()
340
+ assert.equal(internal.phase, 'draining')
341
+
342
+ const unregisterReplacement = adapter.register(() => {})
343
+ assert.ok(internal.pendingRearmRequestClose)
344
+ unregisterReplacement()
345
+
346
+ assert.equal(internal.openCount, 0)
347
+ assert.equal(internal.pendingRearmRequestClose, null)
348
+ })
349
+
350
+ it('a refused close fails open for push and cross-path replace instead of blocking forever', async () => {
351
+ for (const kind of ['push', 'replace'] as const) {
352
+ const { win, adapter, history } = setUp('https://example.test/list')
353
+ adapter.enabled = true
354
+ let closeCalls = 0
355
+ const unregister = adapter.register(() => {
356
+ closeCalls += 1
357
+ return false
358
+ })
359
+
360
+ history[kind]('/checkout')
361
+ await waitUntil(() => history.location.pathname === '/checkout')
362
+
363
+ assert.equal(closeCalls, 1)
364
+ assert.equal(__inspectOverlayBackForTests__(win)?.pendingNav, null)
365
+ assert.equal(__inspectOverlayBackForTests__(win)?.guard, null)
366
+ assert.equal((win.history.state as Record<string, unknown>).__asmaOverlayBack, undefined)
367
+ unregister()
368
+ }
369
+ })
370
+
371
+ it('continues a pending route through each registry layer before draining', async () => {
372
+ const { adapter, history } = setUp('https://example.test/list')
373
+ adapter.enabled = true
374
+ let layers = 2
375
+ let closeCalls = 0
376
+ const unregister: () => void = adapter.register(() => {
377
+ closeCalls += 1
378
+ layers -= 1
379
+ if (layers === 0) unregister()
380
+ })
381
+
382
+ history.push('/checkout')
383
+ assert.equal(adapter.pendingNavigation, true)
384
+ assert.equal(history.location.pathname, '/list')
385
+ assert.equal(closeCalls, 1)
386
+
387
+ adapter.continuePendingNavigation()
388
+ await waitUntil(() => history.location.pathname === '/checkout')
389
+
390
+ assert.equal(closeCalls, 2)
391
+ assert.equal(adapter.pendingNavigation, false)
392
+ })
393
+
394
+ it('TEST-003: push while armed defers until the overlay closes, landing on C; a blocker on B prompts once', async () => {
395
+ const { win: _win, adapter, history } = setUp('https://example.test/home')
396
+ history.push('/list')
397
+ adapter.enabled = true
398
+
399
+ let blockCalls = 0
400
+ const unblock = history.block((tx) => {
401
+ blockCalls += 1
402
+ unblock()
403
+ tx.retry()
404
+ })
405
+
406
+ let closeCalls = 0
407
+ const unregister: () => void = adapter.register(() => {
408
+ closeCalls += 1
409
+ unregister()
410
+ })
411
+
412
+ history.push('/checkout')
413
+
414
+ await waitUntil(() => history.location.pathname === '/checkout')
415
+ assert.equal(closeCalls, 1)
416
+ assert.equal(blockCalls, 1)
417
+
418
+ history.back()
419
+ await waitUntil(() => history.location.pathname === '/list')
420
+ history.forward()
421
+ await waitUntil(() => history.location.pathname === '/checkout')
422
+ })
423
+
424
+ it('TEST-004: a same-path replace keeps the marker without draining; a cross-path replace defers', async () => {
425
+ const { win, adapter, history } = setUp('https://example.test/home')
426
+ history.push('/list')
427
+ adapter.enabled = true
428
+
429
+ let closeCalls = 0
430
+ const unregister: () => void = adapter.register(() => {
431
+ closeCalls += 1
432
+ unregister()
433
+ })
434
+
435
+ const markerBefore = (win.history.state as Record<string, unknown>).__asmaOverlayBack
436
+ assert.ok(markerBefore)
437
+
438
+ history.replace({ pathname: '/list', search: '?page=2' })
439
+
440
+ const stateAfterSamePath = win.history.state as Record<string, unknown>
441
+ assert.deepEqual(stateAfterSamePath.__asmaOverlayBack, markerBefore)
442
+ assert.equal(win.location.search, '?page=2')
443
+ assert.equal(closeCalls, 0)
444
+ const internalMid = __inspectOverlayBackForTests__(win)
445
+ assert.ok(internalMid?.guard)
446
+ assert.equal(internalMid?.phase, null)
447
+
448
+ history.replace('?page=3')
449
+ assert.equal(win.location.search, '?page=3')
450
+ assert.equal(closeCalls, 0)
451
+ assert.deepEqual((win.history.state as Record<string, unknown>).__asmaOverlayBack, markerBefore)
452
+
453
+ history.replace('/checkout')
454
+ await waitUntil(() => history.location.pathname === '/checkout')
455
+ assert.equal(closeCalls, 1)
456
+ })
457
+
458
+ it('TEST-005: a raw replaceState at G carries over onto B when the guard drains', async () => {
459
+ const { win, adapter, history } = setUp('https://example.test/home')
460
+ history.push('/list?x=1')
461
+ adapter.enabled = true
462
+
463
+ const unregister = adapter.register(() => {})
464
+
465
+ const rawBefore = win.history.state as Record<string, unknown>
466
+ win.history.replaceState(
467
+ { ...rawBefore, usr: { ...(rawBefore.usr as Record<string, unknown> | undefined), extra: 'raw' } },
468
+ '',
469
+ 'https://example.test/list?x=2',
470
+ )
471
+
472
+ let lateCalls = 0
473
+ win.addEventListener('popstate', () => {
474
+ lateCalls += 1
475
+ })
476
+ unregister()
477
+ await waitUntil(() => __inspectOverlayBackForTests__(win)?.guard === null)
478
+
479
+ assert.equal(lateCalls, 0)
480
+ assert.equal(win.location.search, '?x=2')
481
+ assert.equal(history.location.pathname, '/list')
482
+ const finalState = win.history.state as Record<string, unknown>
483
+ assert.equal((finalState.usr as Record<string, unknown>).extra, 'raw')
484
+ })
485
+
486
+ it('TEST-006: a second install adds no listener; a marker present at init is stripped', () => {
487
+ const win = createTestWindow('https://example.test/reload')
488
+ win.history.replaceState(
489
+ {
490
+ usr: { a: 1 },
491
+ key: 'k9',
492
+ idx: 4,
493
+ __asmaOverlayBack: { v: 1, s: 'old-session', m: 'old-marker' },
494
+ },
495
+ '',
496
+ win.location.href,
497
+ )
498
+
499
+ const nativeAddEventListener = win.addEventListener.bind(win)
500
+ let popstateListenerCount = 0
501
+ win.addEventListener = ((type: string, listener: EventListenerOrEventListenerObject, options?: unknown) => {
502
+ if (type === 'popstate') {
503
+ popstateListenerCount += 1
504
+ }
505
+ return nativeAddEventListener(type, listener, options as boolean | AddEventListenerOptions | undefined)
506
+ }) as typeof win.addEventListener
507
+
508
+ const adapter1 = installOverlayBackPopstateListener(win)
509
+ const adapter2 = installOverlayBackPopstateListener(win)
510
+
511
+ assert.equal(popstateListenerCount, 1)
512
+ assert.equal(adapter1, adapter2)
513
+
514
+ const state = win.history.state as Record<string, unknown>
515
+ assert.equal(state.__asmaOverlayBack, undefined)
516
+ assert.deepEqual(state.usr, { a: 1 })
517
+ assert.equal(state.key, 'k9')
518
+ assert.equal(state.idx, 4)
519
+ assert.equal(win.location.href, 'https://example.test/reload')
520
+ })
521
+
522
+ it('preserves the current scroll position while draining the guard entry', async () => {
523
+ const { win, adapter } = setUp('https://example.test/list')
524
+ let scrollX = 24
525
+ let scrollY = 800
526
+ Object.defineProperties(win, {
527
+ scrollX: { configurable: true, get: () => scrollX },
528
+ scrollY: { configurable: true, get: () => scrollY },
529
+ })
530
+ win.scrollTo = ((x: number, y: number) => {
531
+ scrollX = x
532
+ scrollY = y
533
+ }) as typeof win.scrollTo
534
+
535
+ adapter.enabled = true
536
+ const unregister = adapter.register(() => {})
537
+ const nativeGo = win.history.go.bind(win.history)
538
+ win.history.go = ((delta?: number) => {
539
+ if (delta === -1) {
540
+ scrollX = 24
541
+ scrollY = 0
542
+ }
543
+ nativeGo(delta)
544
+ }) as typeof win.history.go
545
+
546
+ unregister()
547
+ await waitUntil(() => __inspectOverlayBackForTests__(win)?.guard === null)
548
+
549
+ assert.deepEqual([scrollX, scrollY], [24, 800])
550
+ })
551
+
552
+ it('fails open when a fire-and-forget closer leaves the overlay mounted', async () => {
553
+ const { adapter, history } = setUp('https://example.test/list')
554
+ adapter.enabled = true
555
+ adapter.register(() => {})
556
+
557
+ history.push('/checkout')
558
+ await waitUntil(() => history.location.pathname === '/checkout', 100)
559
+
560
+ assert.equal(adapter.pendingNavigation, false)
561
+ })
562
+
563
+ it('restores the previous closer when the top registration unregisters', async () => {
564
+ const { adapter, history } = setUp('https://example.test/list')
565
+ adapter.enabled = true
566
+ let lowerCalls = 0
567
+ adapter.register(() => {
568
+ lowerCalls += 1
569
+ return false
570
+ })
571
+ const unregisterTop = adapter.register(() => {
572
+ throw new Error('stale top closer')
573
+ })
574
+ unregisterTop()
575
+
576
+ history.push('/checkout')
577
+ await waitUntil(() => history.location.pathname === '/checkout')
578
+
579
+ assert.equal(lowerCalls, 1)
580
+ })
581
+
582
+ it('fails open when a closer throws or returns a non-contract value', async () => {
583
+ for (const requestClose of [() => null, () => true, () => {
584
+ throw new Error('close failed')
585
+ }]) {
586
+ const { adapter, history } = setUp('https://example.test/list')
587
+ adapter.enabled = true
588
+ adapter.register(requestClose as () => void)
589
+
590
+ history.push('/checkout')
591
+ await waitUntil(() => history.location.pathname === '/checkout', 100)
592
+ assert.equal(adapter.pendingNavigation, false)
593
+ }
594
+ })
595
+
596
+ it('re-arms an overlay registered while the previous guard drains', async () => {
597
+ const { win, adapter } = setUp('https://example.test/list')
598
+ adapter.enabled = true
599
+ const unregister = adapter.register(() => {})
600
+ unregister()
601
+ adapter.register(() => {})
602
+
603
+ await waitUntil(() => __inspectOverlayBackForTests__(win)?.phase === null)
604
+
605
+ assert.ok(__inspectOverlayBackForTests__(win)?.guard)
606
+ assert.ok((win.history.state as Record<string, unknown>).__asmaOverlayBack)
607
+ })
608
+
609
+ it('keeps the replaced key aligned for a retired-marker Forward bounce', async () => {
610
+ const { win, adapter, history } = setUp('https://example.test/list')
611
+ adapter.enabled = true
612
+ const unregister = adapter.register(() => {})
613
+ history.replace('/list?view=compact')
614
+ unregister()
615
+ const internal = __inspectOverlayBackForTests__(win)!
616
+ await waitUntil(() => internal.guard === null)
617
+
618
+ let leakedPopstates = 0
619
+ win.addEventListener('popstate', () => {
620
+ leakedPopstates += 1
621
+ })
622
+ win.history.forward()
623
+ await waitUntil(() => internal.retiredBouncePending)
624
+ await waitUntil(() => !internal.retiredBouncePending)
625
+
626
+ assert.equal(leakedPopstates, 0)
627
+ })
628
+
629
+ it('re-arms an open overlay after the feature is disabled and enabled again', async () => {
630
+ const { win, adapter } = setUp('https://example.test/list')
631
+ adapter.enabled = true
632
+ adapter.register(() => {})
633
+
634
+ adapter.enabled = false
635
+ await waitUntil(() => __inspectOverlayBackForTests__(win)?.guard === null)
636
+ adapter.enabled = true
637
+ await waitUntil(() => __inspectOverlayBackForTests__(win)?.guard !== null)
638
+
639
+ assert.ok((win.history.state as Record<string, unknown>).__asmaOverlayBack)
640
+ })
641
+
642
+ it('defers a push that arrives while an owned Back is rearming', async () => {
643
+ const { win, adapter, history } = setUp('https://example.test/list')
644
+ adapter.enabled = true
645
+ let closeCalls = 0
646
+ const unregister: () => void = adapter.register(() => {
647
+ closeCalls += 1
648
+ unregister()
649
+ })
650
+ const internal = __inspectOverlayBackForTests__(win)!
651
+ internal.phase = 'rearming'
652
+
653
+ history.push('/checkout')
654
+ assert.equal(history.location.pathname, '/list')
655
+ win.dispatchEvent(new win.PopStateEvent('popstate'))
656
+ await waitUntil(() => history.location.pathname === '/checkout')
657
+
658
+ assert.equal(closeCalls, 1)
659
+ assert.equal(adapter.pendingNavigation, false)
660
+ })
661
+ })
662
+
663
+ describe('overlayBack arming gate', () => {
664
+ it('arms an already-registered overlay when the host enables the feature', () => {
665
+ const { win, adapter } = setUp('https://example.test/list')
666
+ const unregister = adapter.register(() => {})
667
+ assert.equal(__inspectOverlayBackForTests__(win)?.guard, null)
668
+
669
+ adapter.enabled = true
670
+
671
+ assert.ok(__inspectOverlayBackForTests__(win)?.guard)
672
+ assert.ok((win.history.state as Record<string, unknown>).__asmaOverlayBack)
673
+ unregister()
674
+ })
675
+
676
+ it('gate-pass: a trusted gesture newer than the last popstate arms the guard', () => {
677
+ const { win, adapter } = setUpAdapter('https://example.test/list')
678
+ simulateTrustedGesture(win)
679
+ adapter.enabled = true
680
+
681
+ const unregister = adapter.register(() => {})
682
+
683
+ const state = win.history.state as Record<string, unknown>
684
+ assert.ok(state.__asmaOverlayBack)
685
+ assert.ok(__inspectOverlayBackForTests__(win)?.guard)
686
+
687
+ unregister()
688
+ })
689
+
690
+ it('gate-fail: no trusted gesture recorded yet keeps the overlay registry-only', () => {
691
+ const { win, adapter } = setUpAdapter('https://example.test/list')
692
+ adapter.enabled = true
693
+
694
+ const stateBefore = win.history.state
695
+ const lengthBefore = win.history.length
696
+
697
+ const unregister = adapter.register(() => {})
698
+
699
+ assert.equal(win.history.state, stateBefore)
700
+ assert.equal(win.history.length, lengthBefore)
701
+ assert.equal(__inspectOverlayBackForTests__(win)?.guard, null)
702
+
703
+ unregister()
704
+ })
705
+
706
+ it('gate-fail: a popstate after the last gesture keeps the overlay registry-only', async () => {
707
+ const { win, adapter, history } = setUpAdapter('https://example.test/home')
708
+ history.push('/list')
709
+ simulateTrustedGesture(win)
710
+
711
+ // A navigation lands after the gesture, so the gesture is no longer the newest signal.
712
+ history.back()
713
+ await waitUntil(() => history.location.pathname === '/home')
714
+
715
+ adapter.enabled = true
716
+ const lengthBefore = win.history.length
717
+ const unregister = adapter.register(() => {})
718
+
719
+ assert.equal(__inspectOverlayBackForTests__(win)?.guard, null)
720
+ assert.equal(win.history.length, lengthBefore)
721
+
722
+ unregister()
723
+ })
724
+
725
+ it('gate-fail: navigator.userActivation.isActive === false overrides a fresh gesture', () => {
726
+ const { win, adapter } = setUpAdapter('https://example.test/list')
727
+ simulateTrustedGesture(win)
728
+ Object.defineProperty(win.navigator, 'userActivation', {
729
+ value: { isActive: false },
730
+ configurable: true,
731
+ })
732
+ adapter.enabled = true
733
+
734
+ const lengthBefore = win.history.length
735
+ const unregister = adapter.register(() => {})
736
+
737
+ assert.equal(__inspectOverlayBackForTests__(win)?.guard, null)
738
+ assert.equal(win.history.length, lengthBefore)
739
+
740
+ unregister()
741
+ })
742
+ })