-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontent-script.js
More file actions
1953 lines (1696 loc) · 68.3 KB
/
Copy pathcontent-script.js
File metadata and controls
1953 lines (1696 loc) · 68.3 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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// console.log(`RUNNING content SCRIPT!`)
var httpx = 'HTTP'
var peer = Math.random().toString(36).substr(2)
var version = null
var parents = null
var content_type = null
var merge_type = null
var subscribe = true
var encoding_dt = true
var edit_source = false
var textarea = null
var online = null
var show_editor = null
let deleteIcon = null
var headers = {}
var versions = []
var raw_messages = []
var get_failed = ''
var doc = null
var default_version_count = 1
var on_show_diff = () => { }
// Firefox never gives a content script's sandbox its own ReadableStream, so
// the name resolves up the prototype chain to the page's, and that constructor
// runs in the page's realm — where our underlying source object is off limits.
// braid-http's multiplexer dies building its fake response, with "Permission
// denied to access property autoAllocateChunkSize" (bugzilla 1757836, open
// since Firefox 99). Both primings the bug suggests are MV2-only.
//
// So hand the sandbox a ReadableStream of its own, and the lookup stops here
// instead of reaching the page. A TransformStream built with no arguments
// gives the page's realm nothing to read, and its readable end is a real
// stream that our sandbox-local Response accepts. Only the sliver of the API
// braid-http asks for is covered: a start callback fed enqueue/close/error.
// Chrome has no sandbox, no xray, and takes none of this.
//
// Two things that look like they should work, and don't: priming the sandbox
// the way bug 1757836 suggests (MV2 only — MV3 dropped the sandbox's own
// fetch), and borrowing the constructor off `new Response('').body`, whose
// stream turns out to be the page's too.
try {
if ('wrappedJSObject' in ReadableStream) {
globalThis.ReadableStream = function (source) {
// The page's own TransformStream, reached without xray vision. An xrayed
// one hands back xrayed promises, and reading `.then` off one of those
// from in here is denied (bugzilla 1750290) — which is what awaiting a
// read from this stream ends up doing.
var TS = window.wrappedJSObject?.TransformStream ?? TransformStream
var ts = new TS()
var writer = ts.writable.getWriter()
source?.start?.({
// The chunk has to belong to the page before it is allowed through
// the page's stream: written as it is, a sandbox Uint8Array reads back
// out as undefined, while a cloned one arrives whole and still
// iterable, which is what braid-http walks it as.
enqueue: chunk => {
var theirs = (chunk !== null && typeof chunk === 'object')
? cloneInto(chunk, window) : chunk
writer.write(theirs).catch(() => {})
},
close: () => { writer.close().catch(() => {}) },
error: e => { writer.abort(e).catch(() => {}) },
})
return ts.readable
}
}
} catch (e) {
console.log('ReadableStream shim failed: ' + (e?.stack ?? e))
}
// Bring a character offset into view, if it is not already. The browser is
// asked where that character lands by laying the same text out in a hidden
// copy of the box, which is the only way to account for soft wrapping.
function reveal_offset(el, at) {
let content = el.value ?? el.textContent
if (at == null || at > content.length) return
let cs = getComputedStyle(el)
let mirror = document.createElement('div')
mirror.style.cssText = 'position:absolute;visibility:hidden;top:0;left:-9999px;'
+ 'white-space:pre-wrap;overflow-wrap:break-word'
for (let k of ['fontFamily', 'fontSize', 'fontWeight', 'lineHeight', 'letterSpacing',
'padding', 'border', 'boxSizing', 'width', 'textIndent'])
mirror.style[k] = cs[k]
mirror.textContent = content.slice(0, at)
let marker = document.createElement('span')
marker.textContent = '\u200b'
mirror.appendChild(marker)
document.body.appendChild(mirror)
let y = marker.offsetTop
let line = parseFloat(cs.lineHeight) || 16
mirror.remove()
// Only move if the change is somewhere the reader cannot see. Scrolling a
// document that already shows the edit would be the view chasing itself.
if (y >= el.scrollTop && y + line <= el.scrollTop + el.clientHeight) return
el.scrollTop = Math.max(0, y - el.clientHeight / 2 + line / 2)
}
// The author's colour, softened into something text stays readable on. The
// panel sends the colours the history graph is using, in whatever form it
// draws them; mixing towards transparent works for any of them. An author the
// graph has never drawn falls back to a neutral highlight.
function author_tint(colors, agent) {
let c = colors?.[agent]
return c ? `color-mix(in oklab, ${c} 22%, transparent)`
: 'rgba(140, 140, 140, 0.25)'
}
// Show what a span of history did, in place of the editor, or put the editor
// back when there is nothing to show. Edits are highlighted in their author's
// colour, the same one that author has in the history graph, so the text reads
// as who wrote what, and removed text is struck through and faded.
//
// Leaving the deletions out gives the text exactly as it stood at the far end
// of the span, so it can be read and copied like ordinary text and still says
// who wrote each part. `at` is a position worth looking at, brought into view
// if it is off screen.
function show_diff_view(diff_d, diff, colors, show_deletions, at) {
let showing = window.getComputedStyle(diff_d).display !== 'none'
let from = showing ? diff_d : textarea
let scroll = { vertical: from.scrollTop, horizontal: from.scrollLeft }
if (!diff) {
diff_d.style.display = 'none'
textarea.style.display = 'block'
textarea.scrollTop = scroll.vertical
textarea.scrollLeft = scroll.horizontal
return
}
diff_d.style.display = 'block'
textarea.style.display = 'none'
diff_d.innerHTML = ''
for (let [what, text, agent] of diff) {
if (!text || (what === -1 && !show_deletions)) continue
let span = document.createElement('span')
if (what) {
span.style.backgroundColor = author_tint(colors, agent)
if (what === -1) {
span.style.textDecoration = 'line-through'
span.style.opacity = 0.55
}
}
span.textContent = text
diff_d.appendChild(span)
}
diff_d.scrollTop = scroll.vertical
diff_d.scrollLeft = scroll.horizontal
reveal_offset(diff_d, at)
}
var get_parents = () => null
var current_sync = null
// The navigation's defaults, for rerequests that don't specify these
var nav_content_type = null
var nav_merge_type = null
// The url we have already set ourselves up for, so the second of the two
// 'loaded' messages does not tear that down and build it again
var last_loaded_url = null
var is_chrome_showing_media = false
window.errorify = (msg) => {
console.log(`errorify: ${msg?.stack ?? msg}`)
if (textarea) {
textarea.style.background = 'pink'
textarea.style.color = '#800'
textarea.disabled = true
}
throw new Error(msg)
}
function send_dev_message(m) {
try {
chrome.runtime.sendMessage(m)
} catch (e) {
console.log(`send_dev_message could not send action=${m?.action}`
+ ` keys=[${Object.keys(m ?? {})}]: ${e}`)
window.errorify(e)
}
}
function on_bytes_received(s) {
var text = decode_binary_as_markers(s)
if (text) record_raw(text)
}
// dt-encoded blobs put binary on the wire now. Show each blob as one
// <binary> marker by following the framing: an update whose body starts
// with dt's DMNDTYPS magic, sized by its Content-Length header
var dt_blob_left = 0
function decode_binary_as_markers(bytes) {
var td = new TextDecoder()
var out = ''
var i = 0
// A blob can span network chunks. Its full size was reported when it
// began, so swallow continuation bytes silently
if (dt_blob_left > 0) {
var n = Math.min(dt_blob_left, bytes.length)
dt_blob_left -= n
i = n
}
while (i < bytes.length) {
var body_start = find_crlfcrlf(bytes, i)
if (body_start < 0) {
out += unframed_binary_as_markers(bytes.subarray(i))
break
}
var headers = td.decode(bytes.subarray(i, body_start))
var len = parseInt(headers.match(/^content-length:\s*(\d+)\s*$/im)?.[1])
if (len >= 8 && starts_with_ascii(bytes, body_start, 'DMNDTYPS')) {
out += headers + `<binary: ${len} bytes>`
var have = Math.min(len, bytes.length - body_start)
dt_blob_left = len - have
i = body_start + have
} else {
// Not a dt blob; pass the segment through, sweeping it for any
// binary the framing didn't catch
out += unframed_binary_as_markers(bytes.subarray(i, body_start))
i = body_start
}
}
return out
}
// Returns the index just past the next \r\n\r\n, or -1
function find_crlfcrlf(b, from) {
for (var i = from; i + 3 < b.length; i++)
if (b[i] == 13 && b[i+1] == 10 && b[i+2] == 13 && b[i+3] == 10)
return i + 4
return -1
}
function starts_with_ascii(b, at, s) {
if (at + s.length > b.length) return false
for (var i = 0; i < s.length; i++)
if (b[at + i] != s.charCodeAt(i)) return false
return true
}
// Wire text is \t \r \n, printable ascii, or a valid UTF-8 sequence.
// Everything else (dt varints, stray high bytes) counts as binary.
// Returns the sequence's byte length, or 0 for binary
function text_seq_len(b, i) {
var b0 = b[i]
if (b0 == 9 || b0 == 10 || b0 == 13 || (b0 >= 32 && b0 < 127)) return 1
var n = b0 >= 0xf0 ? 4 : b0 >= 0xe0 ? 3 : b0 >= 0xc2 ? 2 : 0
if (!n || i + n > b.length) return 0
for (var j = 1; j < n; j++)
if ((b[i + j] & 0xc0) != 0x80) return 0
return n
}
// Fallback for binary that isn't dt-framed: mark each binary span,
// growing it while more binary bytes appear nearby
function unframed_binary_as_markers(bytes) {
var td = new TextDecoder()
var out = ''
var text_start = 0
var i = 0
while (i < bytes.length) {
var n = text_seq_len(bytes, i)
if (n) { i += n; continue }
var start = i, end = i + 1
for (var j = end; j < bytes.length && j < end + 16; ) {
var m = text_seq_len(bytes, j)
if (m) j += m
else end = ++j
}
out += td.decode(bytes.subarray(text_start, start))
out += `<binary: ${end - start} bytes>`
text_start = i = end
}
return out + td.decode(bytes.subarray(text_start))
}
// An outgoing body is all one thing: text, or a single blob
function body_as_text_or_marker(bytes) {
for (var i = 0; i < bytes.length; ) {
var n = text_seq_len(bytes, i)
if (!n) return `<binary: ${bytes.length} bytes>`
i += n
}
return new TextDecoder().decode(bytes)
}
function record_raw(s) {
raw_messages.push(s)
send_dev_message({ action: "braid_in", data: s })
}
// Mirror a response's headers to the devtools, and reconstruct its status
// line and headers for the raw view, since braid_fetch doesn't deliver
// those as bytes
function record_response(response) {
headers = {}
// forEach rather than for-of over .entries(): Firefox content scripts don't
// expose Symbol.iterator on the iterator Headers hands back, so for-of dies
// with "not iterable" there while working fine in Chrome.
response.headers.forEach((value, name) => headers[name.toLowerCase()] = value)
send_dev_message({ action: "new_headers", headers })
var status_text = {200: 'OK', 209: 'Multiresponse'}[response.status] ?? ''
record_raw(`HTTP/1.1 ${response.status} ${status_text}\r\n`
+ Object.entries(headers).map(([k, v]) => `${k}: ${v}\r\n`).join('')
+ '\r\n')
}
function on_bytes_going_out(url, params) {
if (!on_bytes_going_out.chain) on_bytes_going_out.chain = Promise.resolve()
on_bytes_going_out.chain = on_bytes_going_out.chain.then(async () => {
let data = await constructHTTPRequest(url, params)
// console.log(`on_bytes_going_out[${data}]`)
raw_messages.push(data)
send_dev_message({ action: "braid_out", data })
})
}
window.subscription_online = false
var on_subscription_status = null // set by merge-type handlers that need it
function set_subscription_online(bool) {
if (window.subscription_online === bool) return
window.subscription_online = bool
console.log(bool ? 'Connected!' : 'Disconnected.')
if (online) online.style.color = bool ? 'lime' : 'orange';
}
// This replaces the page with our "live-update" view of TEXT or JSON
chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) => {
// console.log(`getting message with cmd: ${request.cmd}`)
let reload = () => {
console.log('reloading!')
disconnect()
location.reload()
}
if (request.cmd == 'init') {
send_dev_message({ action: "init", headers, versions, raw_messages, get_failed })
} else if (request.cmd == 'panel_opened') {
if (deleteIcon) deleteIcon.style.display = 'flex'
} else if (request.cmd == 'panel_closed') {
if (deleteIcon) deleteIcon.style.display = 'none'
} else if (request.cmd == "show_diff") {
on_show_diff(request.from_version, request.to_version, request.colors,
request.show_deletions, request.at)
} else if (request.cmd == "edit_source") {
edit_source = true
show_editor()
} else if (request.cmd == "rerequest") {
// Going back to Chrome's native rendering needs a real page reload
if (request.subscribe === false && !request.version && !request.parents)
reload()
else
connect(request)
} else if (request.cmd == 'loaded') {
// Our 'ready' and the background's tabs.onUpdated both ask for this, and
// either can arrive first. Once one has come bearing headers the page is
// set up, and a second would only take it apart and build it again. One
// that arrives without headers settles nothing, so it claims nothing.
if (request.headers && last_loaded_url === request.url) return
if (request.headers) last_loaded_url = request.url
// Standing down without headers is the right answer; throwing on the
// missing object is not, and that is what used to happen here.
if (!request.headers)
console.log(`braid: no response headers for this navigation`)
var res_headers = request.headers ?? {}
nav_content_type =
res_headers['repr-type']?.split(/[;,]/)[0] ||
res_headers['content-type']?.split(/[;,]/)[0] ||
request.request_headers?.accept?.split(/[;,]/)[0]
nav_merge_type = res_headers['merge-type']
headers = {}
for (let x of Object.entries(res_headers)) headers[x[0]] = x[1]
// Only take over pages whose response headers advertise Braid.
// Braidify always Varies on Subscribe; braid-text adds the rest.
// On normal websites, our extra GET can break logins (csrf rotation,
// single-use urls) and trip rate limiters into endless retries.
var braidly = /\bsubscribe\b/i.test(headers.vary ?? '')
|| headers['accept-subscribe'] != null
|| headers['current-version'] != null
|| headers['merge-type'] != null
// Older braid servers (like mail.braid.org) predate braidify's
// Vary headers, but advertise Subscribe in their CORS allow-list
|| /\bsubscribe\b/i.test(headers['access-control-allow-headers'] ?? '')
// A dev_message means devtools explicitly asked to connect this tab,
// which overrides the sniff
if (!braidly && !request.dev_message) return
// Everything past here reads and replaces document.body, and we may have
// been told about this page before the parser has made one — we ask for
// the headers the moment the content script runs, which is earlier than
// the tab reporting itself complete used to be.
if (!document.body) await new Promise(done => {
var o = new MutationObserver(() => {
if (document.body) { o.disconnect(); done() }
})
o.observe(document.documentElement, { childList: true })
})
is_chrome_showing_media =
// showing an image..
(document.body?.firstElementChild?.tagName === 'IMG' &&
document.body.firstElementChild.src === location.href) ||
// showing a video or audio..
(document.body?.firstElementChild?.tagName === 'VIDEO' &&
document.body.firstElementChild.firstElementChild?.src === location.href)
// if chrome is displaying the resource as an image, video or audio,
// show a delete icon
if (is_chrome_showing_media)
addDeleteIcon(request.panel_open)
connect(request.dev_message ?? {})
// if it is displaying the resource as non-html, or it is a 404,
// make it a drop target
if (!content_type?.includes('html') || headers[':status'] === 404)
setupDragAndDrop()
}
})
// A sync is one live connection to this page's resource, under one set of
// request params. Rerequesting stops the current sync and starts a new one;
// the old editor stays visible until the new sync's first update swaps it in.
function connect(params) {
disconnect()
current_sync = { aborter: new AbortController(), cleanups: [] }
version = params.version
parents = params.parents
content_type = params.content_type || nav_content_type
merge_type = params.merge_type || nav_merge_type
subscribe = !(params.subscribe === false)
encoding_dt = !(params.encoding_dt === false)
edit_source = params.edit_source
window.subscription_online = false
on_subscription_status = null
get_parents = () => null
on_show_diff = () => { }
// The old sync's history is replaced along with it. Its headers stay
// shown until the new response arrives, like the editor's content does
versions = []
raw_messages = []
dt_blob_left = 0
get_failed = ''
send_dev_message({ action: "init", versions, raw_messages, get_failed })
if (version || parents) handle_specific_version()
else if (subscribe) handle_subscribe()
}
function disconnect() {
if (!current_sync) return
current_sync.dead = true
current_sync.aborter.abort()
for (var f of current_sync.cleanups) try { f() } catch (e) { }
current_sync = null
}
async function handle_specific_version() {
var abort_controller = current_sync.aborter
window.stop()
// Canvas/CanvasText are CSS system colors that follow the OS
// light/dark theme (given color-scheme), so dark-mode users get
// light text on a dark editor instead of white-on-white
document.body.innerHTML = '<textarea disabled style="position: fixed; left: 0px; top: 0px; right: 0px; bottom: 0px; padding: 13px 8px; font-size: 13px; border: 0; box-sizing: border-box; color-scheme: light dark; background: Canvas; color: CanvasText;"></textarea>'
document.body.style.background = 'none'
textarea = document.body.firstChild
try {
response = await braid_fetch_wrapper(window.location.href, {
version: version ? JSON.parse(`[${version}]`) : null,
parents: parents ? JSON.parse(`[${parents}]`) : null,
peer,
headers: { Accept: content_type, ...(merge_type ? { ['Merge-Type']: merge_type } : {}) },
signal: abort_controller.signal,
retry: true
})
record_response(response)
textarea.textContent = await response.text()
} catch (e) {
if (abort_controller.signal.aborted) return
console.log('braid_fetch_wrapper failed: ' + e)
get_failed = '' + e
send_dev_message({ action: "get_failed", get_failed })
textarea.value = get_failed
textarea.style.border = '4px red solid'
textarea.style.background = '#fee'
textarea.style.color = '#800' // else dark mode puts white text on the pink
send_dev_message({ action: "get_failed", get_failed: '' + e })
}
}
async function handle_subscribe() {
var sync = current_sync
var abort_controller = sync.aborter
let uniquePrefix = '_' + Math.random().toString(36).slice(2)
let main_div = make_html(`<div
style="position: fixed; left: 0px; top: 0px; right: 0px; bottom: 0px; box-sizing: border-box; color-scheme: light dark; background: Canvas; color: CanvasText;"
>
<pre
class="${uniquePrefix}_diff_d"
style="display:none; position: absolute; top: 0px; left: 0px; right: 0px; bottom: 0px; padding: 13px 8px; font-size: 13px; font-family: monospace; overflow:scroll; margin:0px; white-space: pre-wrap; word-wrap: break-word; overflow-wrap: break-word;"
></pre>
<span
class="${uniquePrefix}_online"
style="position: absolute; top: 5px; right: 5px;"
>•</span>
<textarea
class="${uniquePrefix}_textarea"
style="width: 100%; height:100%; padding: 13px 8px; font-size: 13px; border: 0; box-sizing: border-box; background: transparent; color: inherit;"
readonly
disabled
></textarea>
</div>`)
let diff_d = main_div.querySelector(`.${uniquePrefix}_diff_d`)
online = main_div.querySelector(`.${uniquePrefix}_online`)
textarea = main_div.querySelector(`.${uniquePrefix}_textarea`)
// The panel asks what a span of history did whenever one is selected there.
// Replaying the updates answers it for any history that arrives in a
// straight line, which is all of them but dt's; dt replaces this below with
// something that asks the document itself.
on_show_diff = (from_version, to_version, colors, show_deletions, at) =>
show_diff_view(diff_d,
from_version && replay_diff(versions, from_version, to_version),
colors, show_deletions, at)
// show_editor() replaces the original page with our editor. We defer
// calling it until the first subscription update arrives, so that the
// original page stays visible rather than flashing blank while we wait.
show_editor = () => {
document.body.innerHTML = ''
document.body.style.background = 'none'
document.body.append(main_div)
show_editor = () => {}
}
let on_fail = e => {
// We abort on purpose when devtools asks for a reload — that's not a
// failure, so don't paint the error UI
if (abort_controller.signal.aborted) return
console.log(e?.stack || e)
textarea.style.border = '4px red solid'
textarea.style.background = '#fee'
textarea.style.color = '#800' // else dark mode puts white text on the pink
textarea.disabled = true
send_dev_message({ action: "get_failed", get_failed: '' + e })
}
// We defer show_editor() until the first update arrives, so a subscription
// that dies before then needs to show the editor for its error to be seen
var on_subscribe_fail = e => {
if (abort_controller.signal.aborted) return
show_editor()
on_fail(e)
}
var og_headers = headers
// for blobs, let's not load the blob twice unnecessarily
if (merge_type === 'aww')
get_parents = () => og_headers.version && JSON.parse(`[${og_headers.version}]`)
try {
response = await braid_fetch_wrapper(window.location.href, {
version: null,
parents: () => get_parents(),
peer,
headers: { Accept: content_type, ...(merge_type ? { ['Merge-Type']: merge_type } : {}),
// dt history is much faster shipped as binary chunks
...(merge_type === 'dt' && encoding_dt ? { 'Accept-Multiresponse-Encoding': 'dt' } : {}) },
signal: abort_controller.signal,
cache: 'no-store',
subscribe: true,
retry: true,
onSubscriptionStatus: (status) => {
set_subscription_online(status.online)
if (on_subscription_status) on_subscription_status(status)
}
})
} catch (e) {
if (abort_controller.signal.aborted) return
console.log('braid_fetch_wrapper failed: ' + e)
get_failed = '' + e
send_dev_message({ action: "get_failed", get_failed })
textarea.value = get_failed
on_fail(e)
return
}
record_response(response)
if (headers.subscribe !== '?1' && headers.subscribe !== 'true') {
abort_controller.abort()
return
}
if (headers['merge-type']) merge_type = headers['merge-type']
// application/http-history frames the subscription; it is not the repr.
// When the response doesn't name a repr, fall back to the type we asked for
var repr_type = headers['repr-type'] ??
(headers['content-type']?.startsWith('application/http-history')
? content_type : headers['content-type'])
if (repr_type?.split(/[;,]/)[0] === 'text/html' && !edit_source) {
// skip first show_editor attempt
var og_show_editor = show_editor
show_editor = () => show_editor = og_show_editor
}
if (merge_type === 'dt') {
// initSync caches, so rerequests re-enter here for free
let wasmModuleBuffer = await (await fetch(chrome.runtime.getURL('dt_bg.wasm'))).arrayBuffer();
initSync({ module: wasmModuleBuffer })
let last_text = "";
let last_text_code_points = 0;
let outstandings = make_linklist();
doc = new Doc(peer);
sync.cleanups.push(() => { doc?.free(); doc = null })
get_parents = () => doc.getRemoteVersion().map((x) => x.join("-")).sort()
// The document holds the whole history and can be asked about any two
// points in it directly, which beats replaying anything. It goes away
// while a subscription is being replaced, and there is nothing to show
// until its replacement has some history in it.
on_show_diff = (from_version, to_version, colors, show_deletions, at) =>
show_diff_view(diff_d,
from_version && doc && dt_diff_from(doc, from_version, to_version),
colors, show_deletions, at)
textarea.addEventListener("input", async () => {
let commonStart = 0;
let commonStart_codePoints = 0;
while (
commonStart < Math.min(last_text.length, textarea.value.length) &&
last_text.codePointAt(commonStart) == textarea.value.codePointAt(commonStart)
) {
commonStart += textarea.value.codePointAt(commonStart) > 0xffff ? 2 : 1
commonStart_codePoints++
}
let commonEnd = 0;
let commonEnd_codePoints = 0;
let left_over = Math.min(
last_text.length - commonStart,
textarea.value.length - commonStart
)
while (commonEnd < left_over) {
let a = last_text.codePointAt(last_text.length - commonEnd - 1)
let b = textarea.value.codePointAt(textarea.value.length - commonEnd - 1)
if (a != b) break
if (a >= 0xD800 && a <= 0xDFFF) {
if (commonEnd + 1 >= left_over) break
a = last_text.codePointAt(last_text.length - commonEnd - 2)
b = textarea.value.codePointAt(textarea.value.length - commonEnd - 2)
if (a != b) break
commonEnd += 2
} else {
commonEnd++
}
commonEnd_codePoints++
}
let numCodePointsToDelete = last_text_code_points - commonStart_codePoints - commonEnd_codePoints;
let stuffToInsert = textarea.value.slice(
commonStart,
textarea.value.length - commonEnd
);
last_text = textarea.value;
last_text_code_points = commonStart_codePoints + commonEnd_codePoints + count_code_points(stuffToInsert)
let v = doc.getRemoteVersion().map(v => v.join('-'));
if (numCodePointsToDelete)
for (let i = 0; i < numCodePointsToDelete; i++)
doc.del(commonStart_codePoints + numCodePointsToDelete - 1 - i, 1)
if (stuffToInsert) doc.ins(commonStart_codePoints, stuffToInsert);
for (let u of doc.getUpdates(v)) {
// An update covers a run of events; its first is named outright
let start_version_seq = decode_version(u.first_event)[1]
let ops = {
retry: true,
method: "PUT",
mode: "cors",
headers: { "Merge-Type": merge_type },
repr_type: content_type,
version: u.version,
parents: u.parents,
patches: u.patches,
peer
};
versions.push(ops)
send_dev_message({ action: "new_version", version: ops })
let outstanding = {
version: u.version,
ac: new AbortController(),
}
outstandings.push(outstanding)
textarea.style.caretColor = 'red'
rest()
async function rest() {
try {
// The request gets a copy. braid_fetch adds an AbortSignal and
// swaps the headers for a Headers object, and neither of those
// survives the structured clone that carries `versions` over to
// the devtools panel — so the record we keep stays plain data.
await braid_fetch_wrapper(window.location.href,
{...ops, signal: outstanding.ac.signal});
outstandings.remove(outstanding)
} catch (e) {
if (is_access_denied(e)) {
let x = outstanding
while (x) {
if (x != outstanding) x.ac.abort()
for (let i = versions.length - 1; i >= 0; i--) {
if (versions[i].version.length === x.version.length && versions[i].version.every((v, i) => v === x.version[i])) {
versions.splice(i, 1)
break
}
}
send_dev_message({ action: "new_version", remove_version: x.version })
outstandings.remove(x)
x = x.next
}
let rollback_to = doc.getRemoteVersion().map(v => {
if (v[0] === peer) v[1] = start_version_seq - 1
return v.join('-')
})
let new_doc = Doc.fromBytes(
doc.toBytesAt(doc.remoteToLocalVersion(rollback_to)))
doc.free()
doc = new_doc
textarea.value = last_text = doc.get()
last_text_code_points = count_code_points(last_text)
} else on_fail(e)
}
if (!outstandings.size) textarea.style.caretColor = ''
}
}
});
// Set the textarea straight from the doc, holding the cursor's
// index steady
function seed_textarea_from_doc() {
var s0 = textarea.selectionStart, s1 = textarea.selectionEnd
textarea.value = last_text = doc.get()
last_text_code_points = count_code_points(last_text)
textarea.selectionStart = Math.min(s0, textarea.value.length)
textarea.selectionEnd = Math.min(s1, textarea.value.length)
}
// Show the doc's changes since before_v in the textarea
function flush_textarea(before_v) {
// The textarea normalizes \r\n to \n and \r to \n, but last_text preserves \r's.
// Compare and map selection positions from textarea space to last_text space.
let { in_sync, sel } = compareNormalizedAndMapSel(
textarea.value,
last_text,
[textarea.selectionStart, textarea.selectionEnd]
)
if (!in_sync) errorify("textarea out of sync somehow!")
let new_text = applyChanges(
last_text,
sel,
doc.xfSince(before_v)
)
// Convert sel back from last_text space to textarea space
mapSelToNormalized(new_text, sel)
textarea.value = last_text = new_text
last_text_code_points = count_code_points(last_text)
textarea.selectionStart = sel[0]
textarea.selectionEnd = sel[1]
}
response.subscribe(update => {
let { version, parents, patches, body, status } = update
if (status && parseInt(status) !== 200)
return console.log(`ignoring update with status ${status}`)
if (textarea.hasAttribute("readonly")) {
show_editor()
textarea.removeAttribute("readonly")
textarea.removeAttribute('disabled')
// textarea.focus()
}
if (update.extra_headers?.['content-encoding'] === 'dt') {
// The server only marks the encoding per-update, so surface it in
// the devtools response column when the first binary update lands
if (headers.encoding !== 'dt') {
headers.encoding = 'dt'
send_dev_message({ action: "new_headers", headers })
}
// Remember the frontier, so we can tell what this chunk adds
let before_remote = doc.getRemoteVersion().map(x => x.join('-')).sort()
let before_v = doc.getLocalVersion()
// The body is a chunk of history in raw dt bytes; merge it directly
doc.mergeBytes(update.body)
// And expand it into viz rows, just like a server expands its
// dt file into updates for the wire
// Hand the devtools the chunk exactly as it arrived, in dt bytes.
// It keeps its own copy of the document and expands the chunk
// itself, which for a large history is a few hundred kilobytes here
// rather than megabytes of expanded versions in tens of thousands of
// messages.
let bin = ''
for (let i = 0; i < update.body.length; i++)
bin += String.fromCharCode(update.body[i])
send_dev_message({ action: "dt_history", bytes: btoa(bin) })
// The page's own list still needs them, for the diff view
for (let u of doc.getUpdates(before_remote))
versions.push({ method: "GET", version: u.version,
parents: u.parents, patches: u.patches })
if (before_v.length) {
flush_textarea(before_v)
// Wide concurrent spans can defeat xfSince's replay, so check
// the result against the doc, and reseed if it drifted
if (last_text !== doc.get()) seed_textarea_from_doc()
} else
// xfSince can't replay a whole history from scratch, so seed
// the textarea straight from the merged doc
seed_textarea_from_doc()
return
}
if (body) body = update.body_text
if (patches) for (let p of patches) p.content = p.content_text
if (!patches) {
let new_version = {
method: "GET",
version,
parents,
patches: [{ unit: 'text', range: '[0:0]', content: body }]
}
versions.push(new_version)
send_dev_message({ action: "new_version", version: new_version })
return;
}
let v = decode_version(version[0])
if (doc.knownSeqSpan(v[0], v[1], v[1])) return
let new_version = {
method: "GET",
version,
parents,
patches
}
versions.push(new_version)
send_dev_message({ action: "new_version", version: new_version })
let before_v = doc.getLocalVersion();
try {
patches = patches.map((p) => ({
...p,
range: p.range.match(/\d+/g).map((x) => parseInt(x)),
...(p.content ? { content: p.content, content_codepoints: [...p.content] } : {}),
}))
var high_seq = v[1]
var low_seq = v[1] + 1 - patches.reduce((a, b) => a + (b.content?.length ? b.content_codepoints.length : 0) + (b.range[1] - b.range[0]), 0)
v = encode_version(v[0], low_seq)
let ps = parents
// Each edit is positioned against the document as it stood at its own
// parents, so they can all go in together and be merged once.
let ops = []
let offset = 0
for (let p of patches) {
// delete
let del = p.range[1] - p.range[0]
if (del) {
let [va, vs] = decode_version(v)
ops.push({ agent: va, seq: vs, parents: ps,
pos: p.range[0] + offset, del })
offset -= del
ps = [`${va}-${vs + (del - 1)}`]
v = `${va}-${vs + del}`
}
// insert
if (p.content?.length) {
let [va, vs] = decode_version(v)
ops.push({ agent: va, seq: vs, parents: ps,
pos: p.range[1] + offset, ins: p.content })
offset += p.content_codepoints.length
ps = [`${va}-${vs + (p.content_codepoints.length - 1)}`]
v = `${va}-${vs + p.content_codepoints.length}`
}
}
doc.applyRemoteOps(ops)
} catch (e) {
errorify(e)
}
flush_textarea(before_v)
}, on_subscribe_fail)
} else if (merge_type === 'simpleton') {
console.log(`got simpleton..`)
var hl = textarea_highlights(textarea)
var applying_remote = false
var cursor_sync = await cursor_client(window.location.href, {
peer: Math.random().toString(36).slice(2),
get_text: () => textarea.value,
on_change: (sels) => {
for (var [id, ranges] of Object.entries(sels)) {
if (!ranges.length) { hl.remove(id); continue }
hl.set(id, ranges.map(r => ({
from: r.from, to: r.to,
color: r.from === r.to ? peer_color(id) : peer_bg_color(id)
})))
}
hl.render()
}
})
// If we got disconnected while the cursors were connecting, take them down
if (cursor_sync && sync.dead) { cursor_sync.destroy(); cursor_sync = null }
if (cursor_sync) {
sync.cleanups.push(() => cursor_sync.destroy())
on_subscription_status = ({online}) => {
online ? cursor_sync.online() : cursor_sync.offline()
}
if (window.subscription_online) cursor_sync.online()
var on_selectionchange = function() {
if (applying_remote) return
if (document.activeElement !== textarea) return
cursor_sync.set(textarea.selectionStart, textarea.selectionEnd)
}
document.addEventListener('selectionchange', on_selectionchange)
sync.cleanups.push(() =>
document.removeEventListener('selectionchange', on_selectionchange))
}
var char_counter = -1 // Counts the numbers of inserts and deletes generated by this client
var current_version = []
var last_seen_state = null
var outstanding_changes = make_linklist()
var max_outstanding_changes = 10
get_parents = () => current_version
response.subscribe(update => {
if (update.status && parseInt(update.status) !== 200) return console.log(`ignoring update with status ${update.status}`)
if (update.body) update.body = update.body_text
if (update.patches) for (let p of update.patches) p.content = p.content_text
if (textarea.hasAttribute("readonly")) {
show_editor()
textarea.removeAttribute("readonly")
textarea.removeAttribute('disabled')
// textarea.focus()
}
if (current_version.length === (!update.parents ? 0 : update.parents.length) && current_version.every((v, i) => v === update.parents[i])) {
current_version = update.version