-
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathflock.js
More file actions
2944 lines (2703 loc) · 103 KB
/
Copy pathflock.js
File metadata and controls
2944 lines (2703 loc) · 103 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
// Flock - Creative coding in 3D
// Dr Tracy Gardner - https://github.com/tracygardner
// Flip Computing Limited - flipcomputing.com
import * as acorn from 'acorn';
import * as walk from 'acorn-walk';
import HavokPhysics from '@babylonjs/havok';
import * as BABYLON from '@babylonjs/core';
import * as BABYLON_GUI from '@babylonjs/gui/2D/index.js';
import * as BABYLON_LOADER from '@babylonjs/loaders';
import { GradientMaterial } from '@babylonjs/materials';
import * as BABYLON_EXPORT from '@babylonjs/serializers';
// Point Babylon’s Draco loader at local folder for offline use
BABYLON.DracoCompression.Configuration = {
decoder: {
wasmUrl: './draco/draco_wasm_wrapper_gltf.js',
wasmBinaryUrl: './draco/draco_decoder_gltf.wasm',
fallbackUrl: './draco/draco_decoder_gltf.js',
},
};
import earcut from 'earcut';
import '@fontsource/atkinson-hyperlegible-next';
import '@fontsource/atkinson-hyperlegible-next/500.css';
import '@fontsource/atkinson-hyperlegible-next/600.css';
import '@fontsource/asap';
import '@fontsource/asap/500.css';
import '@fontsource/asap/600.css';
import { characterNames, getModelDisplayName } from './config';
import { FlowGraphLog10Block } from '@babylonjs/core';
const optionalBabylonDeps = { earcut, FlowGraphLog10Block };
const globalEarcutTarget = typeof globalThis !== 'undefined' ? globalThis : undefined;
if (globalEarcutTarget) {
Object.assign(globalEarcutTarget, optionalBabylonDeps);
}
import { flockCSG, setFlockReference as setFlockCSG } from './api/csg';
import { flockAnimate, setFlockReference as setFlockAnimate } from './api/animate';
import { flockSound, setFlockReference as setFlockSound } from './api/sound';
import { flockUI, setFlockReference as setFlockUI } from './api/ui';
import { flockMovement, setFlockReference as setFlockMovement } from './api/movement';
import { flockModels, setFlockReference as setFlockModels } from './api/models';
import { flockShapes, getManifold, setFlockReference as setFlockShapes } from './api/shapes';
import { flockTransform, setFlockReference as setFlockTransform } from './api/transform';
import { flockMaterial, setFlockReference as setFlockMaterial } from './api/material';
import { flockEffects, setFlockReference as setFlockEffects } from './api/effects';
import { flockPhysics, setFlockReference as setFlockPhysics } from './api/physics';
import { flockXR, setFlockReference as setFlockXR } from './api/xr';
import { flockControl, setFlockReference as setFlockControl } from './api/control';
import { flockScene, setFlockReference as setFlockScene } from './api/scene';
import { flockMesh, setFlockReference as setFlockMesh } from './api/mesh';
import { flockCamera, setFlockReference as setFlockCamera } from './api/camera';
import { flockEvents, setFlockReference as setFlockEvents } from './api/events';
import { flockMicrobit, setFlockReference as setFlockMicrobit } from './api/microbit';
import {
getMicrobitManager,
setFlockReference as setFlockMicrobitManager,
} from './microbit/manager.js';
import { flockMath, setFlockReference as setFlockMath } from './api/math';
import { flockSensing, setFlockReference as setFlockSensing } from './api/sensing';
import { translate } from './main/translation.js';
import { handleError, dismissBanner, showBanner, markReported } from './ui/notifications.js';
import { attachInteractIndicator, detachInteractIndicator } from './ui/interactIndicator.js';
import { InputManager } from './input/inputManager.js';
import { KeyboardSource } from './input/keyboardSource.js';
import { OnScreenSource } from './input/onScreenSource.js';
import { GamepadSource } from './input/gamepadSource.js';
import { CameraControls } from './input/cameraControls.js';
import { XRSource } from './input/xrSource.js';
import { getBoundKeys } from './input/bindings.js';
import {
enableSceneDescription,
announceSayText,
announceObjectSay,
getObjectLabel,
recordObjectPromptText,
recordObjectSayText,
setTransientSayText,
recordWorldInstructionText,
} from './accessibility/accessibility.js';
import { initUIAccessibility, clearUIControls } from './accessibility/uiA11y.js';
export const flock = {
blockDebug: false,
separateAnimations: true,
memoryDebug: false,
memoryMonitorInterval: 5000,
materialsDebug: false,
meshDebug: false,
performanceOverlay: false,
maxMeshes: 5000,
maxClonesPerSource: 500,
meshLimitEnabled: false,
meshRecyclingEnabled: false,
console: console,
havokAbortHandled: false,
triggerHandlingDebug: false,
soundDebug: false,
modelPath: './models/',
soundPath: './sounds/',
imagePath: './images/',
texturePath: './textures/',
// Keep optional Babylon dependencies referenced so bundlers include them.
optionalBabylonDeps,
engine: null,
engineReady: false,
eventDebug: false,
modelReadyPromises: new Map(),
pendingMeshCreations: 0,
pendingTriggers: new Map(),
pendingIntersections: new Map(),
_nameRegistry: new Map(),
_liveNameCache: new Map(),
_animationFileCache: {},
_ambiguousLiveNames: new Set(),
getModelDisplayName,
characterNames: characterNames,
alert: alert,
BABYLON: BABYLON,
BABYLON_LOADER: BABYLON_LOADER,
GradientMaterial: GradientMaterial,
scene: null,
highlighter: null,
glowLayer: null,
mainLight: null,
shadowLight: null,
shadowGenerator: null,
shadowCasters: new Set(),
xrFramebufferScale: 1.2,
xrFixedFoveation: 0.5,
hk: null,
havokInstance: null,
initialClearColor: null,
ground: null,
sky: null,
GUI: null,
EXPORT: null,
controlsTexture: null,
inputManager: null,
canvas: null,
abortController: null,
_renderLoop: null,
_renderLoopStopped: false,
_contextLostAt: null,
_escalationTimer: null,
_webglVisibilityListenerAdded: false,
_webglContextLostListenerAdded: false,
_audioVisibilityListenerAdded: false,
_audioSuspendedByVisibility: false,
document: document,
disposed: null,
events: {},
modelCache: {},
globalSounds: [],
originalModelTransformations: {},
modelsBeingLoaded: {},
geometryCache: {},
materialCache: {},
physicsShapeCache: {},
flockNotReady: true,
// Diagnostic flag like memoryDebug: logs raw micro:bit serial lines and
// WebUSB status chatter to the console (debug level) while true.
microbitDebug: false,
lastFrameTime: 0,
savedCamera: null,
...flockCSG,
...flockAnimate,
...flockSound,
...flockUI,
...flockMovement,
...flockModels,
...flockShapes,
...flockTransform,
...flockMaterial,
...flockEffects,
...flockPhysics,
...flockScene,
...flockMesh,
...flockCamera,
...flockXR,
...flockControl,
...flockEvents,
...flockMicrobit,
...flockSensing,
...flockMath,
// onBlockError lets the UI show a translated message from key + values.
onBlockError: null,
_debugLogging: undefined,
// Testing phase: warnings ON by default (?debug=false silences).
// TODO: revert to opt-in (`=== 'true'`, default false) after testing.
isDebugLoggingEnabled() {
if (flock._debugLogging === undefined) {
try {
flock._debugLogging = new URLSearchParams(window.location.search).get('debug') !== 'false';
} catch {
flock._debugLogging = true;
}
}
return flock._debugLogging;
},
reportBlockError({ key, values = {}, api, error } = {}) {
// A caught value can come straight from user code, so classify and report
// through safe primitives rather than its own getters.
const safe = error == null ? undefined : flock.sanitizeError(error);
if (safe?.name === 'AbortError') return;
// A stack overflow is nearly always runaway user recursion; report it as
// such. Message differs by engine (V8 "call stack", Firefox "recursion").
if (
(safe?.name === 'RangeError' || safe?.name === 'InternalError') &&
/call stack|recursion/i.test(safe.message)
) {
key = 'recursion_too_deep';
}
// One fault can fire in a burst — a stack-overflow cascade surfaces several
// times, and a per-frame loop error repeats endlessly. Collapse identical
// reports within a short window.
const now = Date.now();
const sig = `${key}\0${api ?? ''}\0${safe?.message ?? ''}`;
if (sig === flock._lastErrorSig && now - flock._lastErrorAt < 1000) {
return;
}
flock._lastErrorSig = sig;
flock._lastErrorAt = now;
if (flock.isDebugLoggingEnabled()) {
console.warn(`[flock] ${api ?? 'block'}: ${key}`, values, safe ?? '');
}
try {
flock.onBlockError?.({ key, values, api, error: safe });
} catch {
// a broken listener must not break the swallow path
}
},
// User code can throw any value, including an object whose name/message/stack
// getters throw or return non-strings. Read each once, defensively, into a
// plain Error so host handlers touch only safe primitives. (A getter that
// hangs rather than throws can't be defended against — that's a self-inflicted
// hang, like any infinite loop in user code.)
sanitizeError(error) {
const read = (get) => {
try {
const v = get();
return v == null ? '' : String(v);
} catch {
return '';
}
};
// A thrown primitive (e.g. `throw "bad input"`) has no .message, so use the
// value itself rather than losing the text.
const isPrimitive = error == null || (typeof error !== 'object' && typeof error !== 'function');
const safe = new Error(isPrimitive ? read(() => error) : read(() => error?.message));
safe.name = isPrimitive ? 'Error' : read(() => error?.name) || 'Error';
safe.stack = isPrimitive ? '' : read(() => error?.stack);
return safe;
},
requireMesh(target, { api, name } = {}) {
if (target instanceof flock.BABYLON.AbstractMesh) return true;
flock.reportBlockError({
key: target == null ? 'object_not_found' : 'target_not_a_mesh',
api,
values: { object: name },
});
return false;
},
// Enhanced error reporting with block context
createEnhancedError(error, code) {
const lines = code.split('\n');
const errorContext = {
message: error.message,
stack: error.stack,
codeSnippet: null,
suggestion: null,
};
// Try to extract line number from error
const lineMatch = error.stack?.match(/at .*:(\d+):\d+/);
if (lineMatch) {
const lineNum = parseInt(lineMatch[1]) - 1;
if (lineNum >= 0 && lineNum < lines.length) {
const start = Math.max(0, lineNum - 2);
const end = Math.min(lines.length, lineNum + 3);
errorContext.codeSnippet = lines
.slice(start, end)
.map((line, idx) => {
const actualLine = start + idx;
const marker = actualLine === lineNum ? '>>> ' : ' ';
return `${marker}${actualLine + 1}: ${line}`;
})
.join('\n');
}
}
// Add common error suggestions
if (error.message.includes('is not defined')) {
errorContext.suggestion =
'Check if the variable or function name is spelled correctly and has been declared.';
} else if (error.message.includes('Cannot read property')) {
errorContext.suggestion = 'Check if the object exists before accessing its properties.';
}
return errorContext;
},
// Prune disposed entries and auto-recycle the oldest live instance
// when the per-key cap is hit. Used by all mesh creation paths.
// Only active when flock.meshRecyclingEnabled is true.
_recycleOldestByKey(key) {
if (!flock.meshRecyclingEnabled) return;
if (!flock._modelInstances) flock._modelInstances = Object.create(null);
const current = Array.isArray(flock._modelInstances[key]) ? flock._modelInstances[key] : [];
flock._modelInstances[key] = current.filter((name) => {
const m = flock.scene?.getMeshByName(name);
return m && !m.isDisposed();
});
const max = flock.maxClonesPerSource ?? 500;
if (flock._modelInstances[key].length >= max) {
const oldestName = flock._modelInstances[key][0];
const oldest = flock.scene?.getMeshByName(oldestName);
if (oldest) flock.disposeMesh(oldest);
flock._modelInstances[key] = flock._modelInstances[key].slice(1);
}
},
_registerInstance(key, meshName) {
if (!flock._modelInstances) flock._modelInstances = Object.create(null);
const current = Array.isArray(flock._modelInstances[key]) ? flock._modelInstances[key] : [];
flock._modelInstances[key] = current.concat(meshName);
},
maxMeshesReached() {
if (!flock.meshLimitEnabled) return false;
const scene = flock?.scene;
if (!scene || typeof flock.maxMeshes !== 'number') return false;
const meshCount = scene.meshes.length;
const max = flock.maxMeshes;
if (meshCount >= max) {
flock.printText?.({
text: translate('max_mesh_limit_reached').replace('{max}', max),
duration: 30,
color: '#ff0000',
});
return true;
}
return false;
},
_resetCameraInputState(camera = flock.scene?.activeCamera) {
if (!camera) return;
// ArcRotateCamera inertial offsets can keep rotating after input ends.
if ('inertialAlphaOffset' in camera) camera.inertialAlphaOffset = 0;
if ('inertialBetaOffset' in camera) camera.inertialBetaOffset = 0;
if ('inertialRadiusOffset' in camera) camera.inertialRadiusOffset = 0;
if ('inertialPanningX' in camera) camera.inertialPanningX = 0;
if ('inertialPanningY' in camera) camera.inertialPanningY = 0;
// Free/Universal camera deltas can persist when pointer state desyncs.
if (camera.cameraDirection?.set) {
camera.cameraDirection.set(0, 0, 0);
}
if (camera.cameraRotation?.set) {
camera.cameraRotation.set(0, 0);
} else if (camera.cameraRotation) {
camera.cameraRotation.x = 0;
camera.cameraRotation.y = 0;
}
},
_hardResetCameraControls(
camera = flock.scene?.activeCamera,
{ reattachDelayMs = 0, noPreventDefault = true } = {}
) {
if (!camera || !flock.canvas) return;
if (typeof camera.detachControl !== 'function') return;
if (typeof camera.attachControl !== 'function') return;
camera.detachControl(flock.canvas);
flock._resetCameraInputState(camera);
if (flock._cameraControlReattachTimer) {
clearTimeout(flock._cameraControlReattachTimer);
flock._cameraControlReattachTimer = null;
}
const reattach = () => {
if (!flock.scene || flock.scene.activeCamera !== camera) return;
if (flock._canvasControlsEnabled === false) return;
flock._resetCameraInputState(camera);
camera.attachControl(flock.canvas, noPreventDefault);
flock._cameraControlReattachTimer = null;
};
if (reattachDelayMs > 0) {
flock._cameraControlReattachTimer = setTimeout(reattach, reattachDelayMs);
return;
}
reattach();
},
getTotalSceneVertices() {
return flock.scene.meshes.reduce((total, mesh) => {
return total + mesh.getTotalVertices();
}, 0);
},
checkMemoryUsage() {
if (!performance.memory) {
return; // Not available in all browsers
}
const used = performance.memory.usedJSHeapSize / 1024 / 1024;
const total = performance.memory.totalJSHeapSize / 1024 / 1024;
const limit = performance.memory.jsHeapSizeLimit / 1024 / 1024;
console.log(
`Memory: ${used.toFixed(1)}MB used / ${total.toFixed(1)}MB allocated / ${limit.toFixed(1)}MB limit`
);
// Warn if approaching limits
const usagePercent = (used / limit) * 100;
if (usagePercent > 80) {
console.warn(`High memory usage: ${usagePercent.toFixed(1)}% of limit`);
// Show user warning in UI
this.printText({
text: translate('high_memory_usage_warning').replace('{percent}', usagePercent.toFixed(1)),
duration: 3,
color: '#ff9900',
});
}
// Count Babylon.js objects for more specific monitoring
if (flock.scene) {
const counts = {
meshes: flock.scene.meshes.length,
geometries: Object.keys(flock.geometryCache).length,
vertices: flock.getTotalSceneVertices(),
materials: flock.scene.materials.length,
cachedMaterials: Object.keys(flock.materialCache).length,
textures: flock.scene.textures.length,
animationGroups: flock.scene.animationGroups.length,
};
console.log('Scene objects:', counts);
}
},
startMemoryMonitoring() {
console.log('Starting memory monitoring...');
// Clear any existing monitoring
if (flock.memoryMonitorInterval) {
clearInterval(flock.memoryMonitorInterval);
}
// Get the abort signal
const signal = flock.abortController?.signal;
if (signal?.aborted) {
return; // Don't start if already aborted
}
// Monitor every 5 seconds
flock.memoryMonitorInterval = setInterval(() => {
// Check if aborted before each check
if (signal?.aborted) {
clearInterval(flock.memoryMonitorInterval);
flock.memoryMonitorInterval = null;
return;
}
flock.checkMemoryUsage();
}, 5000);
// Clean up when aborted
signal?.addEventListener('abort', () => {
if (flock.memoryMonitorInterval) {
clearInterval(flock.memoryMonitorInterval);
flock.memoryMonitorInterval = null;
}
});
},
// Havok's wasm needs WebAssembly SIMD, which iOS Safari only has from 16.4.
// Older engines can't parse the v128 return type in this module's type
// section, so validate() is false there and true everywhere Havok can run.
isWasmSimdSupported() {
if (flock._wasmSimdSupported === undefined) {
try {
flock._wasmSimdSupported =
typeof WebAssembly !== 'undefined' &&
WebAssembly.validate(
new Uint8Array([
0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 10, 1, 8, 0, 65,
0, 253, 15, 253, 98, 11,
])
);
} catch {
// A throwing validate() means the engine can't handle the module at all.
flock._wasmSimdSupported = false;
}
}
return flock._wasmSimdSupported;
},
isPhysicsMemoryAbort(error) {
const message = `${error?.message ?? error}`.toLowerCase();
const isWasmRuntimeError =
typeof WebAssembly !== 'undefined' && error instanceof WebAssembly.RuntimeError;
// Emscripten wraps a wasm parse failure as "Aborted(CompileError: …)".
// That's a missing capability, not memory pressure.
if (message.includes('compileerror') || !flock.isWasmSimdSupported()) {
return false;
}
return message.includes('out of memory') || (isWasmRuntimeError && message.includes('abort'));
},
// Loader is injectable so tests can assert the wasm is never fetched when
// the device can't run it.
async ensurePhysicsInstance(loadHavok = HavokPhysics) {
if (!flock.isWasmSimdSupported()) {
const error = new Error('WebAssembly SIMD is unavailable, so Havok physics cannot start.');
handleError(error, { source: 'physics-unsupported' });
throw markReported(error);
}
// Callers that arrive together share one in-flight load, so a second
// caller can't start a duplicate wasm instance and leak the loser.
if (!flock.havokInstance) {
flock._havokInstancePromise ??= loadHavok();
try {
flock.havokInstance = await flock._havokInstancePromise;
} finally {
flock._havokInstancePromise = undefined;
}
}
return flock.havokInstance;
},
handlePhysicsOutOfMemory(error) {
if (flock.havokAbortHandled) {
return;
}
flock.havokAbortHandled = true;
try {
flock._renderLoopStopped = true;
if (flock._renderLoop) {
flock.engine?.stopRenderLoop(flock._renderLoop);
} else {
flock.engine?.stopRenderLoop();
}
flock.abortController?.abort();
} catch (e) {
console.log('Failed to stop render loop during physics OOM handling:', e);
}
try {
flock.hk?.dispose?.();
} catch (e) {
console.log('Failed to dispose Havok instance during physics OOM handling:', e);
}
handleError(error, { source: 'physics-oom', fatal: true });
},
validateCode(code) {
if (typeof code !== 'string') {
throw new Error('Code must be a string');
}
// Length check (reasonable)
if (code.length > 100000) {
throw new Error('Code too long (max 100KB)');
}
// Basic syntax check
try {
new Function(code); // Just check if it parses
} catch (e) {
throw new Error(`Syntax error: ${e.message}`);
}
// Optional: Warn about patterns (don't block)
const warnings = [];
if (/eval\s*\(/.test(code)) {
warnings.push("Warning: eval() detected - this won't work in the sandbox");
}
if (warnings.length > 0) {
console.warn(warnings.join('\n'));
}
return true;
},
validateUserCodeAST(src) {
// 1) Very broad identifier blocklist (names anywhere in user code)
const REJECT_IDENTIFIERS = new Set([
// dynamic code / reflection
'eval',
'Function',
'AsyncFunction',
'GeneratorFunction',
'Proxy',
'Reflect',
// frames & globals
'window',
'document',
'globalThis',
'self',
'parent',
'top',
'frames',
'frameElement',
// navigation & env
'location',
'history',
'navigator',
'opener',
// network / ipc
'fetch',
'XMLHttpRequest',
'WebSocket',
'EventSource',
'postMessage',
'MessageChannel',
'MessagePort',
'BroadcastChannel',
// workers & worklets
'Worker',
'SharedWorker',
'ServiceWorker',
'Worklet',
'importScripts',
// storage / persistence
'localStorage',
'sessionStorage',
'indexedDB',
'caches',
'cookieStore',
// file/blob/crypto
'Blob',
'File',
'FileReader',
'crypto',
// urls & media constructors
'URL',
'URLSearchParams',
'Image',
'Audio',
'RTCPeerConnection',
'MediaDevices',
'Notification',
// popups / UI
'open',
'alert',
'confirm',
'prompt',
'print',
'showModalDialog',
// timers (we’ll also do special checks)
'setTimeout',
'setInterval',
'setImmediate',
'queueMicrotask',
// module-ish
'require',
]);
// 2) Callees we never allow (even if shadowed)
const REJECT_CALLEES = new Set([
'eval',
'Function',
'AsyncFunction',
'GeneratorFunction',
'setTimeout',
'setInterval',
'setImmediate',
'queueMicrotask',
'open',
'alert',
'confirm',
'prompt',
'print',
]);
// 3) Member/property names that are escape hatches
const REJECT_PROPERTIES = new Set([
'constructor',
'__proto__',
'prototype',
'caller',
'callee',
'arguments',
]);
const ast = acorn.parse(src, {
ecmaVersion: 'latest',
sourceType: 'script',
allowAwaitOutsideFunction: true,
locations: false,
});
walk.simple(ast, {
// Syntax we never allow
WithStatement() {
throw new Error('with() not allowed');
},
DebuggerStatement() {
throw new Error('debugger not allowed');
},
ImportDeclaration() {
throw new Error('import declarations not allowed');
},
ExportNamedDeclaration() {
throw new Error('export not allowed');
},
ExportDefaultDeclaration() {
throw new Error('export not allowed');
},
ImportExpression() {
throw new Error('dynamic import() not allowed');
},
MetaProperty(n) {
if (n.meta?.name === 'import') throw new Error('import.meta not allowed');
},
// Any usage of these identifiers anywhere
Identifier(n) {
if (REJECT_IDENTIFIERS.has(n.name)) {
throw new Error(`Identifier '${n.name}' is not allowed`);
}
},
// Ban .constructor / .__proto__ / .prototype / .caller / .callee / .arguments
MemberExpression(n) {
// foo.bar
if (
!n.computed &&
n.property?.type === 'Identifier' &&
REJECT_PROPERTIES.has(n.property.name)
) {
throw new Error(`Access to '.${n.property.name}' is not allowed`);
}
// foo["constructor"]
if (
n.computed &&
n.property?.type === 'Literal' &&
typeof n.property.value === 'string' &&
REJECT_PROPERTIES.has(n.property.value)
) {
throw new Error(`Access to '["${n.property.value}"]' is not allowed`);
}
},
// Disallow dangerous callees; forbid string-eval timers
CallExpression(n) {
const callee = n.callee;
const name =
callee?.type === 'Identifier'
? callee.name
: callee?.type === 'MemberExpression' &&
!callee.computed &&
callee.property?.type === 'Identifier'
? callee.property.name
: null;
if (name && REJECT_CALLEES.has(name)) {
// Special case: timers with string as first arg (string-eval)
if (
(name === 'setTimeout' || name === 'setInterval') &&
n.arguments[0]?.type === 'Literal' &&
typeof n.arguments[0].value === 'string'
) {
throw new Error('String-eval timers are not allowed');
}
// Block all the listed callees regardless
throw new Error(`Call to '${name}()' is not allowed`);
}
},
// new Function(), new Worker(), etc.
NewExpression(n) {
const callee = n.callee;
const name = callee?.type === 'Identifier' ? callee.name : null;
if (name && (REJECT_CALLEES.has(name) || REJECT_IDENTIFIERS.has(name))) {
throw new Error(`'new ${name}()' is not allowed`);
}
},
});
},
async runCode(code, options = {}) {
const { focusCanvas = true } = options;
try {
flock.validateUserCodeAST(code);
await flock.disposeOldScene();
// --- remove any existing iframe ---
const oldIframe = document.getElementById('flock-iframe');
if (oldIframe) {
try {
await oldIframe.contentWindow?.flock?.disposeOldScene?.();
} catch {
/* ignore cleanup errors */
}
try {
oldIframe.onload = oldIframe.onerror = null;
} catch {
/* ignore cleanup errors */
}
try {
oldIframe.src = 'about:blank';
} catch {
/* ignore cleanup errors */
}
try {
oldIframe.remove();
} catch {
/* ignore cleanup errors */
}
}
// --- create fresh same-origin iframe ---
const { win, doc } = await flock.replaceSandboxIframe({
id: 'flock-iframe',
sameOrigin: true,
});
// --- load SES text in parent and inject inline into iframe (CSP allows inline) ---
const sesResp = await fetch('vendor/ses/lockdown.umd.min.js');
if (!sesResp.ok) throw new Error(`Failed to fetch SES: ${sesResp.status}`);
const sesText = await sesResp.text();
const sesScript = doc.createElement('script');
sesScript.type = 'text/javascript';
sesScript.text = sesText;
doc.head.appendChild(sesScript);
// Re-wraps a host-realm fn into this realm; lockdown only tames this
// realm, so a raw host fn would leak the untamed Function via
// `.constructor` (sandbox escape). Must run before lockdown.
const wrapScript = doc.createElement('script');
wrapScript.type = 'text/javascript';
wrapScript.text = 'window.__flockWrapHostFn = (fn) => (...args) => fn(...args);';
doc.head.appendChild(wrapScript);
// Lock down the iframe realm. Disable SES's own unhandled-rejection
// reporter (the SES_UNHANDLED_REJECTION console dump); the win backstop
// below handles those and routes them to the friendly warn path.
win.lockdown({ unhandledRejectionTrapping: 'none' });
// initialise scene
await this.initializeNewScene?.();
if (this.memoryDebug) this.startMemoryMonitoring?.();
// abort plumbing
this.__runToken = (this.__runToken || 0) + 1;
const runToken = this.__runToken;
this.abortController?.abort?.();
this.abortController = new AbortController();
const signal = this.abortController.signal;
const guard =
(fn) =>
(...args) => {
if (signal.aborted || runToken !== this.__runToken) return;
return fn(...args);
};
const whitelist = this.createWhitelist({
win,
signal,
guard,
});
// Create an endowments object in the iframe's realm
const endowments = new win.Object();
for (const [key, value] of Object.entries(whitelist)) {
const t = typeof value;
if (t === 'function') {
// Wrap into the iframe realm: a host-realm fn leaks the untamed host
// Function via `.constructor` (sandbox escape). bind(null) drops host `this`.
endowments[key] = win.__flockWrapHostFn(value.bind(null));
} else if (value == null || (t !== 'object' && t !== 'symbol')) {
// primitives only
endowments[key] = value;
} else {
// skip complex objects (meshes, DOM nodes, etc). Expose via functions instead.
}
}
// win.Object, not a host `{}`: a host literal leaks host Function via
// obj.constructor.constructor.
endowments.performance = new win.Object();
endowments.performance.now = win.performance.now.bind(win.performance);
// Host window, not the display:none iframe: Firefox never fires rAF for
// an unpainted document, so loop yields would hang. The host window
// outlives the iframe, so guard the callback (which iframe teardown used
// to cancel implicitly) or a stale run's frames fire into the next run.
// Wrapped so the endowment carries no host `.constructor`.
const hostRequestAnimationFrame = window.requestAnimationFrame.bind(window);
endowments.requestAnimationFrame = win.__flockWrapHostFn((callback) =>
hostRequestAnimationFrame(guard(callback))
);
endowments.Date = new win.Object();
endowments.Date.now = win.Date.now.bind(win.Date);
// Undefine unwanted globals
// --- shadow unsafe / unneeded globals ---
const toUndefine = [
// Host / DOM / cross-frame
'flock',
'window',
'self',
'globalThis',
'parent',
'top',
'frames',
'opener',
'frameElement',
'document',
// SES meta
'lockdown',
'harden',
'Compartment',
// Legacy / GC / crypto
'escape',
'unescape',
'FinalizationRegistry',
'WeakRef',
'crypto',
// Dynamic code creation
'eval',
'Function',
'AsyncFunction',
'GeneratorFunction',
'AsyncGeneratorFunction',
// Threads / native
'SharedArrayBuffer',
'Atomics',
'WebAssembly',
// Workers & messaging
'Worker',
'SharedWorker',
'MessageChannel',
'BroadcastChannel',
'queueMicrotask',
// Network / storage / env
'fetch',
'XMLHttpRequest',
'navigator',
'location',
'localStorage',
'sessionStorage',
'indexedDB',
'caches',
// UX
'Notification',
//Events
'addEventListener',
'removeEventListener',
'dispatchEvent',
];
for (const k of toUndefine) endowments[k] = undefined;
for (const key of toUndefine) {
endowments[key] = undefined;
}
Object.freeze(endowments);
const wrapped =
'(async function () {\n"use strict";\n' +
code +
'\n}).call(undefined)\n//# sourceURL=user-code.js';
// Compartment errors surface on `win` (the iframe realm), not the parent;
// preventDefault stops SES double-reporting.
win.addEventListener('unhandledrejection', (ev) => {
ev.preventDefault?.();
const error = flock.sanitizeError(ev.reason);
if (error.name === 'AbortError') return;
flock.reportBlockError({ key: 'unhandled_rejection', api: 'user-code', error });
});
win.addEventListener('error', (ev) => {
ev.preventDefault?.();
const error = flock.sanitizeError(ev.error ?? ev.message);
if (error.name === 'AbortError') return;
flock.reportBlockError({ key: 'uncaught_error', api: 'user-code', error });
});
// Evaluate in SES Compartment
const c = new win.Compartment(endowments);
const MAX_MS = 5000;
const hostSetTimeout = window.setTimeout.bind(window);
await Promise.race([
c.evaluate(wrapped),