-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
2768 lines (2377 loc) · 87.1 KB
/
index.js
File metadata and controls
2768 lines (2377 loc) · 87.1 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
// Name: CLΔ Core
// ID: cldeltacore
// Description: Essentials for P2P network connectivity.
// By: MikeDEV <https://scratch.mit.edu/users/MikeDEVTheDucklord/>
// License: MIT
/*
CloudLink Delta Core Extension
MIT License
Copyright (C) 2025 CloudLink Delta.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/*
https://github.com/peers/peerjs
(source: https://unpkg.com/peerjs@1.5.5/dist/peerjs.min.js)
Copyright (c) 2015 Michelle Bu and Eric Zhang, http://peerjs.com
The MIT License
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
;(function (Scratch) {
'use strict'
// DO NOT INCREMENT THIS VALUE UNLESS A SIGNIFICANT CHANGE TO THE PROTOCOL IS INTENDED
const DIALECT_REVISION = 0
// Extension version information
const EXTENSION_VERSION = {
type: 'Scratch', // Do not change this
major: 1,
minor: 0,
patch: 0
}
// Dynamically load PeerJS dependencies
const PEERJS_SOURCES = [
'https://unpkg.com/peerjs@1.5.5/dist/peerjs.min.js',
'https://cdn.jsdelivr.net/npm/peerjs@1.5.5/dist/peerjs.min.js'
]
// Default arguments to use for the extension
const SESSION_SERVER = {
host: 'peerjs.mikedev101.cc',
port: 443,
secure: true,
path: '/',
key: 'peerjs',
connectTimeoutMs: 10000,
config: {
iceTransportPolicy: 'all',
iceServers: [
{
urls: [
'stun:vpn.mikedev101.cc:3478',
'stun:vpn.mikedev101.cc:5349'
]
},
{
urls: [
'turn:vpn.mikedev101.cc:3478',
'turn:vpn.mikedev101.cc:5349'
],
username: 'free',
credential: 'free'
},
{
urls: [
'stun:stun.l.google.com:19302',
'stun:stun.l.google.com:5349',
'stun:stun1.l.google.com:3478',
'stun:stun1.l.google.com:5349',
'stun:stun2.l.google.com:19302',
'stun:stun2.l.google.com:5349',
'stun:stun3.l.google.com:3478',
'stun:stun3.l.google.com:5349',
'stun:stun4.l.google.com:19302',
'stun:stun4.l.google.com:5349',
'stun:stun.cloudflare.com:3478',
'stun:stun.cloudflare.com:53'
]
},
]
}
}
const blockIcon =
'data:image/svg+xml;charset=utf-8,%3Csvg%20width%3D%22312%22%20height%3D%22218%22%20viewBox%3D%220%200%20312%20218%22%20fill%3D%22none%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M155.88%200C194.829%200.000212318%20226.786%2030.1084%20229.987%2068.4414H237.391C278.466%2068.4414%20311.759%20101.922%20311.759%20143.221C311.759%20184.52%20278.466%20218%20237.391%20218H74.3682C33.2934%20218%200%20184.52%200%20143.221C0.000123011%20101.922%2033.2935%2068.4415%2074.3682%2068.4414H81.7715C84.9733%2030.1082%20116.931%200%20155.88%200ZM155.88%2010C122.221%2010%2094.5136%2036.0335%2091.7373%2069.2744L90.9717%2078.4414H74.3682C38.8684%2078.4415%2010.0001%20107.392%2010%20143.221C10%20179.049%2038.8683%20208%2074.3682%20208H237.391C272.891%20208%20301.759%20179.049%20301.759%20143.221C301.759%20107.392%20272.891%2078.4414%20237.391%2078.4414H220.788L220.023%2069.2744C217.246%2036.0337%20189.539%2010.0002%20155.88%2010Z%22%20fill%3D%22white%22%2F%3E%3Cpath%20d%3D%22M109.5%20180V172.5L149.85%2072.4502H162L202.2%20172.5V180H109.5ZM124.95%20167.85H186.6L161.55%20102.45C161.25%20101.65%20160.7%20100.2%20159.9%2098.1002C159.1%2096.0002%20158.3%2093.8502%20157.5%2091.6502C156.8%2089.3502%20156.25%2087.6002%20155.85%2086.4002C155.35%2088.4002%20154.75%2090.4502%20154.05%2092.5502C153.45%2094.5502%20152.8%2096.4002%20152.1%2098.1002C151.5%2099.8002%20151%20101.25%20150.6%20102.45L124.95%20167.85Z%22%20fill%3D%22white%22%2F%3E%3C%2Fsvg%3E'
const menuIcon =
'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzczIiBoZWlnaHQ9IjM3MyIgdmlld0JveD0iMCAwIDM3MyAzNzMiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxjaXJjbGUgY3g9IjE4Ni41IiBjeT0iMTg2LjUiIHI9IjE4Ni41IiBmaWxsPSIjMEY3RUJEIi8+CjxwYXRoIGQ9Ik0xODYuODggNjFDMjI1LjgyOSA2MS4wMDAyIDI1Ny43ODYgOTEuMTA4NCAyNjAuOTg3IDEyOS40NDFIMjY4LjM5MUMzMDkuNDY2IDEyOS40NDEgMzQyLjc1OSAxNjIuOTIyIDM0Mi43NTkgMjA0LjIyMUMzNDIuNzU5IDI0NS41MiAzMDkuNDY2IDI3OSAyNjguMzkxIDI3OUgxMDUuMzY4QzY0LjI5MzQgMjc5IDMxIDI0NS41MiAzMSAyMDQuMjIxQzMxLjAwMDEgMTYyLjkyMiA2NC4yOTM1IDEyOS40NDIgMTA1LjM2OCAxMjkuNDQxSDExMi43NzJDMTE1Ljk3MyA5MS4xMDgyIDE0Ny45MzEgNjEgMTg2Ljg4IDYxWk0xODYuODggNzFDMTUzLjIyMSA3MSAxMjUuNTE0IDk3LjAzMzUgMTIyLjczNyAxMzAuMjc0TDEyMS45NzIgMTM5LjQ0MUgxMDUuMzY4QzY5Ljg2ODQgMTM5LjQ0MiA0MS4wMDAxIDE2OC4zOTIgNDEgMjA0LjIyMUM0MSAyNDAuMDQ5IDY5Ljg2ODMgMjY5IDEwNS4zNjggMjY5SDI2OC4zOTFDMzAzLjg5MSAyNjkgMzMyLjc1OSAyNDAuMDQ5IDMzMy43NTkgMjA0LjIyMUMzMzIuNzU5IDE2OC4zOTIgMzAzLjg5MSAxMzkuNDQxIDI2OC4zOTEgMTM5LjQ0MUgyNTEuNzg4TDI1MS4wMjMgMTMwLjI3NEMyNDguMjQ2IDk3LjAzMzcgMjIwLjUzOSA3MS4wMDAyIDE4Ni44OCA3MVoiIGZpbGw9IndoaXRlIi8+CjxwYXRoIGQ9Ik0xNDAuNSAyNDFWMjMzLjVMMTgwLjg1IDEzMy40NUgxOTNMMjMzLjIgMjMzLjVWMjQxSDE0MC41Wk0xNTUuOTUgMjI4Ljg1SDIxNy42TDE5Mi41NSAxNjMuNDVDMTkyLjI1IDE2Mi42NSAxOTEuNyAxNjEuMiAxOTAuOSAxNTkuMUMxOTAuMSAxNTcgMTg5LjMgMTU0Ljg1IDE4OC41IDE1Mi42NUMxODcuOCAxNTAuMzUgMTg3LjI1IDE0OC42IDE4Ni44NSAxNDcuNEMxODYuMzUgMTQ5LjQgMTg1Ljc1IDE1MS40NSAxODUuMDUgMTUzLjU1QzE4NC40NSAxNTUuNTUgMTgzLjggMTU3LjQgMTgzLjEgMTU5LjFDMTgyLjUgMTYwLjggMTgyIDE2Mi4yNSAxODEuNiAxNjMuNDVMMTU1Ljk1IDIyOC44NVoiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPgo='
// Require the extension to be unsandboxed
if (!Scratch.extensions.unsandboxed) {
alert(
'The CloudLink Delta extension must be loaded in an unsandboxed environment.'
)
return
}
// Require access to the VM and/or runtime
if (!Scratch.vm || !Scratch.vm.runtime) {
alert(
"The CloudLink Delta extension could not detect access to the Scratch VM and/or runtime; this extension won't work."
)
return
}
// Require browser to support Web Locks API (used for concurrency)
if (!navigator.locks) {
alert(
"The CloudLink Delta extension could not detect Web Locks support; this extension won't work."
)
return
}
// Initialize the plugin loader
if (!Scratch.vm.runtime.ext_cldelta_pluginloader) {
Scratch.vm.runtime.ext_cldelta_pluginloader = new Array()
}
/*
Block utilities for creating blocks with less code.
Based on Rotur.js by Mistium
https://extensions.mistium.com/featured/Rotur.js
MPL-2.0
This Source Code is subject to the terms of the Mozilla Public License, v2.0,
If a copy of the MPL was not distributed with this file,
Then you can obtain one at https://mozilla.org/MPL/2.0/
*/
// Defines a set of block types
const opcodes = {
conditional: (opcode, text, options = {}) => ({
opcode,
text: text.map(v => Scratch.translate(v)),
blockType: Scratch.BlockType.CONDITIONAL,
branchCount: text.length - 1,
...options
}),
reporter: (opcode, text, args = {}, options = {}) => ({
opcode,
blockType: Scratch.BlockType.REPORTER,
text: Scratch.translate(text),
arguments: args,
...options
}),
command: (opcode, text, args = {}, options = {}) => ({
opcode,
blockType: Scratch.BlockType.COMMAND,
text: Scratch.translate(text),
arguments: args,
...options
}),
boolean: (opcode, text, args = {}, options = {}) => ({
opcode,
blockType: Scratch.BlockType.BOOLEAN,
text: Scratch.translate(text),
arguments: args,
...options
}),
hat: (opcode, text, options = {}) => ({
opcode,
blockType: Scratch.BlockType.HAT,
text: Scratch.translate(text),
isEdgeActivated: false,
...options
}),
event: (opcode, text, options = {}) => ({
opcode,
blockType: Scratch.BlockType.EVENT,
text: Scratch.translate(text),
isEdgeActivated: false,
...options
}),
button: (text, func, options = {}) => ({
blockType: Scratch.BlockType.BUTTON,
text: Scratch.translate(text),
func,
...options
}),
label: text => ({
blockType: Scratch.BlockType.LABEL,
text: Scratch.translate(text)
}),
separator: () => '---'
}
const args = {
string: (value, options = {}) => ({
type: Scratch.ArgumentType.STRING,
defaultValue: value,
...options
}),
number: (value, options = {}) => ({
type: Scratch.ArgumentType.NUMBER,
defaultValue: value,
...options
}),
boolean: (value, options = {}) => ({
type: Scratch.ArgumentType.BOOLEAN,
defaultValue: value,
...options
})
}
function getTarget (targetRef, name, type = '') {
const target =
typeof targetRef === 'string'
? Scratch.vm.runtime.getTargetById(targetRef)
: targetRef
const findVariable = current => {
if (!current || !current.variables) return undefined
return Object.values(current.variables).find(
v => v.name === name && v.type === type
)
}
const localMatch = findVariable(target)
if (localMatch) return localMatch
const stage = Scratch.vm.runtime.getTargetForStage
? Scratch.vm.runtime.getTargetForStage()
: null
return findVariable(stage)
}
// Ah yes, Perry the platypus. It seems you've found my callback-inator.
class CallbackInator {
constructor () {
this.calls = new Map()
this.debug = 0
}
/**
* Sets the debug level for the CallbackInator.
*
* @param {number} level - The desired debug level. Higher numbers enable more verbose logging.
*
* Adjust the verbosity of logging for debugging purposes. A higher level means more detailed logs.
*/
set_debug_level (level) {
this.debug = level
}
/**
* Unbinds a callback function from a specified event name.
* @param {string} name - The name of the event to unbind the callback from.
* @param {string} id - The ID of the callback to unbind. If set to "*", all callbacks for the event will be unbound.
* @returns {void}
*
* Does nothing if the callback was never bound.
*/
unbind (name, id) {
if (id === '*') {
this.calls.delete(name)
if (this.debug > 2) console.log(`Unbound all callbacks for "${name}"`)
return
}
if (!this.calls.has(name) || !this.calls.get(name).has(id)) return
this.calls.get(name).delete(id)
if (this.debug > 2) {
console.log(`Unbound callback for "${name}" with ID "${id}"`)
}
}
/**
* Binds a callback function to a specified event name.
*
* @param {string} name - The name of the event to bind the callback to.
* @param {function} callback - The function to be called when the event is triggered.
* @param {string} [id="default"] - An optional identifier for the callback.
* @throws {TypeError} If the provided callback is not a function.
*/
bind (name, callback, id = 'default') {
if (!this.calls.has(name)) {
this.calls.set(name, new Map())
}
if (typeof callback !== 'function') {
if (this.debug > 0) console.error('Callback must be a function')
return
}
this.calls.get(name).set(id, callback)
if (this.debug > 2) {
console.log(`Bound callback for "${name}" with ID "${id}"`)
}
}
/**
* Executes all registered callbacks for a given event name with the provided arguments.
*
* @param {string} name - The name of the event whose callbacks should be executed.
* @param {...*} args - Arguments to pass to the callbacks.
* @returns {void}
*
* Logs warnings if there are no callbacks registered, if the callbacks map is null,
* if the callbacks map is empty, or if any callback is not a function. Logs an error
* if the registered callback is not a map.
*/
call (name, ...args) {
if (!this.calls.has(name)) {
if (this.debug > 1) console.warn(`No callbacks registered for "${name}"`)
return
}
const callbacks = this.calls.get(name)
if (!callbacks || callbacks.size === 0) {
if (this.debug > 1) console.warn(`No callbacks registered for "${name}"`)
return
}
if (!(callbacks instanceof Map)) {
if (this.debug > 0) {
console.error('Callback was not a map! Got ', typeof callbacks, 'instead.')
}
return
}
if (this.debug > 2) console.log(`Executing callbacks for "${name}"`)
for (const callback of callbacks.values()) {
if (callback === null || typeof callback !== 'function') {
if (this.debug > 1) {
console.warn(
`Callback registered for "${name}" is null or not a function`
)
}
continue
}
try {
if (this.debug > 2) console.log(`Executing callback ${callback}`)
callback(...args)
} catch (error) {
if (this.debug > 0) {
console.error(`Error executing callback for "${name}"`, error)
}
}
}
}
}
class CloudLinkDelta_Core {
constructor () {
this.peer = null
this.peerJsLoader = null
this.name = ''
this.dataConnections = new Map()
this.newestConnected = ''
this.lastDisconnected = ''
this.lastPacket = {
peer: '',
channel: ''
}
this.lastGlobalPacket = {
channel: '',
origin: ''
}
this.lastPeerErrorInfo = ''
this.peerStatus = 'idle'
this.peerConnectTimeout = null
this.outgoingConnectTimeoutMs = 10000
this.verboseLogs = false
this.maskedConnections = new Set()
this.callbacks = new CallbackInator()
this.plugins = new Array()
this.remapper = new Map()
this.taskQueue = new Map()
this.pingPongEnabled = true
this.pingPongInterval = 5000
this.prettifier = null
this.diagnostics = {
guaranteedToWork: false,
browser: '',
dataCapable: false,
reliableCapable: false,
mediaCapable: false
}
// Allow plugins to use their own ID resolvers as key-value pairs
this.idRemapper = null
this.enableIdRemapper = false
// Allow plugins to redirect packets to another peer
this.packetRedirector = null
this.enablePacketRedirector = false
/**
* A Map to register plugin handlers for specific opcodes.
* Maps: opcode (string) -> handler (function)
*/
this.opcodeHandlers = new Map()
/**
* A map of plugin-specific message handlers.
* Plugins (like Sync, Discovery) will register themselves here.
* @type {Object<string, function>}
*/
this.onMessage = {}
/**
* Key is the channel label.
* Value is an object containing the most recent value and the origin ID.
* @type {Map<string, Object>}
*/
this.gmsg_state = new Map()
this.pmsg_state = new Map()
this.sessionServer = this._cloneSessionServer(SESSION_SERVER)
this.sessionServerInput = SESSION_SERVER.host
}
// Internal functions that aren't mapped to blocks
_cloneIceServer (server) {
const cloned = { ...server }
if (Array.isArray(cloned.urls)) {
cloned.urls = [...cloned.urls]
}
return cloned
}
_cloneSessionServer (server) {
return {
...server,
config: {
...server.config,
iceServers: (server.config?.iceServers || []).map(ice =>
this._cloneIceServer(ice)
)
}
}
}
_normalizePeerServerPath (path) {
let normalized = String(path || '/').trim()
if (!normalized.startsWith('/')) {
normalized = '/' + normalized
}
normalized = normalized.replace(/\/+$/, '')
if (normalized.toLowerCase().endsWith('/peerjs')) {
normalized = normalized.slice(0, -7)
}
if (!normalized) {
normalized = '/'
}
if (!normalized.endsWith('/')) {
normalized += '/'
}
return normalized
}
_normalizeSessionServerInput (input) {
const raw = Scratch.Cast.toString(input).trim()
const baseServer = this._cloneSessionServer(this.sessionServer || SESSION_SERVER)
if (!raw) {
return baseServer
}
let candidate = raw
if (!/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(candidate)) {
candidate = 'https://' + candidate
}
let parsed
try {
parsed = new URL(candidate)
} catch {
throw new Error('Invalid session server IP/URL.')
}
const secure = parsed.protocol === 'https:' || parsed.protocol === 'wss:'
const host = parsed.hostname
const port = parsed.port
? parseInt(parsed.port, 10)
: secure
? 443
: 80
if (!host) {
throw new Error('Session server IP/URL must include a valid host.')
}
baseServer.host = host
baseServer.port = Number.isFinite(port) && port > 0 ? port : secure ? 443 : 80
baseServer.secure = secure
baseServer.path = this._normalizePeerServerPath(parsed.pathname)
return baseServer
}
_normalizeIceUrl (url, kind) {
let value = Scratch.Cast.toString(url).trim()
if (!value) {
throw new Error(`${kind.toUpperCase()} URL cannot be empty.`)
}
if (!/^[a-z]+:/i.test(value)) {
value = `${kind}:${value}`
}
if (kind === 'stun' && !/^stuns?:/i.test(value)) {
throw new Error('STUN URL must begin with stun: or stuns:.')
}
if (kind === 'turn' && !/^turns?:/i.test(value)) {
throw new Error('TURN URL must begin with turn: or turns:.')
}
return value
}
_syncPeerConfig () {
if (this.peer && this.peer.options && this.peer.options.config) {
this.peer.options.config.iceTransportPolicy =
this.sessionServer.config.iceTransportPolicy
this.peer.options.config.iceServers =
this.sessionServer.config.iceServers.map(ice =>
this._cloneIceServer(ice)
)
}
}
_configureSessionServer (input) {
try {
this.sessionServer = this._normalizeSessionServerInput(input)
const raw = Scratch.Cast.toString(input).trim()
this.sessionServerInput = raw || this.sessionServer.host
this._syncPeerConfig()
return true
} catch (err) {
this._recordPeerError(err)
return false
}
}
_addIceServer (url, kind, extra = {}) {
try {
const normalized = this._normalizeIceUrl(url, kind)
const entry = {
urls: normalized
}
if (extra && typeof extra === 'object') {
if (extra.username !== undefined) {
entry.username = extra.username
}
if (extra.credential !== undefined) {
entry.credential = extra.credential
}
}
const nextIceServers = this.sessionServer.config.iceServers.map(ice =>
this._cloneIceServer(ice)
)
const alreadyExists = nextIceServers.some(server => {
const urls = Array.isArray(server.urls) ? server.urls : [server.urls]
const urlMatch = urls.some(existing => {
return String(existing).toLowerCase() === normalized.toLowerCase()
})
if (!urlMatch) return false
const existingUsername =
server.username === undefined ? '' : String(server.username)
const existingCredential =
server.credential === undefined ? '' : String(server.credential)
const nextUsername =
entry.username === undefined ? '' : String(entry.username)
const nextCredential =
entry.credential === undefined ? '' : String(entry.credential)
return (
existingUsername === nextUsername &&
existingCredential === nextCredential
)
})
if (!alreadyExists) {
nextIceServers.unshift(entry)
}
this.sessionServer.config.iceServers = nextIceServers
this._syncPeerConfig()
} catch (err) {
this._recordPeerError(err)
}
}
_getPeerConstructor () {
if (typeof Peer !== 'undefined') return Peer
if (typeof globalThis !== 'undefined') {
if (globalThis.Peer) return globalThis.Peer
if (globalThis.peerjs && globalThis.peerjs.Peer) {
return globalThis.peerjs.Peer
}
}
if (typeof window !== 'undefined') {
if (window.Peer) return window.Peer
if (window.peerjs && window.peerjs.Peer) {
return window.peerjs.Peer
}
}
if (typeof self !== 'undefined') {
if (self.Peer) return self.Peer
if (self.peerjs && self.peerjs.Peer) {
return self.peerjs.Peer
}
}
return null
}
_loadScript (src) {
return new Promise((resolve, reject) => {
if (typeof document === 'undefined') {
reject(new Error('Document is unavailable, so PeerJS cannot be loaded.'))
return
}
const mount =
document.head || document.documentElement || document.body
if (!mount) {
reject(new Error('No document mount point was found for loading PeerJS.'))
return
}
const existing = Array.from(document.querySelectorAll('script')).find(
script => script.src === src
)
if (existing) {
if (this._getPeerConstructor()) {
resolve()
return
}
const handleLoad = () => {
existing.removeEventListener('load', handleLoad)
existing.removeEventListener('error', handleError)
resolve()
}
const handleError = () => {
existing.removeEventListener('load', handleLoad)
existing.removeEventListener('error', handleError)
reject(new Error(`Failed to load PeerJS from ${src}`))
}
existing.addEventListener('load', handleLoad)
existing.addEventListener('error', handleError)
return
}
const script = document.createElement('script')
script.src = src
script.async = true
script.crossOrigin = 'anonymous'
script.onload = () => resolve()
script.onerror = () =>
reject(new Error(`Failed to load PeerJS from ${src}`))
mount.appendChild(script)
})
}
async _ensurePeerJsLoaded () {
const existingCtor = this._getPeerConstructor()
if (existingCtor) return existingCtor
if (this.peerJsLoader) return this.peerJsLoader
this.peerJsLoader = (async () => {
let lastError = null
for (const src of PEERJS_SOURCES) {
try {
await this._loadScript(src)
const PeerCtor = this._getPeerConstructor()
if (PeerCtor) return PeerCtor
lastError = new Error(
`PeerJS script loaded from ${src}, but no Peer constructor was exposed.`
)
} catch (err) {
lastError = err
}
}
throw (
lastError ||
new Error('PeerJS could not be loaded from any configured source.')
)
})()
try {
return await this.peerJsLoader
} catch (err) {
this.peerJsLoader = null
throw err
}
}
/**
* Converts a peer ID to a human-readable "pretty" format if a prettifier is registered.
* @param {string} id The peer ID to format.
* @returns {string} The formatted ID or the original ID.
* @private
*/
_prettyPeer (id) {
if (this.prettifier) return this.prettifier(id)
return id
}
_clearPeerConnectTimeout () {
if (this.peerConnectTimeout) {
clearTimeout(this.peerConnectTimeout)
this.peerConnectTimeout = null
}
}
_clearOutgoingConnectTimeout (conn) {
if (conn && conn._cldeltaConnectTimeout) {
clearTimeout(conn._cldeltaConnectTimeout)
conn._cldeltaConnectTimeout = null
}
}
_failOutgoingConnection (conn, message, error = null) {
this._clearOutgoingConnectTimeout(conn)
if (!conn) return
if (conn.label !== 'default') return
if (message) {
this.lastPeerErrorInfo = message
if (this.peer) this.peer.errorInfo = message
console.error('[CLΔ Core] ' + message, error || '')
Scratch.vm.runtime.startHats('cldeltacore_whenPeerHasError')
}
if (this.dataConnections.get(conn.peer) === conn && !conn.open) {
this.dataConnections.delete(conn.peer)
}
try {
if (!conn.open) conn.close()
} catch {}
}
_recordPeerError (error) {
const message =
error && typeof error === 'object'
? error.message || error.type || String(error)
: String(error)
this.lastPeerErrorInfo = message
if (this.peer) {
this.peer.errorInfo = message
}
console.error('[CLΔ Core] Peer error:', error)
Scratch.vm.runtime.startHats('cldeltacore_whenPeerHasError')
return message
}
_resetConnectionState () {
for (const tasks of this.taskQueue.values()) {
clearInterval(tasks.pinger)
clearInterval(tasks.poller)
}
this.taskQueue.clear()
for (const conn of this.dataConnections.values()) {
try {
conn.close()
} catch {}
}
this.dataConnections.clear()
this.newestConnected = ''
this.lastDisconnected = ''
this.lastPacket = {
peer: '',
channel: ''
}
this.lastGlobalPacket = {
channel: '',
origin: ''
}
this.gmsg_state.clear()
this.pmsg_state.clear()
}
/**
* Registers a function from a plugin to format peer IDs for logging.
* @param {object} plugin The plugin instance registering the function.
* @param {function} func The function that takes an ID and returns a string.
*/
registerPrettifier (plugin, func) {
if (this.prettifier) {
console.warn('[CLΔ Core] A prettifier is already registered. Overwriting.')
}
if (!plugin || typeof func !== 'function') {
console.error(
'[CLΔ Core] Prettifier registration failed: invalid plugin or function.'
)
return
}
this.prettifier = func
console.log(
`[CLΔ Core] Registered peer ID prettifier from plugin: ${plugin.id}`
)
}
removePrettifier () {
if (this.prettifier) {
this.prettifier = null
console.log('[CLΔ Core] Removed peer ID prettifier.')
}
}
_sendOnChannel (conn, label, message) {
const entry = this._getChan(conn, label)
if (!entry || !entry.chan) return false
const transport = entry.chan
const isOpen =
transport === conn ? !!conn.open : transport.readyState === 'open'
if (!isOpen) return false
try {
transport.send(message)
return true
} catch (err) {
console.warn(
`[CLΔ Core] Failed to send on channel "${label}" with peer "${this._prettyPeer(conn.peer)}":`,
err
)
return false
}
}
/**
* Internal "smart" send function.
* All outgoing packets should be routed through here.
* @param {object} packet - A packet object following the protocol schema.
* @private
*/
_send (packet) {
if (!this.peer || !this.peer.open) return
// Apply defaults and origin
const fullPacket = {
origin: this.peer.id,
ttl: 1,
target: '*', // Default to broadcast
channel: 'default',
...packet // The packet from the block will overwrite defaults
}
const { target, channel } = fullPacket
if (target === '*') {
const message = JSON.stringify(fullPacket)
// --- Broadcast to all peers ---
for (const conn of this.dataConnections.values()) {
// Do not transmit a broadcast event if the connection is masked
if (this.maskedConnections.has(conn.peer)) continue
if (!conn.channels || !conn.channels.has(channel)) continue
this._sendOnChannel(conn, channel, message)
}
return
}
let connectionTarget = target
if (this.enablePacketRedirector && this.packetRedirector) {
const redirected = this.packetRedirector(target)
if (redirected) {
connectionTarget = redirected
fullPacket.target = target
}
}
const message = JSON.stringify(fullPacket)
const conn = this.dataConnections.get(connectionTarget)
if (!conn) {
console.warn(
`[CLΔ Core] Cannot send packet: Not connected to peer "${connectionTarget}".`
)
return
}
if (!conn.channels || !conn.channels.has(channel)) {
console.warn(
`[CLΔ Core] Cannot send packet: Channel "${channel}" not open with peer "${connectionTarget}".`
)
return
}
if (!this._sendOnChannel(conn, channel, message)) {
console.warn(
`[CLΔ Core] Cannot send packet: Channel "${channel}" with peer "${connectionTarget}" is not ready.`
)
}
}
/**
* Runs diagnostics to determine the capabilities of the browser.
* @returns {object} Object containing the results of the diagnostics.
* @property {boolean} guaranteedToWork Whether the extension is guaranteed to work in the current browser.
* @property {string} browser The type of browser being used.
* @property {boolean} dataCapable Whether the browser supports data channels.
* @property {boolean} reliableCapable Whether the browser supports reliable data channels.
* @property {boolean} mediaCapable Whether the browser supports media capture.
*/
_runDiagnostics () {
this.diagnostics.guaranteedToWork = false
const browser = () => {
if (typeof navigator === 'undefined' || !navigator.userAgent) {
return 'Not a browser'
}
const ua = navigator.userAgent.toLowerCase()
if (ua.includes('firefox')) return 'firefox'
if (ua.includes('edg/') || ua.includes('edge')) return 'edge'
if (ua.includes('chrome') && !ua.includes('edg/') && !ua.includes('opr/')) {
return 'chrome'
}