tempo-sdk 0.0.38 → 0.0.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6587,6 +6587,1000 @@ function initCombinedSourceInterface(targetOrigin, serialize, hideFiberProp) {
6587
6587
  };
6588
6588
  }
6589
6589
 
6590
+ // ../../modules/iframe-projection/canvas-frames/demand.ts
6591
+ var DEFAULT_CANVAS_FRAME_MAX_IN_FLIGHT = 2;
6592
+ var DEFAULT_CANVAS_ACTIVITY_WINDOW_MS = 2e3;
6593
+ var DISABLED_CANVAS_FRAME_DEMAND = Object.freeze({
6594
+ enabled: false,
6595
+ width: 0,
6596
+ height: 0,
6597
+ maxFps: 0
6598
+ });
6599
+
6600
+ // ../../modules/iframe-projection/canvas-frames/demand-planner.ts
6601
+ var LOW_FPS_AREA = 96 * 96;
6602
+
6603
+ // ../../modules/iframe-projection/canvas-frames/draw-tracker.ts
6604
+ var WeakReferenceCtor = globalThis.WeakRef;
6605
+ var INNER = /* @__PURE__ */ Symbol.for("iframe-projection.canvas-frames.draw-tracker.inner");
6606
+ var METHODS_2D = [
6607
+ "clearRect",
6608
+ "fillRect",
6609
+ "strokeRect",
6610
+ "fill",
6611
+ "stroke",
6612
+ "fillText",
6613
+ "strokeText",
6614
+ "drawImage",
6615
+ "putImageData",
6616
+ "reset",
6617
+ "drawFocusIfNeeded"
6618
+ ];
6619
+ var METHODS_GL = [
6620
+ "clear",
6621
+ "drawArrays",
6622
+ "drawElements",
6623
+ "drawArraysInstanced",
6624
+ "drawElementsInstanced",
6625
+ "drawRangeElements",
6626
+ "blitFramebuffer",
6627
+ "clearBufferfv",
6628
+ "clearBufferiv",
6629
+ "clearBufferuiv",
6630
+ "clearBufferfi"
6631
+ ];
6632
+ var GL_EXTENSION_DRAW_METHOD = /^(multiDraw|drawArrays|drawElements)/;
6633
+ var GPU_QUEUE_WRITE_METHODS = [
6634
+ "submit",
6635
+ "writeTexture",
6636
+ "copyExternalImageToTexture"
6637
+ ];
6638
+ function prototypeOf(scope, constructorName) {
6639
+ const ctor = scope[constructorName];
6640
+ if (typeof ctor !== "function") return null;
6641
+ const prototype = ctor.prototype;
6642
+ return typeof prototype === "object" && prototype !== null ? prototype : null;
6643
+ }
6644
+ function canvasOf(context) {
6645
+ const canvas = context?.canvas;
6646
+ return typeof canvas === "object" && canvas !== null ? canvas : null;
6647
+ }
6648
+ function unlink(current, wrapper) {
6649
+ if (current === wrapper) return wrapper[INNER];
6650
+ let outer = current;
6651
+ while (typeof outer === "function" && outer[INNER] !== wrapper) {
6652
+ outer = outer[INNER];
6653
+ }
6654
+ if (typeof outer === "function") outer[INNER] = wrapper[INNER];
6655
+ return current;
6656
+ }
6657
+ function installDrawTracker(scope = globalThis) {
6658
+ const states = /* @__PURE__ */ new WeakMap();
6659
+ const untracked = /* @__PURE__ */ new WeakSet();
6660
+ const restores = [];
6661
+ const wrapped = /* @__PURE__ */ new WeakMap();
6662
+ let patchedCount = 0;
6663
+ const stateOf = (canvas) => {
6664
+ let state = states.get(canvas);
6665
+ if (!state) {
6666
+ state = { revision: 0, dirty: false, listeners: null };
6667
+ states.set(canvas, state);
6668
+ }
6669
+ return state;
6670
+ };
6671
+ const notify = (state) => {
6672
+ if (!state.listeners) return;
6673
+ for (const listener of state.listeners) listener();
6674
+ };
6675
+ const mark = (canvas) => {
6676
+ if (!canvas) return;
6677
+ const state = stateOf(canvas);
6678
+ if (state.dirty) return;
6679
+ state.dirty = true;
6680
+ state.revision += 1;
6681
+ notify(state);
6682
+ };
6683
+ const alreadyWrapped = (owner, name) => {
6684
+ const names = wrapped.get(owner) ?? /* @__PURE__ */ new Set();
6685
+ if (names.has(name)) return true;
6686
+ names.add(name);
6687
+ wrapped.set(owner, names);
6688
+ return false;
6689
+ };
6690
+ const wrap = (owner, name, key, after) => {
6691
+ if (!owner || alreadyWrapped(owner, name)) return;
6692
+ const descriptor = Object.getOwnPropertyDescriptor(owner, name);
6693
+ const original = descriptor?.[key];
6694
+ if (typeof original !== "function") return;
6695
+ const wrapper = function(...args) {
6696
+ const result = Reflect.apply(
6697
+ wrapper[INNER] ?? original,
6698
+ this,
6699
+ args
6700
+ );
6701
+ after(this, args, result);
6702
+ return result;
6703
+ };
6704
+ wrapper[INNER] = original;
6705
+ Object.defineProperty(owner, name, { ...descriptor, [key]: wrapper });
6706
+ patchedCount += 1;
6707
+ restores.push(() => {
6708
+ const current = Object.getOwnPropertyDescriptor(owner, name)?.[key];
6709
+ const head = unlink(current, wrapper);
6710
+ if (head !== current) {
6711
+ Object.defineProperty(owner, name, { ...descriptor, [key]: head });
6712
+ }
6713
+ });
6714
+ };
6715
+ const markContextCanvas = (context) => mark(canvasOf(context));
6716
+ const markSelf = (self) => mark(self);
6717
+ for (const type of [
6718
+ "CanvasRenderingContext2D",
6719
+ "OffscreenCanvasRenderingContext2D"
6720
+ ]) {
6721
+ const prototype = prototypeOf(scope, type);
6722
+ for (const name of METHODS_2D) {
6723
+ wrap(prototype, name, "value", markContextCanvas);
6724
+ }
6725
+ }
6726
+ wrap(
6727
+ prototypeOf(scope, "ImageBitmapRenderingContext"),
6728
+ "transferFromImageBitmap",
6729
+ "value",
6730
+ markContextCanvas
6731
+ );
6732
+ const extensionCanvas = /* @__PURE__ */ new WeakMap();
6733
+ const markExtensionCanvas = (extension) => {
6734
+ if (typeof extension !== "object" || extension === null) return;
6735
+ mark(extensionCanvas.get(extension) ?? null);
6736
+ };
6737
+ for (const type of ["WebGLRenderingContext", "WebGL2RenderingContext"]) {
6738
+ const prototype = prototypeOf(scope, type);
6739
+ for (const name of METHODS_GL) {
6740
+ wrap(prototype, name, "value", markContextCanvas);
6741
+ }
6742
+ wrap(prototype, "getExtension", "value", (context, _args, extension) => {
6743
+ if (typeof extension !== "object" || extension === null) return;
6744
+ const canvas = canvasOf(context);
6745
+ if (canvas) extensionCanvas.set(extension, canvas);
6746
+ for (const owner of [extension, Object.getPrototypeOf(extension)]) {
6747
+ if (!owner) continue;
6748
+ for (const name of Object.getOwnPropertyNames(owner)) {
6749
+ if (GL_EXTENSION_DRAW_METHOD.test(name)) {
6750
+ wrap(owner, name, "value", markExtensionCanvas);
6751
+ }
6752
+ }
6753
+ }
6754
+ });
6755
+ }
6756
+ const gpuContexts = /* @__PURE__ */ new WeakMap();
6757
+ for (const type of ["HTMLCanvasElement", "OffscreenCanvas"]) {
6758
+ const prototype = prototypeOf(scope, type);
6759
+ wrap(prototype, "width", "set", markSelf);
6760
+ wrap(prototype, "height", "set", markSelf);
6761
+ wrap(prototype, "getContext", "value", (canvas, args, context) => {
6762
+ if (args[0] !== "webgpu" || typeof context !== "object" || !context) {
6763
+ return;
6764
+ }
6765
+ if (gpuContexts.has(context)) return;
6766
+ gpuContexts.set(context, {
6767
+ canvas,
6768
+ queue: null,
6769
+ reference: null
6770
+ });
6771
+ });
6772
+ }
6773
+ wrap(
6774
+ prototypeOf(scope, "HTMLCanvasElement"),
6775
+ "transferControlToOffscreen",
6776
+ "value",
6777
+ (canvas) => {
6778
+ untracked.add(canvas);
6779
+ const state = stateOf(canvas);
6780
+ if (state.dirty) notify(state);
6781
+ else mark(canvas);
6782
+ }
6783
+ );
6784
+ const observer = typeof scope.MutationObserver === "function" && scope.document ? new scope.MutationObserver((records) => {
6785
+ for (const record of records) {
6786
+ const target = record.target;
6787
+ if (target.localName === "canvas") mark(target);
6788
+ }
6789
+ }) : null;
6790
+ observer?.observe(scope.document, {
6791
+ subtree: true,
6792
+ attributes: true,
6793
+ attributeFilter: ["width", "height"]
6794
+ });
6795
+ const queueCanvases = /* @__PURE__ */ new WeakMap();
6796
+ const detachFromQueue = (state) => {
6797
+ if (state.queue && state.reference) {
6798
+ queueCanvases.get(state.queue)?.delete(state.reference);
6799
+ }
6800
+ state.queue = null;
6801
+ state.reference = null;
6802
+ };
6803
+ const gpuContextPrototype = prototypeOf(scope, "GPUCanvasContext");
6804
+ wrap(gpuContextPrototype, "configure", "value", (context, args) => {
6805
+ const state = gpuContexts.get(context);
6806
+ if (!state) return;
6807
+ detachFromQueue(state);
6808
+ const queue = args[0]?.device?.queue;
6809
+ if (queue) {
6810
+ const canvases = queueCanvases.get(queue) ?? /* @__PURE__ */ new Set();
6811
+ queueCanvases.set(queue, canvases);
6812
+ state.queue = queue;
6813
+ state.reference = new WeakReferenceCtor(state.canvas);
6814
+ canvases.add(state.reference);
6815
+ }
6816
+ mark(state.canvas);
6817
+ });
6818
+ wrap(gpuContextPrototype, "unconfigure", "value", (context) => {
6819
+ const state = gpuContexts.get(context);
6820
+ if (!state) return;
6821
+ detachFromQueue(state);
6822
+ mark(state.canvas);
6823
+ });
6824
+ const markQueueCanvases = (queue) => {
6825
+ const canvases = queueCanvases.get(queue);
6826
+ if (!canvases) return;
6827
+ for (const reference of canvases) {
6828
+ const canvas = reference.deref();
6829
+ if (canvas) mark(canvas);
6830
+ else canvases.delete(reference);
6831
+ }
6832
+ };
6833
+ for (const name of GPU_QUEUE_WRITE_METHODS) {
6834
+ wrap(prototypeOf(scope, "GPUQueue"), name, "value", markQueueCanvases);
6835
+ }
6836
+ return {
6837
+ patchedCount,
6838
+ revision: (canvas) => states.get(canvas)?.revision ?? 0,
6839
+ subscribe(canvas, listener) {
6840
+ const state = stateOf(canvas);
6841
+ state.listeners ?? (state.listeners = /* @__PURE__ */ new Set());
6842
+ state.listeners.add(listener);
6843
+ return () => {
6844
+ state.listeners?.delete(listener);
6845
+ };
6846
+ },
6847
+ captureStarted(canvas) {
6848
+ const state = stateOf(canvas);
6849
+ state.dirty = false;
6850
+ return state.revision;
6851
+ },
6852
+ isTracked: (canvas) => !untracked.has(canvas),
6853
+ dispose() {
6854
+ observer?.disconnect();
6855
+ for (const restore of restores) restore();
6856
+ restores.length = 0;
6857
+ }
6858
+ };
6859
+ }
6860
+
6861
+ // ../../modules/iframe-projection/canvas-frames/port-envelope.ts
6862
+ function definePortEnvelope(type) {
6863
+ const is = (value) => typeof value === "object" && value !== null && value.type === type;
6864
+ return {
6865
+ type,
6866
+ is,
6867
+ accept(event, trustedSource) {
6868
+ if (!is(event.data)) return null;
6869
+ const port = event.ports?.[0] ?? null;
6870
+ if (event.source !== trustedSource || !port) {
6871
+ port?.close();
6872
+ return null;
6873
+ }
6874
+ const fields = {
6875
+ ...event.data
6876
+ };
6877
+ delete fields.type;
6878
+ return { fields, port };
6879
+ },
6880
+ post(target, fields, port) {
6881
+ target.postMessage({ type, ...fields }, "*", [port]);
6882
+ }
6883
+ };
6884
+ }
6885
+ var CANVAS_FRAME_LANE_WINDOW_PORT = definePortEnvelope(
6886
+ "canvas-frames:window-port"
6887
+ );
6888
+
6889
+ // ../../modules/iframe-projection/canvas-frames/canvas-registry.ts
6890
+ function isCanvas(node) {
6891
+ return node.nodeType === 1 && node.localName === "canvas";
6892
+ }
6893
+ function collectCanvases(scope, into) {
6894
+ if (scope.nodeType !== 1) return;
6895
+ if (isCanvas(scope)) into.push(scope);
6896
+ for (const canvas of scope.querySelectorAll("canvas")) {
6897
+ into.push(canvas);
6898
+ }
6899
+ }
6900
+ function watchCanvasElements(root, callbacks) {
6901
+ const canvases = /* @__PURE__ */ new Set();
6902
+ let stopped = false;
6903
+ const add = (canvas) => {
6904
+ if (canvases.has(canvas) || !root.contains(canvas)) return;
6905
+ canvases.add(canvas);
6906
+ callbacks.onAdded(canvas);
6907
+ };
6908
+ const remove = (canvas) => {
6909
+ if (!canvases.delete(canvas)) return;
6910
+ callbacks.onRemoved(canvas);
6911
+ };
6912
+ const handleMutations = (records) => {
6913
+ if (stopped) return;
6914
+ const removedCandidates = [];
6915
+ const addedCandidates = [];
6916
+ for (const record of records) {
6917
+ for (const node of record.removedNodes) {
6918
+ collectCanvases(node, removedCandidates);
6919
+ }
6920
+ for (const node of record.addedNodes) {
6921
+ collectCanvases(node, addedCandidates);
6922
+ }
6923
+ }
6924
+ for (const canvas of removedCandidates) {
6925
+ if (!root.contains(canvas)) remove(canvas);
6926
+ }
6927
+ for (const canvas of addedCandidates) add(canvas);
6928
+ };
6929
+ const observer = new MutationObserver(handleMutations);
6930
+ observer.observe(root, { childList: true, subtree: true });
6931
+ const initial = [];
6932
+ collectCanvases(root, initial);
6933
+ for (const canvas of initial) add(canvas);
6934
+ return () => {
6935
+ if (stopped) return;
6936
+ stopped = true;
6937
+ observer.disconnect();
6938
+ };
6939
+ }
6940
+
6941
+ // ../../modules/iframe-projection/canvas-frames/direct-sampler.ts
6942
+ function resizeOptionsFor(source, size) {
6943
+ const width = Math.min(size.width, source.width);
6944
+ const height = Math.min(size.height, source.height);
6945
+ if (source.width === width && source.height === height) return {};
6946
+ return { resizeWidth: width, resizeHeight: height, resizeQuality: "low" };
6947
+ }
6948
+ var sampleCanvasDirect = (canvas, size) => {
6949
+ const scope = canvas.ownerDocument.defaultView ?? globalThis;
6950
+ return scope.createImageBitmap(canvas, resizeOptionsFor(canvas, size));
6951
+ };
6952
+ function classifyCanvasSampleError(error) {
6953
+ const name = error?.name;
6954
+ return name === "SecurityError" ? "tainted" : "unreadable";
6955
+ }
6956
+
6957
+ // ../../modules/iframe-projection/canvas-frames/capture-stream-sampler.ts
6958
+ var watchCanvasPaints = (canvas, callbacks) => {
6959
+ const scope = canvas.ownerDocument.defaultView ?? globalThis;
6960
+ const Processor = scope.MediaStreamTrackProcessor;
6961
+ if (typeof Processor !== "function" || typeof scope.createImageBitmap !== "function") {
6962
+ return null;
6963
+ }
6964
+ let stopped = false;
6965
+ let held = null;
6966
+ let stream = null;
6967
+ let reader = null;
6968
+ const run = async () => {
6969
+ if (stopped) return;
6970
+ let track;
6971
+ try {
6972
+ stream = canvas.captureStream();
6973
+ track = stream.getVideoTracks()[0];
6974
+ if (!track) {
6975
+ callbacks.onEnded("unreadable");
6976
+ return;
6977
+ }
6978
+ reader = new Processor({ track }).readable.getReader();
6979
+ while (!stopped) {
6980
+ const result = await reader.read();
6981
+ if (result.done) {
6982
+ if (!stopped) callbacks.onEnded("unreadable");
6983
+ return;
6984
+ }
6985
+ if (stopped) {
6986
+ result.value.close();
6987
+ return;
6988
+ }
6989
+ held?.close();
6990
+ held = result.value;
6991
+ callbacks.onPaint();
6992
+ }
6993
+ } catch (error) {
6994
+ if (!stopped) callbacks.onEnded(classifyCanvasSampleError(error));
6995
+ } finally {
6996
+ track?.stop();
6997
+ }
6998
+ };
6999
+ void Promise.resolve().then(run);
7000
+ return {
7001
+ async read(size) {
7002
+ const frame = held;
7003
+ held = null;
7004
+ if (!frame) return null;
7005
+ try {
7006
+ const source = {
7007
+ width: frame.displayWidth,
7008
+ height: frame.displayHeight
7009
+ };
7010
+ return await scope.createImageBitmap(
7011
+ frame,
7012
+ resizeOptionsFor(source, size)
7013
+ );
7014
+ } finally {
7015
+ frame.close();
7016
+ }
7017
+ },
7018
+ stop() {
7019
+ if (stopped) return;
7020
+ stopped = true;
7021
+ held?.close();
7022
+ held = null;
7023
+ void reader?.cancel().catch(() => {
7024
+ });
7025
+ for (const track of stream?.getTracks() ?? []) track.stop();
7026
+ }
7027
+ };
7028
+ };
7029
+
7030
+ // ../../modules/iframe-projection/canvas-frames/source.ts
7031
+ function createDefaultScheduler(view = globalThis) {
7032
+ const Channel = view.MessageChannel ?? MessageChannel;
7033
+ const channel = new Channel();
7034
+ const queued = [];
7035
+ channel.port1.onmessage = () => queued.shift()?.();
7036
+ return {
7037
+ now: () => performance.now(),
7038
+ setTimeout: (callback, ms) => view.setTimeout(callback, ms),
7039
+ clearTimeout: (handle) => view.clearTimeout(handle),
7040
+ post(callback) {
7041
+ queued.push(callback);
7042
+ channel.port2.postMessage(null);
7043
+ },
7044
+ close() {
7045
+ queued.length = 0;
7046
+ channel.port1.close();
7047
+ channel.port2.close();
7048
+ }
7049
+ };
7050
+ }
7051
+ var PAINT_RESTART_DELAY_MS = 1e3;
7052
+ function watchCanvasFrames(root, emitter, options = {}) {
7053
+ const own = options.scheduler ? null : createDefaultScheduler(
7054
+ root.ownerDocument.defaultView ?? globalThis
7055
+ );
7056
+ const scheduler = options.scheduler ?? own;
7057
+ const tracker = options.tracker ?? null;
7058
+ const sampleCanvas = options.sampleCanvas ?? sampleCanvasDirect;
7059
+ const watchPaints = options.watchPaints ?? watchCanvasPaints;
7060
+ const maxInFlight = options.maxInFlight ?? DEFAULT_CANVAS_FRAME_MAX_IN_FLIGHT;
7061
+ const activityWindowMs = options.activityWindowMs ?? DEFAULT_CANVAS_ACTIVITY_WINDOW_MS;
7062
+ const watched = /* @__PURE__ */ new Map();
7063
+ let demand = {};
7064
+ let stopped = false;
7065
+ const trackerOf = (entry) => tracker?.isTracked(entry.canvas) ? tracker : null;
7066
+ const revisionOf = (entry) => trackerOf(entry)?.revision(entry.canvas) ?? entry.paintRevision;
7067
+ const isServed = (entry) => entry.demand.enabled && !entry.removed && !entry.terminal && !entry.paintsExhausted;
7068
+ const isRunnable = (entry) => isServed(entry) && !entry.pending && entry.outstanding.size < maxInFlight && revisionOf(entry) !== entry.sampledRevision;
7069
+ let active = false;
7070
+ let lastDirtyAt = Number.NEGATIVE_INFINITY;
7071
+ let activityTimer = null;
7072
+ const rearmBlockedCanvases = () => {
7073
+ let drawnSinceRearm = false;
7074
+ for (const entry of watched.values()) {
7075
+ if (!isServed(entry)) continue;
7076
+ const seenBy = trackerOf(entry);
7077
+ if (!seenBy) continue;
7078
+ const revision = seenBy.revision(entry.canvas);
7079
+ if (revision === entry.sampledRevision) continue;
7080
+ if (revision !== entry.armedRevision) drawnSinceRearm = true;
7081
+ entry.armedRevision = revision;
7082
+ seenBy.captureStarted(entry.canvas);
7083
+ }
7084
+ return drawnSinceRearm;
7085
+ };
7086
+ const armActivityExpiry = (ms) => {
7087
+ activityTimer = scheduler.setTimeout(() => {
7088
+ activityTimer = null;
7089
+ const remaining = lastDirtyAt + activityWindowMs - scheduler.now();
7090
+ if (remaining > 0) {
7091
+ armActivityExpiry(remaining);
7092
+ return;
7093
+ }
7094
+ if (rearmBlockedCanvases()) {
7095
+ armActivityExpiry(activityWindowMs);
7096
+ return;
7097
+ }
7098
+ active = false;
7099
+ emitter.activity(false);
7100
+ }, ms);
7101
+ };
7102
+ const touchActivity = () => {
7103
+ lastDirtyAt = scheduler.now();
7104
+ if (!active) {
7105
+ active = true;
7106
+ emitter.activity(true);
7107
+ }
7108
+ if (activityTimer === null) armActivityExpiry(activityWindowMs);
7109
+ };
7110
+ const reportUnavailable = (entry, reason) => {
7111
+ if (reason !== "unreadable") entry.terminal = true;
7112
+ if (entry.unavailableReported) return;
7113
+ entry.unavailableReported = true;
7114
+ emitter.removed(entry.targetId, reason);
7115
+ };
7116
+ const stopPaints = (entry) => {
7117
+ entry.paints?.stop();
7118
+ entry.paints = null;
7119
+ if (entry.paintRestartTimer !== null) {
7120
+ scheduler.clearTimeout(entry.paintRestartTimer);
7121
+ entry.paintRestartTimer = null;
7122
+ }
7123
+ };
7124
+ const onPaintsEnded = (entry, reason) => {
7125
+ stopPaints(entry);
7126
+ if (entry.removed || stopped) return;
7127
+ reportUnavailable(entry, reason);
7128
+ if (entry.terminal) return;
7129
+ if (entry.paintRestarts > 0) {
7130
+ entry.paintsExhausted = true;
7131
+ return;
7132
+ }
7133
+ entry.paintRestarts += 1;
7134
+ entry.paintRestartTimer = scheduler.setTimeout(() => {
7135
+ entry.paintRestartTimer = null;
7136
+ syncPaints(entry);
7137
+ if (entry.paints) {
7138
+ entry.sampledRevision = -1;
7139
+ wake(entry);
7140
+ }
7141
+ }, PAINT_RESTART_DELAY_MS);
7142
+ };
7143
+ const startPaints = (entry) => {
7144
+ const watcher = watchPaints(entry.canvas, {
7145
+ onPaint: () => {
7146
+ if (entry.removed || stopped) return;
7147
+ entry.paintRevision += 1;
7148
+ onDirty(entry);
7149
+ },
7150
+ onEnded: (reason) => onPaintsEnded(entry, reason)
7151
+ });
7152
+ if (!watcher) {
7153
+ reportUnavailable(entry, "unsupported");
7154
+ return;
7155
+ }
7156
+ entry.paints = watcher;
7157
+ };
7158
+ const syncPaints = (entry) => {
7159
+ const wantsPaints = isServed(entry) && trackerOf(entry) === null;
7160
+ if (wantsPaints && !entry.paints) startPaints(entry);
7161
+ else if (!wantsPaints && entry.paints) stopPaints(entry);
7162
+ };
7163
+ let readPosted = false;
7164
+ let dueTimer = null;
7165
+ let dueTimerAt = Number.POSITIVE_INFINITY;
7166
+ const clearDueTimer = () => {
7167
+ if (dueTimer !== null) scheduler.clearTimeout(dueTimer);
7168
+ dueTimer = null;
7169
+ dueTimerAt = Number.POSITIVE_INFINITY;
7170
+ };
7171
+ const armDueTimer = (at, now) => {
7172
+ if (at === Number.POSITIVE_INFINITY) {
7173
+ clearDueTimer();
7174
+ return;
7175
+ }
7176
+ if (dueTimer !== null && dueTimerAt <= at) return;
7177
+ clearDueTimer();
7178
+ dueTimerAt = at;
7179
+ dueTimer = scheduler.setTimeout(() => {
7180
+ dueTimer = null;
7181
+ dueTimerAt = Number.POSITIVE_INFINITY;
7182
+ readDue();
7183
+ }, at - now);
7184
+ };
7185
+ const postRead = () => {
7186
+ if (readPosted) return;
7187
+ readPosted = true;
7188
+ scheduler.post(readDue);
7189
+ };
7190
+ const wake = (entry) => {
7191
+ if (stopped || !isRunnable(entry)) return;
7192
+ const now = scheduler.now();
7193
+ if (now >= entry.nextDueAt) postRead();
7194
+ else armDueTimer(entry.nextDueAt, now);
7195
+ };
7196
+ const schedule = () => {
7197
+ if (stopped) return;
7198
+ const now = scheduler.now();
7199
+ let earliest = Number.POSITIVE_INFINITY;
7200
+ let anyDue = false;
7201
+ for (const entry of watched.values()) {
7202
+ if (!isRunnable(entry)) continue;
7203
+ if (now >= entry.nextDueAt) anyDue = true;
7204
+ else earliest = Math.min(earliest, entry.nextDueAt);
7205
+ }
7206
+ if (anyDue) postRead();
7207
+ armDueTimer(earliest, now);
7208
+ };
7209
+ const readDue = () => {
7210
+ readPosted = false;
7211
+ if (stopped) return;
7212
+ const now = scheduler.now();
7213
+ for (const entry of watched.values()) {
7214
+ if (isRunnable(entry) && now >= entry.nextDueAt) beginRead(entry, now);
7215
+ }
7216
+ schedule();
7217
+ };
7218
+ const onDirty = (entry) => {
7219
+ if (!isServed(entry)) return;
7220
+ touchActivity();
7221
+ wake(entry);
7222
+ };
7223
+ const readEntry = async (entry, size) => {
7224
+ try {
7225
+ const paint = await entry.paints?.read(size);
7226
+ if (paint) return paint;
7227
+ } catch {
7228
+ return null;
7229
+ }
7230
+ return sampleCanvas(entry.canvas, size);
7231
+ };
7232
+ const beginRead = (entry, now) => {
7233
+ const interval = entry.demand.maxFps > 0 ? 1e3 / entry.demand.maxFps : 0;
7234
+ const dueAgain = entry.nextDueAt + interval;
7235
+ entry.nextDueAt = now < dueAgain + interval ? dueAgain : now + interval;
7236
+ entry.sampledRevision = trackerOf(entry)?.captureStarted(entry.canvas) ?? entry.paintRevision;
7237
+ const sourceWidth = entry.canvas.width;
7238
+ const sourceHeight = entry.canvas.height;
7239
+ const demandGeneration = entry.demandGeneration;
7240
+ if (sourceWidth <= 0 || sourceHeight <= 0) {
7241
+ emitter.removed(entry.targetId);
7242
+ return;
7243
+ }
7244
+ entry.pending = true;
7245
+ void readEntry(entry, {
7246
+ width: entry.demand.width,
7247
+ height: entry.demand.height
7248
+ }).then(
7249
+ (bitmap) => {
7250
+ entry.pending = false;
7251
+ if (bitmap) {
7252
+ if (demandGeneration !== entry.demandGeneration) {
7253
+ bitmap.close();
7254
+ } else {
7255
+ entry.unavailableReported = false;
7256
+ deliver(entry, bitmap, sourceWidth, sourceHeight);
7257
+ }
7258
+ }
7259
+ schedule();
7260
+ },
7261
+ (error) => {
7262
+ entry.pending = false;
7263
+ if (demandGeneration === entry.demandGeneration && !entry.removed && !stopped) {
7264
+ reportUnavailable(entry, classifyCanvasSampleError(error));
7265
+ }
7266
+ schedule();
7267
+ }
7268
+ );
7269
+ };
7270
+ const deliver = (entry, bitmap, sourceWidth, sourceHeight) => {
7271
+ if (stopped || !isServed(entry)) {
7272
+ bitmap.close();
7273
+ return;
7274
+ }
7275
+ entry.nextFrameId += 1;
7276
+ const frameId = entry.nextFrameId;
7277
+ entry.outstanding.add(frameId);
7278
+ const delivered = emitter.frame({
7279
+ targetId: entry.targetId,
7280
+ frameId,
7281
+ bitmap,
7282
+ sourceWidth,
7283
+ sourceHeight
7284
+ });
7285
+ if (!delivered) {
7286
+ bitmap.close();
7287
+ entry.outstanding.delete(frameId);
7288
+ }
7289
+ };
7290
+ const applyDemand = (entry, next) => {
7291
+ const previous = entry.demand;
7292
+ entry.demand = next;
7293
+ if (previous.enabled !== next.enabled) entry.demandGeneration += 1;
7294
+ const sizeChanged = previous.width !== next.width || previous.height !== next.height;
7295
+ if (next.enabled && (!previous.enabled || sizeChanged)) {
7296
+ entry.sampledRevision = -1;
7297
+ }
7298
+ if (next.enabled && !previous.enabled) {
7299
+ entry.paintRestarts = 0;
7300
+ entry.paintsExhausted = false;
7301
+ }
7302
+ syncPaints(entry);
7303
+ };
7304
+ const track = (canvas) => {
7305
+ const targetId = ensureProjectionDomId(canvas);
7306
+ if (!targetId) return;
7307
+ const entry = {
7308
+ canvas,
7309
+ targetId,
7310
+ demand: DISABLED_CANVAS_FRAME_DEMAND,
7311
+ sampledRevision: -1,
7312
+ pending: false,
7313
+ demandGeneration: 0,
7314
+ nextDueAt: 0,
7315
+ nextFrameId: 0,
7316
+ outstanding: /* @__PURE__ */ new Set(),
7317
+ tracked: tracker?.isTracked(canvas) ?? false,
7318
+ paints: null,
7319
+ paintRevision: 0,
7320
+ paintRestarts: 0,
7321
+ paintRestartTimer: null,
7322
+ paintsExhausted: false,
7323
+ unsubscribe: null,
7324
+ terminal: false,
7325
+ unavailableReported: false,
7326
+ removed: false,
7327
+ armedRevision: -1
7328
+ };
7329
+ watched.set(canvas, entry);
7330
+ entry.unsubscribe = tracker?.subscribe(canvas, () => {
7331
+ if (entry.tracked && trackerOf(entry) === null) {
7332
+ entry.tracked = false;
7333
+ entry.sampledRevision = -1;
7334
+ }
7335
+ syncPaints(entry);
7336
+ onDirty(entry);
7337
+ }) ?? null;
7338
+ applyDemand(entry, demand[targetId] ?? DISABLED_CANVAS_FRAME_DEMAND);
7339
+ wake(entry);
7340
+ };
7341
+ const untrack = (canvas, notify) => {
7342
+ const entry = watched.get(canvas);
7343
+ if (!entry) return;
7344
+ entry.removed = true;
7345
+ watched.delete(canvas);
7346
+ entry.unsubscribe?.();
7347
+ entry.unsubscribe = null;
7348
+ stopPaints(entry);
7349
+ if (notify) emitter.removed(entry.targetId);
7350
+ };
7351
+ const stopRegistry = watchCanvasElements(root, {
7352
+ onAdded: (canvas) => {
7353
+ if (!stopped) track(canvas);
7354
+ },
7355
+ onRemoved: (canvas) => untrack(canvas, true)
7356
+ });
7357
+ return {
7358
+ ack(targetId, frameId) {
7359
+ for (const entry of watched.values()) {
7360
+ if (entry.targetId !== targetId) continue;
7361
+ if (entry.outstanding.delete(frameId)) wake(entry);
7362
+ return;
7363
+ }
7364
+ },
7365
+ updateDemand(entries) {
7366
+ if (stopped) return;
7367
+ demand = entries;
7368
+ for (const entry of watched.values()) {
7369
+ applyDemand(
7370
+ entry,
7371
+ entries[entry.targetId] ?? DISABLED_CANVAS_FRAME_DEMAND
7372
+ );
7373
+ }
7374
+ schedule();
7375
+ },
7376
+ stop(stopOptions = {}) {
7377
+ if (stopped) return;
7378
+ stopped = true;
7379
+ stopRegistry();
7380
+ for (const entry of [...watched.values()]) {
7381
+ untrack(entry.canvas, stopOptions.notifyRemovals ?? false);
7382
+ }
7383
+ clearDueTimer();
7384
+ if (activityTimer !== null) scheduler.clearTimeout(activityTimer);
7385
+ activityTimer = null;
7386
+ if (active) {
7387
+ active = false;
7388
+ emitter.activity(false);
7389
+ }
7390
+ own?.close();
7391
+ }
7392
+ };
7393
+ }
7394
+
7395
+ // ../../modules/iframe-projection/canvas-frames/port-protocol.ts
7396
+ function isRecord3(value) {
7397
+ return typeof value === "object" && value !== null;
7398
+ }
7399
+ function isLaneCommand(value) {
7400
+ return isRecord3(value) && typeof value.kind === "string" && value.kind.startsWith("canvas-frames:");
7401
+ }
7402
+ var DEFAULT_ROOT_POLL_MS = 250;
7403
+ function serveCanvasFramesOverPort(port, options) {
7404
+ const { resolveRoot, rootPollMs, ...watchOptions } = options;
7405
+ const own = options.scheduler ? null : createDefaultScheduler();
7406
+ const scheduler = options.scheduler ?? own;
7407
+ const pollMs = rootPollMs ?? DEFAULT_ROOT_POLL_MS;
7408
+ let disposed = false;
7409
+ let rootId = null;
7410
+ let selector;
7411
+ let demand = {};
7412
+ let root = null;
7413
+ let watcher = null;
7414
+ let pollTimer = null;
7415
+ const send = (event, transfer) => {
7416
+ if (disposed) return false;
7417
+ try {
7418
+ port.postMessage(event, transfer);
7419
+ return true;
7420
+ } catch {
7421
+ return false;
7422
+ }
7423
+ };
7424
+ const startWatcher = (current) => {
7425
+ const started = watchCanvasFrames(
7426
+ current,
7427
+ {
7428
+ frame: ({ targetId, frameId, bitmap, sourceWidth, sourceHeight }) => send(
7429
+ {
7430
+ kind: "canvas-frames:frame",
7431
+ targetId,
7432
+ frameId,
7433
+ sourceWidth,
7434
+ sourceHeight,
7435
+ bitmap
7436
+ },
7437
+ [bitmap]
7438
+ ),
7439
+ removed: (targetId, reason) => void send({ kind: "canvas-frames:removed", targetId, reason }),
7440
+ activity: (active) => void send({ kind: "canvas-frames:activity", active })
7441
+ },
7442
+ { ...watchOptions, scheduler }
7443
+ );
7444
+ watcher = started;
7445
+ root = current;
7446
+ started.updateDemand(demand);
7447
+ };
7448
+ const stopLane = () => {
7449
+ watcher?.stop();
7450
+ watcher = null;
7451
+ root = null;
7452
+ rootId = null;
7453
+ if (pollTimer !== null) scheduler.clearTimeout(pollTimer);
7454
+ pollTimer = null;
7455
+ };
7456
+ const ensureRoot = () => {
7457
+ if (rootId === null || disposed) return;
7458
+ pollTimer = null;
7459
+ try {
7460
+ if (root && !root.isConnected) {
7461
+ watcher?.stop({ notifyRemovals: true });
7462
+ watcher = null;
7463
+ root = null;
7464
+ }
7465
+ if (!root) {
7466
+ const resolved = resolveRoot(rootId, selector);
7467
+ if (resolved) startWatcher(resolved);
7468
+ }
7469
+ } finally {
7470
+ pollTimer = scheduler.setTimeout(ensureRoot, pollMs);
7471
+ }
7472
+ };
7473
+ const handle = (command) => {
7474
+ switch (command.kind) {
7475
+ case "canvas-frames:start": {
7476
+ stopLane();
7477
+ rootId = command.rootId;
7478
+ selector = command.selector;
7479
+ demand = {};
7480
+ ensureRoot();
7481
+ return;
7482
+ }
7483
+ case "canvas-frames:demand": {
7484
+ if (rootId === null) return;
7485
+ demand = command.entries;
7486
+ watcher?.updateDemand(command.entries);
7487
+ return;
7488
+ }
7489
+ case "canvas-frames:ack":
7490
+ watcher?.ack(command.targetId, command.frameId);
7491
+ return;
7492
+ }
7493
+ };
7494
+ port.onmessage = (event) => {
7495
+ if (disposed) return;
7496
+ const command = event.data;
7497
+ if (!isLaneCommand(command)) return;
7498
+ try {
7499
+ handle(command);
7500
+ } catch (error) {
7501
+ console.warn("[canvas-frames] lane command failed", error);
7502
+ }
7503
+ };
7504
+ port.start?.();
7505
+ return () => {
7506
+ if (disposed) return;
7507
+ disposed = true;
7508
+ stopLane();
7509
+ own?.close();
7510
+ port.onmessage = null;
7511
+ try {
7512
+ port.close();
7513
+ } catch {
7514
+ }
7515
+ };
7516
+ }
7517
+ function serveCanvasFrameLanes(subscribePorts, options) {
7518
+ const lanes = /* @__PURE__ */ new Set();
7519
+ const unsubscribe = subscribePorts((port) => {
7520
+ const dispose = serveCanvasFramesOverPort(port, options);
7521
+ const disposeOnce = () => {
7522
+ if (!lanes.delete(disposeOnce)) return;
7523
+ dispose();
7524
+ };
7525
+ lanes.add(disposeOnce);
7526
+ port.addEventListener?.("close", disposeOnce, { once: true });
7527
+ });
7528
+ return () => {
7529
+ unsubscribe();
7530
+ for (const dispose of [...lanes]) dispose();
7531
+ };
7532
+ }
7533
+
7534
+ // ../../modules/iframe-projection/canvas-frames/preserve-drawing-buffer.ts
7535
+ var WEBGL_CONTEXT_IDS = /* @__PURE__ */ new Set(["webgl", "webgl2", "experimental-webgl"]);
7536
+ function installPreserveDrawingBuffer(scope = globalThis) {
7537
+ const prototype = scope.HTMLCanvasElement?.prototype;
7538
+ if (!prototype) return () => {
7539
+ };
7540
+ const original = prototype.getContext;
7541
+ if (typeof original !== "function") return () => {
7542
+ };
7543
+ const callOriginal = original;
7544
+ const patched = function(contextId, attributes, ...rest) {
7545
+ const forced = WEBGL_CONTEXT_IDS.has(contextId) ? {
7546
+ ...typeof attributes === "object" && attributes !== null ? attributes : {},
7547
+ preserveDrawingBuffer: true
7548
+ } : attributes;
7549
+ return callOriginal.call(this, contextId, forced, ...rest);
7550
+ };
7551
+ prototype.getContext = patched;
7552
+ return () => {
7553
+ if (prototype.getContext === patched) prototype.getContext = original;
7554
+ };
7555
+ }
7556
+
7557
+ // canvas/interact-canvas-frames.ts
7558
+ function installTempoInteractCanvasFrameLane() {
7559
+ const restoreDrawingBuffer = installPreserveDrawingBuffer(globalThis);
7560
+ const tracker = installDrawTracker(globalThis);
7561
+ const disposeLanes = serveCanvasFrameLanes(
7562
+ (deliver) => {
7563
+ const onMessage = (event) => {
7564
+ const hit = CANVAS_FRAME_LANE_WINDOW_PORT.accept(event, window.parent);
7565
+ if (hit) deliver(hit.port);
7566
+ };
7567
+ window.addEventListener("message", onMessage);
7568
+ return () => window.removeEventListener("message", onMessage);
7569
+ },
7570
+ {
7571
+ tracker,
7572
+ // The interact producer's projection root is the document body unless
7573
+ // the renderer named a capture selector, so the rootId is never used.
7574
+ resolveRoot: (_rootId, selector) => selector ? document.querySelector(selector) : document.body
7575
+ }
7576
+ );
7577
+ return () => {
7578
+ disposeLanes();
7579
+ tracker.dispose();
7580
+ restoreDrawingBuffer();
7581
+ };
7582
+ }
7583
+
6590
7584
  // canvas/interact-projection.ts
6591
7585
  var PENDING_ROOTS_KEY = "__tempoPendingFiberRoots";
6592
7586
  function installTempoInteractProjectionSource() {
@@ -6602,10 +7596,15 @@ function installTempoInteractProjectionSource() {
6602
7596
  pendingRoots.clear();
6603
7597
  delete hook[PENDING_ROOTS_KEY];
6604
7598
  }
6605
- return startCombinedSourceInterface();
7599
+ const disposeCanvasFrames = installTempoInteractCanvasFrameLane();
7600
+ const disposeProjection = startCombinedSourceInterface();
7601
+ return () => {
7602
+ disposeProjection();
7603
+ disposeCanvasFrames();
7604
+ };
6606
7605
  }
6607
7606
 
6608
7607
  export {
6609
7608
  installTempoInteractProjectionSource
6610
7609
  };
6611
- //# sourceMappingURL=chunk-FAO5QIJG.js.map
7610
+ //# sourceMappingURL=chunk-ED5VHXXD.js.map