tempo-sdk 0.0.37 → 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.
@@ -945,7 +945,9 @@ function buildProjectionCapturePerf(input) {
945
945
  observedFileEntries: input.observedFileEntries ?? Object.keys(input.html?.declared.observedVersions ?? {}).length,
946
946
  batchesEmitted: 1,
947
947
  rootsPerBatch: input.rootsPerBatch,
948
- fullSnapshotReason: input.fullSnapshotReason
948
+ fullSnapshotReason: input.fullSnapshotReason,
949
+ ...input.triggerReasons === void 0 ? {} : { triggerReasons: input.triggerReasons },
950
+ ...input.sourceViewportSamples === void 0 ? {} : { sourceViewportSamples: input.sourceViewportSamples }
949
951
  };
950
952
  }
951
953
 
@@ -3931,6 +3933,7 @@ function createProjectionOutbox(options) {
3931
3933
  const full = /* @__PURE__ */ new Set();
3932
3934
  let dirtyHead = false;
3933
3935
  const dirtyHeadRoots = /* @__PURE__ */ new Set();
3936
+ const triggerReasons = /* @__PURE__ */ new Set();
3934
3937
  let sessionId;
3935
3938
  let sequence = 0;
3936
3939
  let stopped = false;
@@ -3945,7 +3948,7 @@ function createProjectionOutbox(options) {
3945
3948
  const assertActive = () => {
3946
3949
  if (stopped) throw new Error("Projection producer has been stopped");
3947
3950
  };
3948
- const restore = (failedSession, rootIds, includeHeadForAllRoots, headRootIds) => {
3951
+ const restore = (failedSession, rootIds, includeHeadForAllRoots, headRootIds, failedTriggers) => {
3949
3952
  if (stopped || sessionId !== failedSession) return;
3950
3953
  for (const rootId of rootIds) {
3951
3954
  if (!roots.has(rootId)) continue;
@@ -3958,6 +3961,8 @@ function createProjectionOutbox(options) {
3958
3961
  if (roots.has(rootId)) dirtyHeadRoots.add(rootId);
3959
3962
  }
3960
3963
  }
3964
+ for (const trigger of failedTriggers) triggerReasons.add(trigger);
3965
+ triggerReasons.add("retry-after-error");
3961
3966
  fixedWindow.schedule();
3962
3967
  };
3963
3968
  const flushOnce = (timing) => {
@@ -3968,16 +3973,19 @@ function createProjectionOutbox(options) {
3968
3973
  const includeHeadForAllRoots = dirtyHead;
3969
3974
  const headRootIds = includeHeadForAllRoots ? [] : [...dirtyHeadRoots];
3970
3975
  const includeHead = includeHeadForAllRoots || headRootIds.length > 0;
3976
+ const currentTriggers = [...triggerReasons];
3971
3977
  const context = {
3972
3978
  ...timing,
3973
3979
  candidateRootCount: rootIds.length,
3974
3980
  initialForSession: sequence === 0,
3975
- fullRequested: false
3981
+ fullRequested: false,
3982
+ triggerReasons: currentTriggers
3976
3983
  };
3977
3984
  dirty.clear();
3978
3985
  full.clear();
3979
3986
  dirtyHead = false;
3980
3987
  dirtyHeadRoots.clear();
3988
+ triggerReasons.clear();
3981
3989
  try {
3982
3990
  const changes = [];
3983
3991
  for (const rootId of rootIds) {
@@ -4012,7 +4020,8 @@ function createProjectionOutbox(options) {
4012
4020
  activeSession,
4013
4021
  rootIds,
4014
4022
  includeHeadForAllRoots,
4015
- headRootIds
4023
+ headRootIds,
4024
+ currentTriggers
4016
4025
  );
4017
4026
  }
4018
4027
  };
@@ -4032,7 +4041,9 @@ function createProjectionOutbox(options) {
4032
4041
  dirty.clear();
4033
4042
  full.clear();
4034
4043
  dirtyHeadRoots.clear();
4044
+ triggerReasons.clear();
4035
4045
  dirtyHead = true;
4046
+ triggerReasons.add("session-bind");
4036
4047
  sessionId = nextSessionId;
4037
4048
  sequence = 0;
4038
4049
  for (const rootId of roots.keys()) {
@@ -4049,6 +4060,7 @@ function createProjectionOutbox(options) {
4049
4060
  if (!sessionId) return;
4050
4061
  dirty.add(rootId);
4051
4062
  full.add(rootId);
4063
+ triggerReasons.add("root-added");
4052
4064
  if (!dirtyHead) dirtyHeadRoots.add(rootId);
4053
4065
  if (sequence === 0) fixedWindow.schedule();
4054
4066
  else fixedWindow.flushNow();
@@ -4058,7 +4070,10 @@ function createProjectionOutbox(options) {
4058
4070
  dirty.delete(rootId);
4059
4071
  full.delete(rootId);
4060
4072
  dirtyHeadRoots.delete(rootId);
4061
- if (!hasWork()) fixedWindow.cancel();
4073
+ if (!hasWork()) {
4074
+ fixedWindow.cancel();
4075
+ triggerReasons.clear();
4076
+ }
4062
4077
  },
4063
4078
  record(activity) {
4064
4079
  if (stopped || !sessionId) return;
@@ -4066,6 +4081,7 @@ function createProjectionOutbox(options) {
4066
4081
  for (const rootId of activity.rootIds ?? []) {
4067
4082
  if (roots.has(rootId)) dirty.add(rootId);
4068
4083
  }
4084
+ triggerReasons.add(activity.trigger ?? "dom-mutation");
4069
4085
  fixedWindow.schedule();
4070
4086
  },
4071
4087
  requestFull(rootId, options2) {
@@ -4073,6 +4089,7 @@ function createProjectionOutbox(options) {
4073
4089
  if (!sessionId || !roots.has(rootId)) return;
4074
4090
  dirty.add(rootId);
4075
4091
  full.add(rootId);
4092
+ triggerReasons.add(options2?.trigger ?? "receiver-baseline");
4076
4093
  if (options2?.includeHead && !dirtyHead) dirtyHeadRoots.add(rootId);
4077
4094
  fixedWindow.flushNow();
4078
4095
  },
@@ -4085,6 +4102,7 @@ function createProjectionOutbox(options) {
4085
4102
  full.clear();
4086
4103
  dirtyHeadRoots.clear();
4087
4104
  dirtyHead = false;
4105
+ triggerReasons.clear();
4088
4106
  sessionId = void 0;
4089
4107
  }
4090
4108
  };
@@ -4271,8 +4289,14 @@ var PortalTrackerImpl = class {
4271
4289
 
4272
4290
  // ../../modules/iframe-projection/combined/projection-root-accumulator.ts
4273
4291
  function createProjectionRootAccumulator(options) {
4274
- const dom = watchDom(options.root, options.onChange);
4275
- const state = watchState(options.root, options.onChange);
4292
+ const dom = watchDom(
4293
+ options.root,
4294
+ () => options.onChange("dom-mutation")
4295
+ );
4296
+ const state = watchState(
4297
+ options.root,
4298
+ () => options.onChange("state-event")
4299
+ );
4276
4300
  const portals = /* @__PURE__ */ new Map();
4277
4301
  const dirtyPortals = /* @__PURE__ */ new Set();
4278
4302
  const removedPortals = /* @__PURE__ */ new Map();
@@ -4298,7 +4322,7 @@ function createProjectionRootAccumulator(options) {
4298
4322
  const restyled = records.some((record) => record.type === "attributes");
4299
4323
  if (!reparented && !restyled) return;
4300
4324
  if (portals.size === 0) return;
4301
- options.onChange();
4325
+ options.onChange("portal-coordinate-change");
4302
4326
  });
4303
4327
  function observeAncestors(chain) {
4304
4328
  frameWatcher.disconnect();
@@ -4321,11 +4345,11 @@ function createProjectionRootAccumulator(options) {
4321
4345
  if (stopped || portals.has(portal)) return;
4322
4346
  const handle = watchPortal(portal, () => {
4323
4347
  dirtyPortals.add(portal);
4324
- options.onChange();
4348
+ options.onChange("portal-mutation");
4325
4349
  });
4326
4350
  portals.set(portal, handle);
4327
4351
  dirtyPortals.add(portal);
4328
- options.onChange();
4352
+ options.onChange("portal-mutation");
4329
4353
  },
4330
4354
  onPortalRemoved(portal) {
4331
4355
  const handle = portals.get(portal);
@@ -4338,7 +4362,7 @@ function createProjectionRootAccumulator(options) {
4338
4362
  portals.delete(portal);
4339
4363
  sentPortalCoordinates.delete(portal);
4340
4364
  handle.stop();
4341
- options.onChange();
4365
+ options.onChange("portal-mutation");
4342
4366
  }
4343
4367
  });
4344
4368
  return {
@@ -4485,8 +4509,31 @@ function createCombinedDocumentProducer(options) {
4485
4509
  let rootLifecycleObserver = null;
4486
4510
  let headPerfContext = null;
4487
4511
  let headSnapshotMs = 0;
4512
+ const sourceWindow = options.document.defaultView;
4513
+ const pendingSourceViewportSamples = [];
4514
+ function recordSourceViewport() {
4515
+ if (!sourceWindow) return;
4516
+ const sample = {
4517
+ at: Date.now(),
4518
+ width: sourceWindow.innerWidth,
4519
+ height: sourceWindow.innerHeight,
4520
+ devicePixelRatio: sourceWindow.devicePixelRatio
4521
+ };
4522
+ const previous = pendingSourceViewportSamples.at(-1);
4523
+ if (previous?.width === sample.width && previous.height === sample.height && previous.devicePixelRatio === sample.devicePixelRatio) {
4524
+ return;
4525
+ }
4526
+ if (pendingSourceViewportSamples.length < 16) {
4527
+ pendingSourceViewportSamples.push(sample);
4528
+ } else {
4529
+ pendingSourceViewportSamples[15] = sample;
4530
+ }
4531
+ }
4532
+ recordSourceViewport();
4488
4533
  const core = createProjectionOutbox({
4489
4534
  emit(batch) {
4535
+ recordSourceViewport();
4536
+ const sourceViewportSamples = pendingSourceViewportSamples.splice(0);
4490
4537
  const rootPerf = batch.roots.flatMap((change) => {
4491
4538
  const payload = change.kind === "full" ? change.snapshot : change.kind === "patch" ? change.patch : change.problem;
4492
4539
  return typeof payload === "object" && payload !== null ? [captureStats.get(payload)?.perf].filter(
@@ -4498,7 +4545,8 @@ function createCombinedDocumentProducer(options) {
4498
4545
  batch.head,
4499
4546
  headPerfContext,
4500
4547
  headSnapshotMs,
4501
- batch.roots.length
4548
+ batch.roots.length,
4549
+ sourceViewportSamples
4502
4550
  );
4503
4551
  headPerfContext = null;
4504
4552
  headSnapshotMs = 0;
@@ -4730,6 +4778,7 @@ function createCombinedDocumentProducer(options) {
4730
4778
  function recordReactCommit(commit) {
4731
4779
  if (stopped) return;
4732
4780
  const affectedRootIds = [];
4781
+ let retainedDomRecords = false;
4733
4782
  for (const [rootId, runtime] of roots) {
4734
4783
  if (runtime.dormant) continue;
4735
4784
  const current = runtime.layerAdapter.resolveCommittedRoot(
@@ -4748,19 +4797,24 @@ function createCombinedDocumentProducer(options) {
4748
4797
  runtime.committedFiber,
4749
4798
  current
4750
4799
  );
4751
- runtime.accumulator?.takePendingDomRecords();
4800
+ retainedDomRecords = (runtime.accumulator?.takePendingDomRecords() ?? 0) > 0 || retainedDomRecords;
4752
4801
  }
4753
4802
  runtime.committedFiber = current;
4754
4803
  affectedRootIds.push(rootId);
4755
4804
  }
4756
- if (affectedRootIds.length > 0) core.record({ rootIds: affectedRootIds });
4805
+ if (affectedRootIds.length > 0) {
4806
+ core.record({ rootIds: affectedRootIds, trigger: "react-commit" });
4807
+ if (retainedDomRecords) {
4808
+ core.record({ rootIds: affectedRootIds, trigger: "dom-mutation" });
4809
+ }
4810
+ }
4757
4811
  }
4758
4812
  function startRootObserver(rootId, runtime) {
4759
4813
  const unregisterRootObserver = registerCaptureRootObserver();
4760
4814
  try {
4761
4815
  const accumulator = createProjectionRootAccumulator({
4762
4816
  root: runtime.options.element,
4763
- onChange() {
4817
+ onChange(trigger) {
4764
4818
  if (!runtime.options.element.isConnected) {
4765
4819
  makeRootDormant(runtime);
4766
4820
  return;
@@ -4771,16 +4825,16 @@ function createCombinedDocumentProducer(options) {
4771
4825
  if (renderError) {
4772
4826
  if (runtime.renderError === null) {
4773
4827
  runtime.renderError = renderError;
4774
- core.requestFull(rootId);
4828
+ core.requestFull(rootId, { trigger: "render-problem" });
4775
4829
  }
4776
4830
  return;
4777
4831
  }
4778
4832
  if (runtime.renderError !== null) {
4779
4833
  runtime.renderError = null;
4780
- core.requestFull(rootId);
4834
+ core.requestFull(rootId, { trigger: "render-recovery" });
4781
4835
  return;
4782
4836
  }
4783
- core.record({ rootIds: [rootId] });
4837
+ core.record({ rootIds: [rootId], trigger });
4784
4838
  }
4785
4839
  });
4786
4840
  runtime.accumulator = accumulator;
@@ -4846,7 +4900,7 @@ function createCombinedDocumentProducer(options) {
4846
4900
  roots.set(rootId, previous);
4847
4901
  throw error;
4848
4902
  }
4849
- core.requestFull(rootId);
4903
+ core.requestFull(rootId, { trigger: "selector-rebind" });
4850
4904
  return runtime;
4851
4905
  }
4852
4906
  function reconcileSelectorRoots() {
@@ -4907,6 +4961,7 @@ function createCombinedDocumentProducer(options) {
4907
4961
  };
4908
4962
  let stopHeadChanges = () => {
4909
4963
  };
4964
+ sourceWindow?.addEventListener("resize", recordSourceViewport);
4910
4965
  try {
4911
4966
  stopReactCommits = reactHook.onCommit(recordReactCommit);
4912
4967
  const headSubscription = getHeadTracker().subscribe(
@@ -4917,12 +4972,17 @@ function createCombinedDocumentProducer(options) {
4917
4972
  for (const [rootId, runtime] of roots) {
4918
4973
  if (runtime.accumulator?.hasPortals()) rootIds.push(rootId);
4919
4974
  }
4920
- core.record({ head: true, rootIds });
4975
+ core.record({
4976
+ head: true,
4977
+ rootIds,
4978
+ trigger: "head-mutation"
4979
+ });
4921
4980
  }
4922
4981
  );
4923
4982
  stopHeadChanges = () => headSubscription.unsubscribe();
4924
4983
  } catch (error) {
4925
4984
  runCleanup(stopReactCommits);
4985
+ sourceWindow?.removeEventListener("resize", recordSourceViewport);
4926
4986
  core.stop();
4927
4987
  throw error;
4928
4988
  }
@@ -4979,7 +5039,10 @@ function createCombinedDocumentProducer(options) {
4979
5039
  }));
4980
5040
  syncRootLifecycleObserver();
4981
5041
  },
4982
- requestFull: (rootId, requestOptions) => core.requestFull(rootId, requestOptions),
5042
+ requestFull: (rootId, requestOptions) => core.requestFull(rootId, {
5043
+ ...requestOptions,
5044
+ trigger: "receiver-baseline"
5045
+ }),
4983
5046
  captureSemanticSubtree(rootId, targetFiberId) {
4984
5047
  if (stopped) throw new Error("Projection producer has been stopped");
4985
5048
  const runtime = roots.get(rootId);
@@ -5021,6 +5084,7 @@ function createCombinedDocumentProducer(options) {
5021
5084
  rootLifecycleObserver = null;
5022
5085
  runCleanup(stopReactCommits);
5023
5086
  runCleanup(stopHeadChanges);
5087
+ sourceWindow?.removeEventListener("resize", recordSourceViewport);
5024
5088
  unregisterDocumentProducer();
5025
5089
  roots.clear();
5026
5090
  }
@@ -5267,6 +5331,7 @@ function makePerf(input) {
5267
5331
  semanticDiscoveryNodesVisited: input.semanticDiscoveryNodesVisited ?? 0,
5268
5332
  rootsPerBatch: input.flushContext.candidateRootCount,
5269
5333
  fullSnapshotReason: input.fullReason,
5334
+ triggerReasons: input.flushContext.triggerReasons,
5270
5335
  htmlChars: input.htmlChars,
5271
5336
  domNodesSerialized: input.domNodes,
5272
5337
  semanticNodesSerialized: input.semanticNodes,
@@ -5276,7 +5341,7 @@ function makePerf(input) {
5276
5341
  observedFileEntries: input.observedFiles
5277
5342
  });
5278
5343
  }
5279
- function aggregateBatchPerf(roots, head, context, capturedHeadMs, rootsPerBatch) {
5344
+ function aggregateBatchPerf(roots, head, context, capturedHeadMs, rootsPerBatch, sourceViewportSamples) {
5280
5345
  if (roots.length === 0) {
5281
5346
  if (!context) return void 0;
5282
5347
  return buildProjectionCapturePerf({
@@ -5297,6 +5362,8 @@ function aggregateBatchPerf(roots, head, context, capturedHeadMs, rootsPerBatch)
5297
5362
  candidateTargetsAfterCoalescing: 0,
5298
5363
  rootsPerBatch: 0,
5299
5364
  fullSnapshotReason: null,
5365
+ triggerReasons: context.triggerReasons,
5366
+ sourceViewportSamples,
5300
5367
  domNodesSerialized: 0,
5301
5368
  semanticNodesSerialized: 0,
5302
5369
  annotationTargetsSerialized: 0,
@@ -5366,7 +5433,9 @@ function aggregateBatchPerf(roots, head, context, capturedHeadMs, rootsPerBatch)
5366
5433
  observedFileEntries: sum((perf) => perf.observedFileEntries),
5367
5434
  batchesEmitted: 1,
5368
5435
  rootsPerBatch,
5369
- fullSnapshotReason: reasons.size === 1 ? first.fullSnapshotReason : "mixed-full"
5436
+ fullSnapshotReason: reasons.size === 1 ? first.fullSnapshotReason : "mixed-full",
5437
+ triggerReasons: context?.triggerReasons ?? first.triggerReasons,
5438
+ sourceViewportSamples
5370
5439
  };
5371
5440
  }
5372
5441
 
@@ -6518,6 +6587,1000 @@ function initCombinedSourceInterface(targetOrigin, serialize, hideFiberProp) {
6518
6587
  };
6519
6588
  }
6520
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
+
6521
7584
  // canvas/interact-projection.ts
6522
7585
  var PENDING_ROOTS_KEY = "__tempoPendingFiberRoots";
6523
7586
  function installTempoInteractProjectionSource() {
@@ -6533,10 +7596,15 @@ function installTempoInteractProjectionSource() {
6533
7596
  pendingRoots.clear();
6534
7597
  delete hook[PENDING_ROOTS_KEY];
6535
7598
  }
6536
- return startCombinedSourceInterface();
7599
+ const disposeCanvasFrames = installTempoInteractCanvasFrameLane();
7600
+ const disposeProjection = startCombinedSourceInterface();
7601
+ return () => {
7602
+ disposeProjection();
7603
+ disposeCanvasFrames();
7604
+ };
6537
7605
  }
6538
7606
 
6539
7607
  export {
6540
7608
  installTempoInteractProjectionSource
6541
7609
  };
6542
- //# sourceMappingURL=chunk-3CR4SX5W.js.map
7610
+ //# sourceMappingURL=chunk-ED5VHXXD.js.map