@kehto/paja 0.27.1 → 0.28.1

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.
@@ -15514,8 +15514,7 @@ function hexToBytes2(hex) {
15514
15514
  }
15515
15515
  function createSendToNapplet(originRegistry2) {
15516
15516
  return (windowId, msg) => {
15517
- const win = originRegistry2.getIframeWindow(windowId);
15518
- if (win) win.postMessage(msg, "*");
15517
+ originRegistry2.postToNapplet(windowId, msg);
15519
15518
  };
15520
15519
  }
15521
15520
  function createRelayPoolAdapter(shellHooks, originRegistry2) {
@@ -15547,8 +15546,8 @@ function createRelayPoolAdapter(shellHooks, originRegistry2) {
15547
15546
  shellHooks.relayPool.untrackSubscription(subKey);
15548
15547
  },
15549
15548
  openScopedRelay(windowId, relayUrl2, subId, filters, _sendFn) {
15550
- const win = originRegistry2.getIframeWindow(windowId);
15551
- if (win) shellHooks.relayPool.openScopedRelay(windowId, relayUrl2, subId, filters, win);
15549
+ const target = originRegistry2.getNappletTarget(windowId);
15550
+ if (target) shellHooks.relayPool.openScopedRelay(windowId, relayUrl2, subId, filters, target);
15552
15551
  },
15553
15552
  closeScopedRelay(windowId) {
15554
15553
  shellHooks.relayPool.closeScopedRelay(windowId);
@@ -15813,7 +15812,21 @@ function adaptHooks(shellHooks, deps) {
15813
15812
  };
15814
15813
  }
15815
15814
  var registry = /* @__PURE__ */ new Map();
15815
+ var spentWindows = /* @__PURE__ */ new WeakSet();
15816
15816
  var nextRegistrationId = 0;
15817
+ function entryFor(windowId) {
15818
+ for (const entry of registry.values()) {
15819
+ if (entry.windowId === windowId) return entry;
15820
+ }
15821
+ return void 0;
15822
+ }
15823
+ function closePort(entry) {
15824
+ const port = entry.port;
15825
+ if (!port) return;
15826
+ entry.port = void 0;
15827
+ port.onmessage = null;
15828
+ port.close();
15829
+ }
15817
15830
  var originRegistry = {
15818
15831
  /**
15819
15832
  * Register a window reference with a windowId and optional identity metadata.
@@ -15821,10 +15834,17 @@ var originRegistry = {
15821
15834
  * @param win - The iframe's contentWindow reference
15822
15835
  * @param windowId - The unique identifier for this napplet window
15823
15836
  * @param identity - Optional NIP-5D identity metadata (dTag and aggregateHash)
15837
+ * @throws {Error} When `win` already bound a NIP-5D port. NIP-5D identity is
15838
+ * bound to one document; hosts must create a fresh iframe instead.
15824
15839
  */
15825
15840
  register(win, windowId, identity) {
15841
+ if (spentWindows.has(win)) {
15842
+ throw new Error("NIP-5D: cannot re-bind a napplet identity to an existing iframe; create a fresh iframe");
15843
+ }
15826
15844
  for (const [registeredWin, entry] of registry.entries()) {
15827
15845
  if (registeredWin === win || entry.windowId === windowId) {
15846
+ closePort(entry);
15847
+ if (registeredWin !== win) spentWindows.add(registeredWin);
15828
15848
  registry.delete(registeredWin);
15829
15849
  }
15830
15850
  }
@@ -15843,10 +15863,73 @@ var originRegistry = {
15843
15863
  unregister(windowId) {
15844
15864
  for (const [win, entry] of registry.entries()) {
15845
15865
  if (entry.windowId === windowId) {
15866
+ closePort(entry);
15867
+ spentWindows.add(win);
15846
15868
  registry.delete(win);
15847
15869
  }
15848
15870
  }
15849
15871
  },
15872
+ /**
15873
+ * Bind the NIP-5D port from a frame's single `napplet.hello`.
15874
+ *
15875
+ * @param windowId - The registered window identifier
15876
+ * @param port - The one port transferred with the hello
15877
+ * @returns `false` when the window is unknown or already bound
15878
+ */
15879
+ bindPort(windowId, port) {
15880
+ for (const [win, entry] of registry.entries()) {
15881
+ if (entry.windowId !== windowId) continue;
15882
+ if (entry.port || spentWindows.has(win)) return false;
15883
+ entry.port = port;
15884
+ spentWindows.add(win);
15885
+ return true;
15886
+ }
15887
+ return false;
15888
+ },
15889
+ /**
15890
+ * Look up the bound NIP-5D port for a window.
15891
+ *
15892
+ * @param windowId - The window identifier
15893
+ * @returns The bound port, or undefined before `napplet.hello`
15894
+ */
15895
+ getPort(windowId) {
15896
+ return entryFor(windowId)?.port;
15897
+ },
15898
+ /**
15899
+ * Send one NAP envelope to a napplet over its bound port. Never falls back
15900
+ * to `iframeWindow.postMessage`.
15901
+ *
15902
+ * @param windowId - The window identifier
15903
+ * @param message - The envelope to send
15904
+ * @returns `true` when a bound port carried the message
15905
+ */
15906
+ postToNapplet(windowId, message3) {
15907
+ const port = entryFor(windowId)?.port;
15908
+ if (!port) return false;
15909
+ port.postMessage(message3);
15910
+ return true;
15911
+ },
15912
+ /**
15913
+ * Return a port-backed outbound target for one napplet window.
15914
+ *
15915
+ * @param windowId - The window identifier
15916
+ * @returns A target that sends through {@link OriginRegistry.postToNapplet}, or null when unregistered
15917
+ */
15918
+ getNappletTarget(windowId) {
15919
+ if (!entryFor(windowId)) return null;
15920
+ return { postMessage: (message3) => {
15921
+ originRegistry.postToNapplet(windowId, message3);
15922
+ } };
15923
+ },
15924
+ /**
15925
+ * Whether a Window already handed over (or lost) its one NIP-5D binding.
15926
+ *
15927
+ * @param win - The iframe `contentWindow`
15928
+ * @returns `true` when the Window can never be registered again
15929
+ */
15930
+ isSpent(win) {
15931
+ return spentWindows.has(win);
15932
+ },
15850
15933
  /**
15851
15934
  * Look up the windowId for a given Window reference.
15852
15935
  *
@@ -15909,9 +15992,11 @@ var originRegistry = {
15909
15992
  getRegistrationId(win) {
15910
15993
  return registry.get(win)?.registrationId;
15911
15994
  },
15912
- /** Clear all registrations. */
15995
+ /** Clear all registrations and close every bound port. */
15913
15996
  clear() {
15997
+ for (const entry of registry.values()) closePort(entry);
15914
15998
  registry.clear();
15999
+ spentWindows = /* @__PURE__ */ new WeakSet();
15915
16000
  }
15916
16001
  };
15917
16002
  var byWindowId = /* @__PURE__ */ new Map();
@@ -16387,7 +16472,7 @@ var audioManager = {
16387
16472
  bump();
16388
16473
  },
16389
16474
  /**
16390
- * Mute or unmute an audio source and notify the napplet via postMessage.
16475
+ * Mute or unmute an audio source and notify the napplet over its bound NIP-5D port.
16391
16476
  *
16392
16477
  * @param windowId - The window identifier
16393
16478
  * @param muted - True to mute, false to unmute
@@ -16403,8 +16488,7 @@ var audioManager = {
16403
16488
  src.muted = muted;
16404
16489
  bump();
16405
16490
  }
16406
- const iframeWindow = originRegistry.getIframeWindow(windowId);
16407
- if (iframeWindow) {
16491
+ if (originRegistry.getPort(windowId)) {
16408
16492
  const muteEvent = {
16409
16493
  kind: 29e3,
16410
16494
  // INC_PEER — inlined numeric after Phase 24 DRIFT-01 shim removal
@@ -16415,7 +16499,7 @@ var audioManager = {
16415
16499
  id: `audio-mute-${windowId}-${Date.now()}`,
16416
16500
  sig: ""
16417
16501
  };
16418
- iframeWindow.postMessage(["EVENT", "__shell__", muteEvent], "*");
16502
+ originRegistry.postToNapplet(windowId, ["EVENT", "__shell__", muteEvent]);
16419
16503
  }
16420
16504
  },
16421
16505
  /**
@@ -16590,7 +16674,7 @@ function handleShellReady({
16590
16674
  }
16591
16675
  const environment = registerSourceSession({ hooks, origin, runtime, state, sourceRegistrationId, sourceWindow, windowId });
16592
16676
  if (!environment?.capabilities.domains.includes("shell")) return;
16593
- postShellInit(sourceWindow, environment);
16677
+ postShellInit(windowId, environment);
16594
16678
  state.initSent.set(sourceWindow, sourceRegistrationId);
16595
16679
  }
16596
16680
  function registerSourceSession(options) {
@@ -16657,14 +16741,15 @@ function resolveNip5dIdentity(hooks, windowId, sourceWindow, existingSession) {
16657
16741
  aggregateHash: originIdentity.aggregateHash
16658
16742
  });
16659
16743
  }
16660
- function postShellInit(win, environment) {
16744
+ function postShellInit(windowId, environment) {
16661
16745
  const initMsg = {
16662
16746
  type: "shell.init",
16663
16747
  capabilities: environment.capabilities,
16664
16748
  services: environment.services
16665
16749
  };
16666
- win.postMessage(initMsg, "*");
16750
+ originRegistry.postToNapplet(windowId, initMsg);
16667
16751
  }
16752
+ var NAPPLET_HELLO = "napplet.hello";
16668
16753
  function reportUnrouted(hooks, event, reason) {
16669
16754
  if (!hooks.onUnroutedMessage) return;
16670
16755
  const data = event.data;
@@ -16674,6 +16759,136 @@ function reportUnrouted(hooks, event, reason) {
16674
16759
  } catch {
16675
16760
  }
16676
16761
  }
16762
+ var REVOCATION_DETAIL = {
16763
+ "window-message": "A window-level message other than the single napplet.hello arrived from the frame",
16764
+ "second-hello": "A second napplet.hello arrived from the frame",
16765
+ "invalid-hello": "napplet.hello did not carry exactly one MessagePort",
16766
+ "second-load": "The frame loaded a second document (navigation or reload)",
16767
+ "port-closed": "The bound NIP-5D port closed or failed",
16768
+ host: "The host revoked the napplet binding"
16769
+ };
16770
+ function isHello(data) {
16771
+ return typeof data === "object" && data !== null && data.type === NAPPLET_HELLO;
16772
+ }
16773
+ function createNip5dTransport({ hooks, runtime, state: shellReadyState }) {
16774
+ const bindings = /* @__PURE__ */ new Map();
16775
+ function currentBinding(windowId) {
16776
+ const binding = bindings.get(windowId);
16777
+ if (binding && originRegistry.getPort(windowId) !== binding.port) {
16778
+ binding.port.onmessage = null;
16779
+ bindings.delete(windowId);
16780
+ return void 0;
16781
+ }
16782
+ return binding;
16783
+ }
16784
+ function revokeNapplet(windowId, reason = "host") {
16785
+ const binding = currentBinding(windowId);
16786
+ const registered = originRegistry.getIframeWindow(windowId) !== null;
16787
+ if (!binding && !registered) return;
16788
+ bindings.delete(windowId);
16789
+ if (binding) binding.port.onmessage = null;
16790
+ originRegistry.unregister(windowId);
16791
+ runtime.destroyWindow(windowId);
16792
+ runtime.sessionRegistry.unregister(windowId);
16793
+ shellReadyState.environments.delete(windowId);
16794
+ shellReadyState.sessionRegistration.delete(windowId);
16795
+ try {
16796
+ hooks.onNappletRevoked?.({ windowId, reason, detail: REVOCATION_DETAIL[reason] });
16797
+ } catch {
16798
+ }
16799
+ }
16800
+ function dispatchEnvelope(windowId, binding, msg) {
16801
+ if (typeof msg !== "object" || msg === null || typeof msg.type !== "string") return;
16802
+ const envelope = msg;
16803
+ try {
16804
+ hooks.onNappletMessage?.(windowId, envelope);
16805
+ } catch {
16806
+ }
16807
+ const context = {
16808
+ hooks,
16809
+ origin: binding.origin,
16810
+ runtime,
16811
+ state: shellReadyState,
16812
+ sourceRegistrationId: binding.registrationId,
16813
+ sourceWindow: binding.sourceWindow,
16814
+ windowId
16815
+ };
16816
+ if (!registerSourceSession(context)) return;
16817
+ if (envelope.type === "shell.ready") {
16818
+ handleShellReady(context);
16819
+ return;
16820
+ }
16821
+ runtime.handleMessage(windowId, envelope);
16822
+ }
16823
+ function bindPort(windowId, sourceWindow, origin, port) {
16824
+ if (!originRegistry.bindPort(windowId, port)) {
16825
+ port.close();
16826
+ revokeNapplet(windowId, "second-hello");
16827
+ return;
16828
+ }
16829
+ const binding = {
16830
+ port,
16831
+ sourceWindow,
16832
+ origin,
16833
+ registrationId: originRegistry.getRegistrationId(sourceWindow) ?? 0
16834
+ };
16835
+ bindings.set(windowId, binding);
16836
+ const isCurrent = () => currentBinding(windowId) === binding;
16837
+ port.onmessage = (portEvent) => {
16838
+ if (isCurrent()) dispatchEnvelope(windowId, binding, portEvent.data);
16839
+ };
16840
+ const onPortFailure = () => {
16841
+ if (isCurrent()) revokeNapplet(windowId, "port-closed");
16842
+ };
16843
+ port.addEventListener("close", onPortFailure);
16844
+ port.addEventListener("messageerror", onPortFailure);
16845
+ port.start();
16846
+ }
16847
+ function handleMessage(event) {
16848
+ const sourceWindow = event.source;
16849
+ if (!sourceWindow) {
16850
+ reportUnrouted(hooks, event, "no-source-window");
16851
+ return;
16852
+ }
16853
+ const windowId = originRegistry.getWindowId(sourceWindow);
16854
+ if (!windowId) {
16855
+ reportUnrouted(hooks, event, "unregistered-window");
16856
+ return;
16857
+ }
16858
+ if (currentBinding(windowId) || originRegistry.getPort(windowId)) {
16859
+ revokeNapplet(windowId, isHello(event.data) ? "second-hello" : "window-message");
16860
+ return;
16861
+ }
16862
+ if (!isHello(event.data)) {
16863
+ revokeNapplet(windowId, "window-message");
16864
+ return;
16865
+ }
16866
+ const ports = event.ports ?? [];
16867
+ if (ports.length !== 1) {
16868
+ for (const port of ports) port.close();
16869
+ revokeNapplet(windowId, "invalid-hello");
16870
+ return;
16871
+ }
16872
+ bindPort(windowId, sourceWindow, event.origin, ports[0]);
16873
+ }
16874
+ function observeFrame(frame, windowId) {
16875
+ let loads = 0;
16876
+ const onLoad = () => {
16877
+ loads += 1;
16878
+ if (loads > 1) revokeNapplet(windowId, "second-load");
16879
+ };
16880
+ frame.addEventListener("load", onLoad);
16881
+ return () => frame.removeEventListener("load", onLoad);
16882
+ }
16883
+ function destroy() {
16884
+ for (const [windowId, binding] of bindings) {
16885
+ binding.port.onmessage = null;
16886
+ if (originRegistry.getPort(windowId) === binding.port) originRegistry.unregister(windowId);
16887
+ }
16888
+ bindings.clear();
16889
+ }
16890
+ return { handleMessage, revokeNapplet, observeFrame, destroy };
16891
+ }
16677
16892
  function createShellBridge(hooks) {
16678
16893
  const shellReadyState = createShellReadyState();
16679
16894
  const runtimeHooks = adaptHooks(hooks, {
@@ -16692,52 +16907,17 @@ function createShellBridge(hooks) {
16692
16907
  const environment = shellReadyState.environments.get(entry.windowId);
16693
16908
  if (!environment?.capabilities.domains.includes(domain)) continue;
16694
16909
  if (!runtime.aclState.check(entry.pubkey, entry.dTag, entry.aggregateHash, capability)) continue;
16695
- const win = originRegistry.getIframeWindow(entry.windowId);
16696
- if (!win) continue;
16697
- win.postMessage(envelope, "*");
16910
+ originRegistry.postToNapplet(entry.windowId, envelope);
16698
16911
  }
16699
16912
  }
16913
+ const transport = createNip5dTransport({ hooks, runtime, state: shellReadyState });
16700
16914
  return {
16701
- handleMessage(event) {
16702
- const sourceWindow = event.source;
16703
- if (!sourceWindow) {
16704
- reportUnrouted(hooks, event, "no-source-window");
16705
- return;
16706
- }
16707
- const windowId = originRegistry.getWindowId(sourceWindow);
16708
- if (!windowId) {
16709
- reportUnrouted(hooks, event, "unregistered-window");
16710
- return;
16711
- }
16712
- const msg = event.data;
16713
- if (typeof msg !== "object" || msg === null || typeof msg.type !== "string") return;
16714
- if (!registerSourceSession({
16715
- hooks,
16716
- origin: event.origin,
16717
- runtime,
16718
- state: shellReadyState,
16719
- sourceRegistrationId: originRegistry.getRegistrationId(sourceWindow) ?? 0,
16720
- sourceWindow,
16721
- windowId
16722
- })) return;
16723
- if (msg.type === "shell.ready") {
16724
- handleShellReady({
16725
- hooks,
16726
- origin: event.origin,
16727
- runtime,
16728
- state: shellReadyState,
16729
- sourceRegistrationId: originRegistry.getRegistrationId(sourceWindow) ?? 0,
16730
- sourceWindow,
16731
- windowId
16732
- });
16733
- return;
16734
- }
16735
- runtime.handleMessage(windowId, msg);
16736
- },
16915
+ handleMessage: transport.handleMessage,
16737
16916
  injectEvent(topic, payload) {
16738
16917
  runtime.injectEvent(topic, payload);
16739
16918
  },
16740
16919
  destroy() {
16920
+ transport.destroy();
16741
16921
  runtime.destroy();
16742
16922
  shellReadyState.clear();
16743
16923
  },
@@ -16752,6 +16932,8 @@ function createShellBridge(hooks) {
16752
16932
  const envelope = { type: "identity.changed", pubkey: pubkey2 };
16753
16933
  publishToEligibleNapplets(envelope, "identity", "identity:read");
16754
16934
  },
16935
+ observeFrame: transport.observeFrame,
16936
+ revokeNapplet: transport.revokeNapplet,
16755
16937
  get runtime() {
16756
16938
  return runtime;
16757
16939
  }
@@ -16973,19 +17155,34 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
16973
17155
  const target = window;
16974
17156
  const allowed2 = new Set(domains);
16975
17157
  const requestTimeoutMs = 3e4;
17158
+ for (const rtcCtor of ["RTCPeerConnection", "webkitRTCPeerConnection"]) {
17159
+ try {
17160
+ Object.defineProperty(target, rtcCtor, {
17161
+ value: void 0,
17162
+ writable: false,
17163
+ configurable: false,
17164
+ enumerable: false
17165
+ });
17166
+ } catch {
17167
+ }
17168
+ }
16976
17169
  function id() {
16977
17170
  if (target.crypto?.randomUUID) return target.crypto.randomUUID();
16978
17171
  return `napplet-${Date.now()}-${Math.random().toString(16).slice(2)}`;
16979
17172
  }
17173
+ const channel = new target.MessageChannel();
17174
+ const port = channel.port1;
17175
+ port.start();
17176
+ target.parent.postMessage({ type: "napplet.hello" }, "*", [channel.port2]);
16980
17177
  function post(message3) {
16981
- target.parent.postMessage(message3, "*");
17178
+ port.postMessage(message3);
16982
17179
  }
16983
17180
  function listen(listener) {
16984
- target.addEventListener("message", listener);
16985
- return () => target.removeEventListener("message", listener);
17181
+ port.addEventListener("message", listener);
17182
+ return () => port.removeEventListener("message", listener);
16986
17183
  }
16987
- function isParentMessage(event) {
16988
- return event.source === target.parent;
17184
+ function isShellMessage(event) {
17185
+ return event.currentTarget === port;
16989
17186
  }
16990
17187
  function request(message3, resultType, map, options = {}) {
16991
17188
  const requestId = message3.id ?? id();
@@ -17006,7 +17203,7 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
17006
17203
  reject2(new DOMException("Aborted", "AbortError"));
17007
17204
  };
17008
17205
  off = listen((event) => {
17009
- if (!isParentMessage(event)) return;
17206
+ if (!isShellMessage(event)) return;
17010
17207
  const incoming = event.data;
17011
17208
  if (typeof incoming !== "object" || incoming === null) return;
17012
17209
  const msg = incoming;
@@ -17111,7 +17308,7 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
17111
17308
  resolveReady = resolve;
17112
17309
  });
17113
17310
  const off = listen((event) => {
17114
- if (!isParentMessage(event) || environment) return;
17311
+ if (!isShellMessage(event) || environment) return;
17115
17312
  const incoming = event.data;
17116
17313
  if (typeof incoming !== "object" || incoming === null) return;
17117
17314
  const message3 = incoming;
@@ -17165,7 +17362,7 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
17165
17362
  }
17166
17363
  function domainEventHandle(eventType, callback, select2 = (message3) => message3.event) {
17167
17364
  const off = listen((event) => {
17168
- if (!isParentMessage(event)) return;
17365
+ if (!isShellMessage(event)) return;
17169
17366
  const msg = event.data;
17170
17367
  if (typeof msg === "object" && msg !== null && msg.type === eventType) callback(select2(msg));
17171
17368
  });
@@ -17176,7 +17373,7 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
17176
17373
  subscribe(filters, onEvent, onEose, options) {
17177
17374
  const subId = id();
17178
17375
  const off = listen((event) => {
17179
- if (!isParentMessage(event)) return;
17376
+ if (!isShellMessage(event)) return;
17180
17377
  const msg = event.data;
17181
17378
  if (typeof msg !== "object" || msg === null || msg.subId !== subId) return;
17182
17379
  if (msg.type === "relay.event") onEvent(msg.result);
@@ -17323,7 +17520,7 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
17323
17520
  state.pendingEvents.push(event);
17324
17521
  }
17325
17522
  listen((event) => {
17326
- if (!isParentMessage(event)) return;
17523
+ if (!isShellMessage(event)) return;
17327
17524
  const msg = event.data;
17328
17525
  if (typeof msg !== "object" || msg === null || typeof msg.type !== "string") return;
17329
17526
  if (msg.type === "inc.channel.opened" && typeof msg.channelId === "string" && typeof msg.peer === "string") {
@@ -17358,14 +17555,14 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
17358
17555
  const handlers = /* @__PURE__ */ new Set();
17359
17556
  const subscriptionId = id();
17360
17557
  const offEvent = listen((event) => {
17361
- if (!isParentMessage(event)) return;
17558
+ if (!isShellMessage(event)) return;
17362
17559
  const msg = event.data;
17363
17560
  if (typeof msg !== "object" || msg === null || msg.type !== "inc.event" || msg.topic !== stableTopic || typeof msg.sender !== "string") return;
17364
17561
  const delivered = Object.prototype.hasOwnProperty.call(msg, "payload") ? { topic: stableTopic, sender: msg.sender, payload: msg.payload } : { topic: stableTopic, sender: msg.sender };
17365
17562
  for (const handler of handlers) handler(delivered);
17366
17563
  });
17367
17564
  const offResult = listen((event) => {
17368
- if (!isParentMessage(event)) return;
17565
+ if (!isShellMessage(event)) return;
17369
17566
  const msg = event.data;
17370
17567
  if (typeof msg !== "object" || msg === null || msg.type !== "inc.subscribe.result" || msg.id !== subscriptionId) return;
17371
17568
  offResult();
@@ -17420,9 +17617,9 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
17420
17617
  return request(
17421
17618
  { type: "inc.channel.list" },
17422
17619
  "inc.channel.list.result",
17423
- (msg) => Object.freeze((Array.isArray(msg.channels) ? msg.channels : []).flatMap((channel) => channel && typeof channel === "object" && typeof channel.id === "string" && typeof channel.peer === "string" ? [Object.freeze({
17424
- id: channel.id,
17425
- peer: channel.peer
17620
+ (msg) => Object.freeze((Array.isArray(msg.channels) ? msg.channels : []).flatMap((channel2) => channel2 && typeof channel2 === "object" && typeof channel2.id === "string" && typeof channel2.peer === "string" ? [Object.freeze({
17621
+ id: channel2.id,
17622
+ peer: channel2.peer
17426
17623
  })] : []))
17427
17624
  );
17428
17625
  },
@@ -17484,7 +17681,7 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
17484
17681
  getBadges: () => read("identity.getBadges", "badges", []),
17485
17682
  onChanged(handler) {
17486
17683
  const off = listen((event) => {
17487
- if (!isParentMessage(event)) return;
17684
+ if (!isShellMessage(event)) return;
17488
17685
  const msg = event.data;
17489
17686
  if (typeof msg !== "object" || msg === null || msg.type !== "identity.changed") return;
17490
17687
  if (typeof msg.pubkey === "string") handler(msg.pubkey);
@@ -17498,7 +17695,7 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
17498
17695
  get: () => request({ type: "theme.get" }, "theme.get.result", (msg) => msg.theme),
17499
17696
  onChanged(handler) {
17500
17697
  const off = listen((event) => {
17501
- if (!isParentMessage(event)) return;
17698
+ if (!isShellMessage(event)) return;
17502
17699
  const msg = event.data;
17503
17700
  if (typeof msg === "object" && msg !== null && msg.type === "theme.changed") handler(msg.theme);
17504
17701
  });
@@ -17614,7 +17811,7 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
17614
17811
  if (keysSmartForwardingInstalled) return;
17615
17812
  keysSmartForwardingInstalled = true;
17616
17813
  listen((event) => {
17617
- if (!isParentMessage(event)) return;
17814
+ if (!isShellMessage(event)) return;
17618
17815
  const msg = event.data;
17619
17816
  if (typeof msg === "object" && msg !== null && msg.type === "keys.bindings") {
17620
17817
  replaceKeyBindings(msg.bindings);
@@ -17668,7 +17865,7 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
17668
17865
  }
17669
17866
  callbacks.add(callback);
17670
17867
  const off = listen((event) => {
17671
- if (!isParentMessage(event)) return;
17868
+ if (!isShellMessage(event)) return;
17672
17869
  const msg = event.data;
17673
17870
  if (typeof msg === "object" && msg !== null && msg.type === "keys.action" && msg.actionId === actionId) callback();
17674
17871
  });
@@ -17692,7 +17889,7 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
17692
17889
  console.warn(`[KEHTO-MEDIA-${name}] Deprecated media API; use ${replacement}. Warned once per endpoint.`);
17693
17890
  };
17694
17891
  listen((event) => {
17695
- if (!isParentMessage(event)) return;
17892
+ if (!isShellMessage(event)) return;
17696
17893
  const msg = event.data;
17697
17894
  if (!msg || typeof msg !== "object" || typeof msg.sessionId !== "string") return;
17698
17895
  const sessionId = msg.sessionId;
@@ -17769,7 +17966,7 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
17769
17966
  function makeNotify() {
17770
17967
  const on = (type, callback) => {
17771
17968
  const off = listen((event) => {
17772
- if (!isParentMessage(event)) return;
17969
+ if (!isShellMessage(event)) return;
17773
17970
  const msg = event.data;
17774
17971
  if (typeof msg === "object" && msg !== null && msg.type === type) callback(msg);
17775
17972
  });
@@ -17783,9 +17980,9 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
17783
17980
  ),
17784
17981
  dismiss: (notificationId) => fire({ type: "notify.dismiss", notificationId }),
17785
17982
  badge: (count) => fire({ type: "notify.badge", count }),
17786
- registerChannel: (channel) => fire({ type: "notify.channel.register", ...channel }),
17787
- requestPermission: (channel) => request(
17788
- { type: "notify.permission.request", ...channel ? { channel } : {} },
17983
+ registerChannel: (channel2) => fire({ type: "notify.channel.register", ...channel2 }),
17984
+ requestPermission: (channel2) => request(
17985
+ { type: "notify.permission.request", ...channel2 ? { channel: channel2 } : {} },
17789
17986
  "notify.permission.result",
17790
17987
  (msg) => ({ granted: msg.granted })
17791
17988
  ),
@@ -17809,7 +18006,7 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
17809
18006
  get: () => request({ type: "config.get" }, "config.values", (msg) => msg.values ?? {}),
17810
18007
  subscribe(callback) {
17811
18008
  const off = listen((event) => {
17812
- if (!isParentMessage(event)) return;
18009
+ if (!isShellMessage(event)) return;
17813
18010
  const msg = event.data;
17814
18011
  if (typeof msg === "object" && msg !== null && msg.type === "config.values") callback(msg.values ?? {});
17815
18012
  });
@@ -17822,7 +18019,7 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
17822
18019
  openSettings: (options) => fire({ type: "config.openSettings", ...options && typeof options === "object" ? options : {} }),
17823
18020
  onSchemaError(callback) {
17824
18021
  const off = listen((event) => {
17825
- if (!isParentMessage(event)) return;
18022
+ if (!isShellMessage(event)) return;
17826
18023
  const msg = event.data;
17827
18024
  if (typeof msg === "object" && msg !== null && msg.type === "config.schemaError") callback(msg);
17828
18025
  });
@@ -17935,7 +18132,7 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
17935
18132
  close: (server) => req("cvm.close", { server }, (msg) => voidResult(msg, "cvm close failed")),
17936
18133
  onEvent(callback) {
17937
18134
  const off = listen((event) => {
17938
- if (!isParentMessage(event)) return;
18135
+ if (!isShellMessage(event)) return;
17939
18136
  const msg = event.data;
17940
18137
  if (typeof msg === "object" && msg !== null && msg.type === "cvm.event" && msg.server !== void 0 && msg.message !== void 0) {
17941
18138
  callback(msg.server, msg.message);
@@ -17959,7 +18156,7 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
17959
18156
  const subId = id();
17960
18157
  const handlers = { event: /* @__PURE__ */ new Set(), closed: /* @__PURE__ */ new Set() };
17961
18158
  const off = listen((event) => {
17962
- if (!isParentMessage(event)) return;
18159
+ if (!isShellMessage(event)) return;
17963
18160
  const msg = event.data;
17964
18161
  if (typeof msg !== "object" || msg === null || msg.subId !== subId) return;
17965
18162
  if (msg.type === "outbox.event") for (const handler of handlers.event) handler(msg.result);
@@ -17993,7 +18190,7 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
17993
18190
  status: (uploadId) => request({ type: "upload.status", uploadId }, "upload.status.result", (msg) => fieldOrThrow(msg, "status", "upload status unavailable")),
17994
18191
  onStatus(callback) {
17995
18192
  const off = listen((event) => {
17996
- if (!isParentMessage(event)) return;
18193
+ if (!isShellMessage(event)) return;
17997
18194
  const msg = event.data;
17998
18195
  if (typeof msg === "object" && msg !== null && msg.type === "upload.status.changed" && msg.status !== void 0) callback(msg.status);
17999
18196
  });
@@ -18034,7 +18231,7 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
18034
18231
  }
18035
18232
  }
18036
18233
  listen((event) => {
18037
- if (!isParentMessage(event)) return;
18234
+ if (!isShellMessage(event)) return;
18038
18235
  const message3 = event.data;
18039
18236
  if (!message3 || message3.type !== "intent.deliver") return;
18040
18237
  const value = message3.delivery;
@@ -18308,7 +18505,7 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
18308
18505
  });
18309
18506
  };
18310
18507
  listen((event) => {
18311
- if (!isParentMessage(event)) return;
18508
+ if (!isShellMessage(event)) return;
18312
18509
  const incoming = event.data;
18313
18510
  if (!incoming || incoming.type !== "gamepad.state" || "id" in incoming || !valid(incoming)) return;
18314
18511
  state = copy(incoming);
@@ -18344,7 +18541,7 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
18344
18541
  unsubscribe: (subscriptionId) => req("dm.unsubscribe", { subscriptionId }),
18345
18542
  onMessage(callback) {
18346
18543
  const off = listen((event) => {
18347
- if (!isParentMessage(event)) return;
18544
+ if (!isShellMessage(event)) return;
18348
18545
  const msg = event.data;
18349
18546
  if (typeof msg === "object" && msg !== null && msg.type === "dm.message" && typeof msg.subscriptionId === "string") {
18350
18547
  callback(msg.message, msg.subscriptionId);
@@ -18393,7 +18590,7 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
18393
18590
  post({ type: "llm.cancel", id: id(), requestId });
18394
18591
  };
18395
18592
  const off = listen((event) => {
18396
- if (!isParentMessage(event)) return;
18593
+ if (!isShellMessage(event)) return;
18397
18594
  const msg = event.data;
18398
18595
  if (typeof msg !== "object" || msg === null) return;
18399
18596
  if (type === "llm.generate" && msg.type === "llm.delta" && msg.requestId === requestId) {
@@ -22228,7 +22425,7 @@ function createPajaRelayHooks(pool, getSimulation, relayConfig, getPublishPool =
22228
22425
  cleanups.get(subKey)?.();
22229
22426
  cleanups.delete(subKey);
22230
22427
  },
22231
- openScopedRelay(windowId, relayUrl2, subId, filters, sourceWindow) {
22428
+ openScopedRelay(windowId, relayUrl2, subId, filters, target) {
22232
22429
  closeScopedRelay(windowId);
22233
22430
  const configured = new Map(relayConfig.getRelayUrls().flatMap((url) => {
22234
22431
  const normalized = normalizeRelayUrl(url);
@@ -22237,20 +22434,20 @@ function createPajaRelayHooks(pool, getSimulation, relayConfig, getPublishPool =
22237
22434
  const requested = normalizeRelayUrl(relayUrl2);
22238
22435
  const allowedUrl = requested && isPajaRelayAllowed(relayUrl2, () => relayConfig.getRelayUrls()) ? configured.get(requested) ?? requested : void 0;
22239
22436
  if (getSimulation().relay.mode !== "live" || !allowedUrl) {
22240
- sourceWindow.postMessage({ type: "relay.closed", subId, reason: "scoped relay unavailable" }, "*");
22437
+ target.postMessage({ type: "relay.closed", subId, reason: "scoped relay unavailable" });
22241
22438
  return;
22242
22439
  }
22243
22440
  const subscription = pool.subscription([allowedUrl], filters).subscribe((item) => {
22244
22441
  if (item === "EOSE") {
22245
- sourceWindow.postMessage({ type: "relay.eose", subId }, "*");
22442
+ target.postMessage({ type: "relay.eose", subId });
22246
22443
  return;
22247
22444
  }
22248
22445
  if (!isVerifiedNostrEvent(item)) return;
22249
- sourceWindow.postMessage({
22446
+ target.postMessage({
22250
22447
  type: "relay.event",
22251
22448
  subId,
22252
22449
  result: { event: item, sidecar: { relayHints: [allowedUrl] } }
22253
- }, "*");
22450
+ });
22254
22451
  });
22255
22452
  scoped.set(windowId, { relayUrl: allowedUrl, unsubscribe: () => subscription.unsubscribe() });
22256
22453
  },
@@ -24907,6 +25104,15 @@ function registerFrameForGeneration(frame, config, generation2, identity, enviro
24907
25104
  originRegistry.setEnvironment(win, environment);
24908
25105
  return windowId;
24909
25106
  }
25107
+ function ensureFreshNappletFrame(frame) {
25108
+ const win = frame.contentWindow;
25109
+ if (!win || !originRegistry.isSpent(win) && originRegistry.getWindowId(win) === void 0) return frame;
25110
+ const fresh = frame.cloneNode(false);
25111
+ fresh.removeAttribute("src");
25112
+ fresh.removeAttribute("srcdoc");
25113
+ frame.replaceWith(fresh);
25114
+ return fresh;
25115
+ }
24910
25116
  async function navigateFrame(frame, config, generation2, adapter, resolvedTarget, windowId, isCurrent, onRegistered) {
24911
25117
  denyNappletControllerAccess(frame);
24912
25118
  const identity = getTargetOriginIdentity(config, resolvedTarget);
@@ -25004,9 +25210,6 @@ var FS_PICKER_METHODS = {
25004
25210
  "fs.pickDirectory.result": "showDirectoryPicker",
25005
25211
  "fs.pickSaveFile.result": "showSaveFilePicker"
25006
25212
  };
25007
- var proxyToReal = /* @__PURE__ */ new WeakMap();
25008
- var realToProxy = /* @__PURE__ */ new WeakMap();
25009
- var proxyContexts = /* @__PURE__ */ new WeakMap();
25010
25213
  function isNappletMessage(value) {
25011
25214
  return typeof value === "object" && value !== null && !Array.isArray(value) && typeof value.type === "string";
25012
25215
  }
@@ -25070,39 +25273,6 @@ function appendPajaMessageLog(state, direction, raw, windowId) {
25070
25273
  }
25071
25274
  renderPajaMessageLog(state);
25072
25275
  }
25073
- function createPajaPostMessageProxy(realWin, state, windowId) {
25074
- const existing = realToProxy.get(realWin);
25075
- if (existing) {
25076
- proxyContexts.set(existing, { state, windowId });
25077
- return existing;
25078
- }
25079
- const proxy = new Proxy(realWin, {
25080
- get(target, prop) {
25081
- if (prop === "postMessage") {
25082
- return (msg, targetOrigin, transfer) => {
25083
- const context = proxyContexts.get(proxy);
25084
- appendPajaMessageLog(
25085
- context?.state ?? state,
25086
- "shell->napplet",
25087
- redactPajaMessageForLog(msg),
25088
- context?.windowId ?? windowId
25089
- );
25090
- return target.postMessage(msg, targetOrigin, transfer);
25091
- };
25092
- }
25093
- try {
25094
- const val = Reflect.get(target, prop, target);
25095
- return typeof val === "function" ? val.bind(target) : val;
25096
- } catch {
25097
- return void 0;
25098
- }
25099
- }
25100
- });
25101
- proxyToReal.set(proxy, realWin);
25102
- realToProxy.set(realWin, proxy);
25103
- proxyContexts.set(proxy, { state, windowId });
25104
- return proxy;
25105
- }
25106
25276
  function redactPajaMessageForLog(message3) {
25107
25277
  if (!isRecord8(message3) || message3.type !== "config.values") return message3;
25108
25278
  return {
@@ -25122,33 +25292,11 @@ function installPajaOriginRegistryProxy(originRegistry2, stateRef, onWindowRemov
25122
25292
  unregister(windowId);
25123
25293
  };
25124
25294
  }
25125
- const originalGetIframeWindow = originRegistry2.getIframeWindow.bind(originRegistry2);
25126
- originRegistry2.getIframeWindow = (windowId) => {
25127
- const win = originalGetIframeWindow(windowId);
25128
- if (!win) return null;
25129
- return createPajaPostMessageProxy(win, stateRef(), windowId);
25130
- };
25131
- const originalGetWindowId = originRegistry2.getWindowId.bind(originRegistry2);
25132
- originRegistry2.getWindowId = (win) => {
25133
- const result2 = originalGetWindowId(win);
25134
- if (result2) return result2;
25135
- const real = proxyToReal.get(win);
25136
- return real ? originalGetWindowId(real) : void 0;
25137
- };
25138
- const originalGetIdentity = originRegistry2.getIdentity.bind(originRegistry2);
25139
- originRegistry2.getIdentity = (win) => {
25140
- const real = proxyToReal.get(win);
25141
- return originalGetIdentity(win) ?? (real ? originalGetIdentity(real) : void 0);
25142
- };
25143
- const originalGetRegistrationId = originRegistry2.getRegistrationId.bind(originRegistry2);
25144
- originRegistry2.getRegistrationId = (win) => {
25145
- const real = proxyToReal.get(win);
25146
- return originalGetRegistrationId(win) ?? (real ? originalGetRegistrationId(real) : void 0);
25147
- };
25148
- const originalGetEnvironment = originRegistry2.getEnvironment.bind(originRegistry2);
25149
- originRegistry2.getEnvironment = (win) => {
25150
- const real = proxyToReal.get(win);
25151
- return originalGetEnvironment(win) ?? (real ? originalGetEnvironment(real) : void 0);
25295
+ const postToNapplet = originRegistry2.postToNapplet.bind(originRegistry2);
25296
+ originRegistry2.postToNapplet = (windowId, message3) => {
25297
+ const delivered = postToNapplet(windowId, message3);
25298
+ if (delivered) appendPajaMessageLog(stateRef(), "shell->napplet", redactPajaMessageForLog(message3), windowId);
25299
+ return delivered;
25152
25300
  };
25153
25301
  }
25154
25302
  function renderPajaDevtools(state, options) {
@@ -26296,6 +26444,101 @@ function unregisterSingleFrameWindow(bridge, runtime, windowId) {
26296
26444
  if (runtime.currentWindowId === windowId) runtime.currentWindowId = null;
26297
26445
  }
26298
26446
 
26447
+ // src/browser-intent-controller.ts
26448
+ var MAX_INTENT_DELIVERY_ATTEMPTS = 10;
26449
+ var BrowserIntentController = class {
26450
+ constructor(options) {
26451
+ this.options = options;
26452
+ this.maxAttempts = normalizeAttempts(options.maxAttempts);
26453
+ }
26454
+ options;
26455
+ maxAttempts;
26456
+ /** Retain delivery work immediately; completion remains host-observable only. */
26457
+ accept(params) {
26458
+ const acceptance = Object.freeze({ completion: this.dispatch(params) });
26459
+ this.options.onAccepted?.(params, acceptance);
26460
+ return acceptance;
26461
+ }
26462
+ /** Complete an already accepted delivery. Kept public for host diagnostics and tests. */
26463
+ async dispatch(params) {
26464
+ const dispatch2 = freezeDispatch(params);
26465
+ let reason = "no-current-target";
26466
+ for (let attempt = 1; attempt <= this.maxAttempts; attempt += 1) {
26467
+ let generation2;
26468
+ try {
26469
+ generation2 = await this.options.openOrReuse(dispatch2, attempt);
26470
+ } catch {
26471
+ reason = "open-failed";
26472
+ continue;
26473
+ }
26474
+ if (!generation2) {
26475
+ reason = "open-failed";
26476
+ continue;
26477
+ }
26478
+ try {
26479
+ await this.options.waitForReady(generation2);
26480
+ } catch {
26481
+ reason = "ready-failed";
26482
+ continue;
26483
+ }
26484
+ if (!await this.options.isCurrent(generation2)) {
26485
+ reason = "no-current-target";
26486
+ continue;
26487
+ }
26488
+ try {
26489
+ await this.options.send(generation2, dispatch2);
26490
+ this.options.onDelivered?.(dispatch2);
26491
+ return;
26492
+ } catch {
26493
+ this.options.onTerminal?.(dispatch2, "send-failed");
26494
+ throw new Error("intent target send failed");
26495
+ }
26496
+ }
26497
+ this.options.onTerminal?.(dispatch2, reason);
26498
+ throw new Error(`intent target ${reason}`);
26499
+ }
26500
+ };
26501
+ function normalizeAttempts(value) {
26502
+ if (value === void 0) return 2;
26503
+ if (!Number.isFinite(value)) throw new TypeError("maxAttempts must be finite");
26504
+ return Math.min(MAX_INTENT_DELIVERY_ATTEMPTS, Math.max(1, Math.floor(value)));
26505
+ }
26506
+ function freezeDispatch(params) {
26507
+ if (!params || typeof params.handler !== "string" || params.handler.length === 0) {
26508
+ throw new TypeError("Intent dispatch requires a handler");
26509
+ }
26510
+ if (typeof params.sender !== "string" || params.sender.length === 0 || typeof params.archetype !== "string" || params.archetype.length === 0 || typeof params.action !== "string" || params.action.length === 0 || typeof params.convention !== "string" || params.convention.length === 0) {
26511
+ throw new TypeError("Intent dispatch requires canonical routing fields");
26512
+ }
26513
+ const payload = freezeValue(params.payload);
26514
+ const behavior = params.behavior === void 0 ? void 0 : freezeValue({ ...params.behavior });
26515
+ return Object.freeze({
26516
+ handler: params.handler,
26517
+ sender: params.sender,
26518
+ archetype: params.archetype,
26519
+ action: params.action,
26520
+ convention: params.convention,
26521
+ ...params.payload === void 0 ? {} : { payload },
26522
+ ...behavior === void 0 ? {} : { behavior },
26523
+ ...params.sourceWindowId === void 0 ? {} : { sourceWindowId: params.sourceWindowId }
26524
+ });
26525
+ }
26526
+ function freezeValue(value, seen = /* @__PURE__ */ new WeakMap()) {
26527
+ if (typeof value !== "object" || value === null) return value;
26528
+ const existing = seen.get(value);
26529
+ if (existing !== void 0) return existing;
26530
+ if (Array.isArray(value)) {
26531
+ const copy2 = [];
26532
+ seen.set(value, copy2);
26533
+ for (const item of value) copy2.push(freezeValue(item, seen));
26534
+ return Object.freeze(copy2);
26535
+ }
26536
+ const copy = {};
26537
+ seen.set(value, copy);
26538
+ for (const [key, item] of Object.entries(value)) copy[key] = freezeValue(item, seen);
26539
+ return Object.freeze(copy);
26540
+ }
26541
+
26299
26542
  // src/browser-runtime-tabs.ts
26300
26543
  var PAJA_RUNTIME_TABS_STORAGE_KEY = "kehto:paja:runtime-tabs:v1";
26301
26544
  function resolvedTargetKey(target) {
@@ -26446,6 +26689,23 @@ function reloadActiveRuntimeTab(state, context) {
26446
26689
  activateRuntimeTab(state, context, tab.id);
26447
26690
  startRuntimeTabNavigation(tab, state, context);
26448
26691
  }
26692
+ function replaceRevokedRuntimeTabFrame(state, context, windowId) {
26693
+ const tab = state.tabs.find((candidate) => candidate.windowId === windowId);
26694
+ if (!tab) return false;
26695
+ context.onTabDestroyed?.(tab);
26696
+ context.runtime.readyWindowIds.delete(windowId);
26697
+ if (context.runtime.currentWindowId === windowId) context.runtime.currentWindowId = null;
26698
+ tab.generation = ++state.generation;
26699
+ tab.windowId = null;
26700
+ tab.status = "error";
26701
+ const fresh = createRuntimeTabFrame(tab, state, context);
26702
+ fresh.hidden = tab.frame.hidden;
26703
+ tab.frame.replaceWith(fresh);
26704
+ tab.frame = fresh;
26705
+ if (state.activeTabId === tab.id) context.setStatus(state, "error");
26706
+ renderRuntimeTabs(state);
26707
+ return true;
26708
+ }
26449
26709
  function showDuplicatePointerDialog() {
26450
26710
  const backdrop = document.getElementById("duplicate-pointer-dialog");
26451
26711
  const loadAgain = document.getElementById("duplicate-load-again");
@@ -26694,6 +26954,7 @@ function startRuntimeTabNavigation(tab, state, context) {
26694
26954
  () => tab.generation === generation2,
26695
26955
  (windowId2) => {
26696
26956
  if (tab.generation !== generation2) return;
26957
+ if (windowId2) context.bridge.observeFrame(tab.frame, windowId2);
26697
26958
  tab.windowId = windowId2;
26698
26959
  if (state.activeTabId === tab.id) context.runtime.currentWindowId = windowId2;
26699
26960
  }
@@ -26719,229 +26980,28 @@ function runtimeTabWindowId(config, tab) {
26719
26980
  return `${config.window.id}:${tab.id}:${tab.generation}`;
26720
26981
  }
26721
26982
 
26722
- // src/browser-local-loader.ts
26723
- async function loadLocalRuntimeFile(state, context, file, effects) {
26724
- if (context.config.target.mode !== "runtime-pointer") return;
26725
- const fileName = file.name;
26726
- context.setPointerStatus(state, `reading ${fileName}`);
26727
- context.setStatus(state, "booting");
26728
- appendPajaMessageLog(state, "paja", { type: "paja.local.load", fileName });
26729
- try {
26730
- const target = await createPajaLocalTarget(file);
26731
- const identityStatus = `local ${target.dTag}:${target.aggregateHash.slice(0, 12)}`;
26732
- const loadedStatus = target.relativeAssets.length > 0 ? `${identityStatus}; ${target.relativeAssets.length} relative asset(s) will not load. ${PAJA_LOCAL_SINGLE_FILE_HINT}` : identityStatus;
26733
- context.setPointerStatus(state, loadedStatus);
26734
- appendPajaMessageLog(state, "paja", {
26735
- type: "paja.local.loaded",
26736
- fileName: target.fileName,
26737
- dTag: target.dTag,
26738
- aggregateHash: target.aggregateHash,
26739
- ...target.relativeAssets.length > 0 ? { relativeAssets: [...target.relativeAssets] } : {}
26740
- });
26741
- const key = resolvedTargetKey(target);
26742
- const duplicate = state.tabs.find((tab2) => tab2.key === key);
26743
- if (duplicate) {
26744
- const choice = await showDuplicatePointerDialog();
26745
- if (choice === "cancel") {
26746
- context.setStatus(state, getActiveTab(state)?.status ?? "ready");
26747
- context.setPointerStatus(state, `already running: ${duplicate.title}`);
26748
- appendPajaMessageLog(state, "paja", { type: "paja.local.duplicate.cancelled", tabId: duplicate.id });
26749
- return;
26750
- }
26751
- if (choice === "open-tab") {
26752
- activateRuntimeTab(state, context, duplicate.id);
26753
- effects.persistTabs(state);
26754
- appendPajaMessageLog(state, "paja", { type: "paja.local.duplicate.opened", tabId: duplicate.id });
26755
- return;
26756
- }
26757
- }
26758
- const tab = addRuntimeTab(state, context, "", target);
26759
- tab.pointerStatus = loadedStatus;
26760
- context.setPointerStatus(state, loadedStatus);
26761
- effects.persistTabs(state);
26762
- } catch (error) {
26763
- const message3 = error instanceof Error ? error.message : String(error);
26764
- context.setPointerStatus(state, message3);
26765
- context.setStatus(state, getActiveTab(state)?.status ?? "error");
26766
- appendPajaMessageLog(state, "paja", { type: "paja.local.error", fileName, error: message3 });
26767
- }
26768
- }
26769
- function pickLocalHtmlFile(files) {
26770
- const list = Array.from(files);
26771
- return list.find((file) => isPajaLocalHtmlFile(file)) ?? list[0] ?? null;
26772
- }
26773
- function installLocalFileControls(load) {
26774
- const input = document.getElementById("runtime-local-file");
26775
- const open = document.getElementById("runtime-local-open");
26776
- const stage = document.getElementById("napplet-stage");
26777
- if (!(input instanceof HTMLInputElement) || !(open instanceof HTMLButtonElement)) return disposeNothing;
26778
- let dragDepth = 0;
26779
- const setDropActive = (active) => stage?.classList.toggle("drop-active", active);
26780
- const carriesFiles = (event) => event.dataTransfer?.types.includes("Files") === true;
26781
- const onOpen = () => input.click();
26782
- const onChange = () => {
26783
- const file = pickLocalHtmlFile(input.files ?? []);
26784
- input.value = "";
26785
- if (file) void load(file);
26786
- };
26787
- const onDragEnter = (event) => {
26788
- if (!carriesFiles(event)) return;
26789
- dragDepth += 1;
26790
- setDropActive(true);
26791
- };
26792
- const onDragOver = (event) => {
26793
- if (!carriesFiles(event)) return;
26794
- event.preventDefault();
26795
- if (event.dataTransfer) event.dataTransfer.dropEffect = "copy";
26796
- };
26797
- const onDragLeave = (event) => {
26798
- if (!carriesFiles(event)) return;
26799
- dragDepth = Math.max(0, dragDepth - 1);
26800
- if (dragDepth === 0) setDropActive(false);
26801
- };
26802
- const onDrop = (event) => {
26803
- if (!carriesFiles(event)) return;
26804
- event.preventDefault();
26805
- dragDepth = 0;
26806
- setDropActive(false);
26807
- const file = pickLocalHtmlFile(event.dataTransfer?.files ?? []);
26808
- if (file) void load(file);
26809
- };
26810
- open.addEventListener("click", onOpen);
26811
- input.addEventListener("change", onChange);
26812
- document.addEventListener("dragenter", onDragEnter);
26813
- document.addEventListener("dragover", onDragOver);
26814
- document.addEventListener("dragleave", onDragLeave);
26815
- document.addEventListener("drop", onDrop);
26816
- return () => {
26817
- open.removeEventListener("click", onOpen);
26818
- input.removeEventListener("change", onChange);
26819
- document.removeEventListener("dragenter", onDragEnter);
26820
- document.removeEventListener("dragover", onDragOver);
26821
- document.removeEventListener("dragleave", onDragLeave);
26822
- document.removeEventListener("drop", onDrop);
26823
- };
26824
- }
26825
- function disposeNothing() {
26826
- }
26827
-
26828
- // src/browser-intent-controller.ts
26829
- var MAX_INTENT_DELIVERY_ATTEMPTS = 10;
26830
- var BrowserIntentController = class {
26831
- constructor(options) {
26832
- this.options = options;
26833
- this.maxAttempts = normalizeAttempts(options.maxAttempts);
26834
- }
26835
- options;
26836
- maxAttempts;
26837
- /** Retain delivery work immediately; completion remains host-observable only. */
26838
- accept(params) {
26839
- const acceptance = Object.freeze({ completion: this.dispatch(params) });
26840
- this.options.onAccepted?.(params, acceptance);
26841
- return acceptance;
26842
- }
26843
- /** Complete an already accepted delivery. Kept public for host diagnostics and tests. */
26844
- async dispatch(params) {
26845
- const dispatch2 = freezeDispatch(params);
26846
- let reason = "no-current-target";
26847
- for (let attempt = 1; attempt <= this.maxAttempts; attempt += 1) {
26848
- let generation2;
26849
- try {
26850
- generation2 = await this.options.openOrReuse(dispatch2, attempt);
26851
- } catch {
26852
- reason = "open-failed";
26853
- continue;
26854
- }
26855
- if (!generation2) {
26856
- reason = "open-failed";
26857
- continue;
26858
- }
26859
- try {
26860
- await this.options.waitForReady(generation2);
26861
- } catch {
26862
- reason = "ready-failed";
26863
- continue;
26864
- }
26865
- if (!await this.options.isCurrent(generation2)) {
26866
- reason = "no-current-target";
26867
- continue;
26868
- }
26869
- try {
26870
- await this.options.send(generation2, dispatch2);
26871
- this.options.onDelivered?.(dispatch2);
26872
- return;
26873
- } catch {
26874
- this.options.onTerminal?.(dispatch2, "send-failed");
26875
- throw new Error("intent target send failed");
26876
- }
26877
- }
26878
- this.options.onTerminal?.(dispatch2, reason);
26879
- throw new Error(`intent target ${reason}`);
26880
- }
26881
- };
26882
- function normalizeAttempts(value) {
26883
- if (value === void 0) return 2;
26884
- if (!Number.isFinite(value)) throw new TypeError("maxAttempts must be finite");
26885
- return Math.min(MAX_INTENT_DELIVERY_ATTEMPTS, Math.max(1, Math.floor(value)));
26886
- }
26887
- function freezeDispatch(params) {
26888
- if (!params || typeof params.handler !== "string" || params.handler.length === 0) {
26889
- throw new TypeError("Intent dispatch requires a handler");
26890
- }
26891
- if (typeof params.sender !== "string" || params.sender.length === 0 || typeof params.archetype !== "string" || params.archetype.length === 0 || typeof params.action !== "string" || params.action.length === 0 || typeof params.convention !== "string" || params.convention.length === 0) {
26892
- throw new TypeError("Intent dispatch requires canonical routing fields");
26893
- }
26894
- const payload = freezeValue(params.payload);
26895
- const behavior = params.behavior === void 0 ? void 0 : freezeValue({ ...params.behavior });
26896
- return Object.freeze({
26897
- handler: params.handler,
26898
- sender: params.sender,
26899
- archetype: params.archetype,
26900
- action: params.action,
26901
- convention: params.convention,
26902
- ...params.payload === void 0 ? {} : { payload },
26903
- ...behavior === void 0 ? {} : { behavior },
26904
- ...params.sourceWindowId === void 0 ? {} : { sourceWindowId: params.sourceWindowId }
26905
- });
26906
- }
26907
- function freezeValue(value, seen = /* @__PURE__ */ new WeakMap()) {
26908
- if (typeof value !== "object" || value === null) return value;
26909
- const existing = seen.get(value);
26910
- if (existing !== void 0) return existing;
26911
- if (Array.isArray(value)) {
26912
- const copy2 = [];
26913
- seen.set(value, copy2);
26914
- for (const item of value) copy2.push(freezeValue(item, seen));
26915
- return Object.freeze(copy2);
26916
- }
26917
- const copy = {};
26918
- seen.set(value, copy);
26919
- for (const [key, item] of Object.entries(value)) copy[key] = freezeValue(item, seen);
26920
- return Object.freeze(copy);
26921
- }
26922
-
26923
- // src/installed-napplet-catalog.ts
26924
- function matchesInstalledNappletRecord(record3, target) {
26925
- return target.id === record3.id && target.aggregateHash === record3.aggregateHash;
26926
- }
26927
- var InstalledNappletCatalog = class {
26928
- records = /* @__PURE__ */ new Map();
26929
- listeners = /* @__PURE__ */ new Set();
26930
- /** Insert or replace a record from an already resolver-verified pointer. */
26931
- install(resolved) {
26932
- const record3 = freezeRecord({
26933
- id: resolved.manifest.catalogId,
26934
- dTag: resolved.dTag,
26935
- aggregateHash: resolved.aggregateHash,
26936
- pointer: copyPointer(resolved.pointer),
26937
- ...resolved.manifest.title === void 0 ? {} : { title: resolved.manifest.title },
26938
- requires: [...resolved.manifest.requires],
26939
- optional: [...resolved.manifest.optional ?? []],
26940
- archetypes: resolved.manifest.archetypes.map((archetype) => ({
26941
- slug: archetype.slug,
26942
- convention: archetype.convention,
26943
- params: [...archetype.params]
26944
- }))
26983
+ // src/installed-napplet-catalog.ts
26984
+ function matchesInstalledNappletRecord(record3, target) {
26985
+ return target.id === record3.id && target.aggregateHash === record3.aggregateHash;
26986
+ }
26987
+ var InstalledNappletCatalog = class {
26988
+ records = /* @__PURE__ */ new Map();
26989
+ listeners = /* @__PURE__ */ new Set();
26990
+ /** Insert or replace a record from an already resolver-verified pointer. */
26991
+ install(resolved) {
26992
+ const record3 = freezeRecord({
26993
+ id: resolved.manifest.catalogId,
26994
+ dTag: resolved.dTag,
26995
+ aggregateHash: resolved.aggregateHash,
26996
+ pointer: copyPointer(resolved.pointer),
26997
+ ...resolved.manifest.title === void 0 ? {} : { title: resolved.manifest.title },
26998
+ requires: [...resolved.manifest.requires],
26999
+ optional: [...resolved.manifest.optional ?? []],
27000
+ archetypes: resolved.manifest.archetypes.map((archetype) => ({
27001
+ slug: archetype.slug,
27002
+ convention: archetype.convention,
27003
+ params: [...archetype.params]
27004
+ }))
26945
27005
  });
26946
27006
  const previous = this.records.get(record3.id);
26947
27007
  this.records.set(record3.id, record3);
@@ -27339,7 +27399,7 @@ function createPajaIntentTargetOptions(getState, getContext, effects = {}) {
27339
27399
  if (!source || originRegistry.getWindowId(source) !== tab.windowId) {
27340
27400
  throw new Error("intent target source is no longer registered");
27341
27401
  }
27342
- createPajaPostMessageProxy(source, state, tab.windowId).postMessage({
27402
+ originRegistry.postToNapplet(tab.windowId, {
27343
27403
  type: "intent.deliver",
27344
27404
  delivery: {
27345
27405
  sender: params.sender,
@@ -27348,7 +27408,7 @@ function createPajaIntentTargetOptions(getState, getContext, effects = {}) {
27348
27408
  convention: params.convention,
27349
27409
  ...params.payload === void 0 ? {} : { payload: params.payload }
27350
27410
  }
27351
- }, "*");
27411
+ });
27352
27412
  }
27353
27413
  };
27354
27414
  }
@@ -27453,6 +27513,192 @@ function clearRuntimeTabGeneration(tab, runtime) {
27453
27513
  }
27454
27514
  }
27455
27515
 
27516
+ // src/browser-nip5d-host.ts
27517
+ var LAUNCHER_MESSAGE_TYPES = /* @__PURE__ */ new Set(["paja.intent.launcher.ready", "paja.intent.launcher.result"]);
27518
+ function messageType(data) {
27519
+ return typeof data === "object" && data !== null && typeof data.type === "string" ? data.type : void 0;
27520
+ }
27521
+ function findLauncher(context, windowId) {
27522
+ return [...context.runtime.launcherFrames.values()].find((entry) => entry.windowId === windowId);
27523
+ }
27524
+ function handlePajaWindowMessage(state, context, event) {
27525
+ const source = event.source;
27526
+ if (!source) return;
27527
+ const { runtime } = context;
27528
+ const sourceTab = state.tabs.find((tab) => tab.frame.contentWindow === source) ?? null;
27529
+ const launcher = runtime.launcherFrames.get(source);
27530
+ const isSingleFrameMessage = context.frame ? source === context.frame.contentWindow : false;
27531
+ if (!sourceTab && !isSingleFrameMessage && !launcher) return;
27532
+ const type = messageType(event.data);
27533
+ if (launcher && type && LAUNCHER_MESSAGE_TYPES.has(type)) {
27534
+ if (originRegistry.getWindowId(source) !== launcher.windowId || !originRegistry.getPort(launcher.windowId)) return;
27535
+ appendPajaMessageLog(state, "napplet->shell", event.data, launcher.windowId);
27536
+ if (type === "paja.intent.launcher.ready") {
27537
+ launcher.ready();
27538
+ return;
27539
+ }
27540
+ const data = event.data;
27541
+ if (typeof data.correlation === "string") launcher.result(data.correlation, data.result);
27542
+ return;
27543
+ }
27544
+ appendPajaMessageLog(state, "napplet->shell", event.data, originRegistry.getWindowId(source) ?? void 0);
27545
+ context.bridge.handleMessage(event);
27546
+ }
27547
+ function observePajaNappletMessage(state, context, windowId, message3, effects) {
27548
+ appendPajaMessageLog(state, "napplet->shell", message3, windowId);
27549
+ if (!state || !context || message3.type !== "shell.ready") return;
27550
+ const launcher = findLauncher(context, windowId);
27551
+ if (launcher) {
27552
+ launcher.ready();
27553
+ return;
27554
+ }
27555
+ const tab = state.tabs.find((candidate) => candidate.windowId === windowId);
27556
+ if (tab) {
27557
+ const source = tab.frame.contentWindow;
27558
+ if (source) {
27559
+ markRuntimeTabReady(state, context, tab, source, originRegistry.getWindowId(source) ?? null, {
27560
+ setReadyStatus: (current) => effects.setStatus(current, "ready")
27561
+ });
27562
+ }
27563
+ return;
27564
+ }
27565
+ if (windowId === context.runtime.currentWindowId) {
27566
+ context.runtime.readyWindowIds.add(windowId);
27567
+ effects.setStatus(state, "ready");
27568
+ }
27569
+ }
27570
+ function handlePajaNappletRevoked(state, context, revocation, effects) {
27571
+ const { windowId, reason, detail } = revocation;
27572
+ appendPajaMessageLog(state, "paja", { type: "paja.napplet.revoked", reason, detail }, windowId);
27573
+ if (!state || !context) return;
27574
+ const { runtime } = context;
27575
+ for (const [source, launcher] of runtime.launcherFrames) {
27576
+ if (launcher.windowId !== windowId) continue;
27577
+ runtime.launcherFrames.delete(source);
27578
+ runtime.intentSenderIds.delete(windowId);
27579
+ runtime.explicitIntentHandlers.delete(windowId);
27580
+ launcher.frame.remove();
27581
+ return;
27582
+ }
27583
+ if (replaceRevokedRuntimeTabFrame(state, context, windowId)) return;
27584
+ if (context.frame && windowId === runtime.currentWindowId) {
27585
+ runtime.readyWindowIds.delete(windowId);
27586
+ runtime.currentWindowId = null;
27587
+ const fresh = ensureFreshNappletFrame(context.frame);
27588
+ if (fresh !== context.frame) {
27589
+ fresh.addEventListener("error", () => effects.setStatus(state, "error"));
27590
+ context.frame = fresh;
27591
+ }
27592
+ effects.setStatus(state, "error");
27593
+ }
27594
+ }
27595
+
27596
+ // src/browser-local-loader.ts
27597
+ async function loadLocalRuntimeFile(state, context, file, effects) {
27598
+ if (context.config.target.mode !== "runtime-pointer") return;
27599
+ const fileName = file.name;
27600
+ context.setPointerStatus(state, `reading ${fileName}`);
27601
+ context.setStatus(state, "booting");
27602
+ appendPajaMessageLog(state, "paja", { type: "paja.local.load", fileName });
27603
+ try {
27604
+ const target = await createPajaLocalTarget(file);
27605
+ const identityStatus = `local ${target.dTag}:${target.aggregateHash.slice(0, 12)}`;
27606
+ const loadedStatus = target.relativeAssets.length > 0 ? `${identityStatus}; ${target.relativeAssets.length} relative asset(s) will not load. ${PAJA_LOCAL_SINGLE_FILE_HINT}` : identityStatus;
27607
+ context.setPointerStatus(state, loadedStatus);
27608
+ appendPajaMessageLog(state, "paja", {
27609
+ type: "paja.local.loaded",
27610
+ fileName: target.fileName,
27611
+ dTag: target.dTag,
27612
+ aggregateHash: target.aggregateHash,
27613
+ ...target.relativeAssets.length > 0 ? { relativeAssets: [...target.relativeAssets] } : {}
27614
+ });
27615
+ const key = resolvedTargetKey(target);
27616
+ const duplicate = state.tabs.find((tab2) => tab2.key === key);
27617
+ if (duplicate) {
27618
+ const choice = await showDuplicatePointerDialog();
27619
+ if (choice === "cancel") {
27620
+ context.setStatus(state, getActiveTab(state)?.status ?? "ready");
27621
+ context.setPointerStatus(state, `already running: ${duplicate.title}`);
27622
+ appendPajaMessageLog(state, "paja", { type: "paja.local.duplicate.cancelled", tabId: duplicate.id });
27623
+ return;
27624
+ }
27625
+ if (choice === "open-tab") {
27626
+ activateRuntimeTab(state, context, duplicate.id);
27627
+ effects.persistTabs(state);
27628
+ appendPajaMessageLog(state, "paja", { type: "paja.local.duplicate.opened", tabId: duplicate.id });
27629
+ return;
27630
+ }
27631
+ }
27632
+ const tab = addRuntimeTab(state, context, "", target);
27633
+ tab.pointerStatus = loadedStatus;
27634
+ context.setPointerStatus(state, loadedStatus);
27635
+ effects.persistTabs(state);
27636
+ } catch (error) {
27637
+ const message3 = error instanceof Error ? error.message : String(error);
27638
+ context.setPointerStatus(state, message3);
27639
+ context.setStatus(state, getActiveTab(state)?.status ?? "error");
27640
+ appendPajaMessageLog(state, "paja", { type: "paja.local.error", fileName, error: message3 });
27641
+ }
27642
+ }
27643
+ function pickLocalHtmlFile(files) {
27644
+ const list = Array.from(files);
27645
+ return list.find((file) => isPajaLocalHtmlFile(file)) ?? list[0] ?? null;
27646
+ }
27647
+ function installLocalFileControls(load) {
27648
+ const input = document.getElementById("runtime-local-file");
27649
+ const open = document.getElementById("runtime-local-open");
27650
+ const stage = document.getElementById("napplet-stage");
27651
+ if (!(input instanceof HTMLInputElement) || !(open instanceof HTMLButtonElement)) return disposeNothing;
27652
+ let dragDepth = 0;
27653
+ const setDropActive = (active) => stage?.classList.toggle("drop-active", active);
27654
+ const carriesFiles = (event) => event.dataTransfer?.types.includes("Files") === true;
27655
+ const onOpen = () => input.click();
27656
+ const onChange = () => {
27657
+ const file = pickLocalHtmlFile(input.files ?? []);
27658
+ input.value = "";
27659
+ if (file) void load(file);
27660
+ };
27661
+ const onDragEnter = (event) => {
27662
+ if (!carriesFiles(event)) return;
27663
+ dragDepth += 1;
27664
+ setDropActive(true);
27665
+ };
27666
+ const onDragOver = (event) => {
27667
+ if (!carriesFiles(event)) return;
27668
+ event.preventDefault();
27669
+ if (event.dataTransfer) event.dataTransfer.dropEffect = "copy";
27670
+ };
27671
+ const onDragLeave = (event) => {
27672
+ if (!carriesFiles(event)) return;
27673
+ dragDepth = Math.max(0, dragDepth - 1);
27674
+ if (dragDepth === 0) setDropActive(false);
27675
+ };
27676
+ const onDrop = (event) => {
27677
+ if (!carriesFiles(event)) return;
27678
+ event.preventDefault();
27679
+ dragDepth = 0;
27680
+ setDropActive(false);
27681
+ const file = pickLocalHtmlFile(event.dataTransfer?.files ?? []);
27682
+ if (file) void load(file);
27683
+ };
27684
+ open.addEventListener("click", onOpen);
27685
+ input.addEventListener("change", onChange);
27686
+ document.addEventListener("dragenter", onDragEnter);
27687
+ document.addEventListener("dragover", onDragOver);
27688
+ document.addEventListener("dragleave", onDragLeave);
27689
+ document.addEventListener("drop", onDrop);
27690
+ return () => {
27691
+ open.removeEventListener("click", onOpen);
27692
+ input.removeEventListener("change", onChange);
27693
+ document.removeEventListener("dragenter", onDragEnter);
27694
+ document.removeEventListener("dragover", onDragOver);
27695
+ document.removeEventListener("dragleave", onDragLeave);
27696
+ document.removeEventListener("drop", onDrop);
27697
+ };
27698
+ }
27699
+ function disposeNothing() {
27700
+ }
27701
+
27456
27702
  // src/theme-broadcast.ts
27457
27703
  function createPajaThemeBroadcastLink() {
27458
27704
  let attachedBridge;
@@ -28390,7 +28636,19 @@ async function launchPajaSharedIntent(state, context, intent, progress, setPoint
28390
28636
  frame.remove();
28391
28637
  };
28392
28638
  try {
28393
- const registered = await context.navigateFrame(frame, context.config, state.generation + 1, context.adapter, launcher, windowId);
28639
+ const registered = await context.navigateFrame(
28640
+ frame,
28641
+ context.config,
28642
+ state.generation + 1,
28643
+ context.adapter,
28644
+ launcher,
28645
+ windowId,
28646
+ void 0,
28647
+ // NIP-5D: a second load of the launcher frame revokes its binding.
28648
+ (registeredWindowId) => {
28649
+ if (registeredWindowId) context.bridge.observeFrame(frame, registeredWindowId);
28650
+ }
28651
+ );
28394
28652
  if (registered !== windowId) throw new Error("Paja intent launcher registration failed");
28395
28653
  const timeout = window.setTimeout(() => readyReject(new Error("Paja intent launcher did not become ready")), 1e4);
28396
28654
  try {
@@ -28935,8 +29193,13 @@ function getFrame() {
28935
29193
  return frame;
28936
29194
  }
28937
29195
  function startFrameNavigation(state, context) {
28938
- const { config, frame, bridge, adapter, runtime } = context;
28939
- if (!frame) return;
29196
+ const { config, bridge, adapter, runtime } = context;
29197
+ if (!context.frame) return;
29198
+ const frame = ensureFreshNappletFrame(context.frame);
29199
+ if (frame !== context.frame) {
29200
+ frame.addEventListener("error", () => setStatus(state, "error"));
29201
+ context.frame = frame;
29202
+ }
28940
29203
  const generation2 = state.generation;
28941
29204
  const isCurrentGeneration = () => state.generation === generation2;
28942
29205
  void navigateFrame(
@@ -28948,6 +29211,7 @@ function startFrameNavigation(state, context) {
28948
29211
  void 0,
28949
29212
  isCurrentGeneration,
28950
29213
  (windowId) => {
29214
+ if (windowId) bridge.observeFrame(frame, windowId);
28951
29215
  if (isCurrentGeneration()) runtime.currentWindowId = windowId;
28952
29216
  }
28953
29217
  ).then((windowId) => {
@@ -29294,7 +29558,7 @@ async function installPajaHost() {
29294
29558
  ...identity,
29295
29559
  consentScope: target ? `${isPajaLocalTarget(target) ? "local-file" : target.manifest.catalogId}:artifact:${target.aggregateHash}` : pajaDevelopmentConsentScope(config.target.url, windowId ?? ""),
29296
29560
  isCurrent: () => {
29297
- const targetFrame = tab?.frame ?? frame;
29561
+ const targetFrame = tab?.frame ?? contextRef?.frame ?? frame;
29298
29562
  return !!targetFrame?.contentWindow && originRegistry.getWindowId(targetFrame.contentWindow) === windowId && (!tab || stateRef?.tabs.includes(tab) === true);
29299
29563
  }
29300
29564
  };
@@ -29356,6 +29620,13 @@ async function installPajaHost() {
29356
29620
  relayEventCounts.recordRead(request.reason, request.relayUrls, request.origin, request.authors);
29357
29621
  });
29358
29622
  await adapter.ready;
29623
+ const nip5dEffects = { setStatus };
29624
+ adapter.onNappletMessage = (windowId, message3) => {
29625
+ observePajaNappletMessage(stateRef, contextRef, windowId, message3, nip5dEffects);
29626
+ };
29627
+ adapter.onNappletRevoked = (revocation) => {
29628
+ handlePajaNappletRevoked(stateRef, contextRef, revocation, nip5dEffects);
29629
+ };
29359
29630
  const bridge = createShellBridge(adapter);
29360
29631
  const stopIdentityChanges = signerController.subscribe(() => {
29361
29632
  confirmationController.cancelSignerRequests();
@@ -29408,48 +29679,7 @@ async function installPajaHost() {
29408
29679
  window.addEventListener("pagehide", resourceSettings.dispose, { once: true });
29409
29680
  window.addEventListener("pagehide", llm.dispose, { once: true });
29410
29681
  window.__KEHTO_PAJA__ = state;
29411
- window.addEventListener("message", (event) => {
29412
- const source = event.source;
29413
- const sourceTab = source ? state.tabs.find((tab) => tab.frame.contentWindow === source) ?? null : null;
29414
- const launcher = source ? runtime.launcherFrames.get(source) : void 0;
29415
- const isSingleFrameMessage = frame ? event.source === frame.contentWindow : false;
29416
- if (!sourceTab && !isSingleFrameMessage && !launcher) return;
29417
- const registeredWindowId = source ? originRegistry.getWindowId(source) ?? null : null;
29418
- const sourceWindowId = launcher?.windowId ?? sourceTab?.windowId ?? registeredWindowId ?? void 0;
29419
- if (launcher && (!source || registeredWindowId !== launcher.windowId)) return;
29420
- if (sourceTab && (!source || !sourceWindowId || registeredWindowId !== sourceWindowId)) return;
29421
- if (isSingleFrameMessage && (!sourceWindowId || sourceWindowId !== runtime.currentWindowId)) return;
29422
- appendPajaMessageLog(state, "napplet->shell", event.data, sourceWindowId);
29423
- const proxiedSource = createPajaPostMessageProxy(event.source, state, sourceWindowId);
29424
- const syntheticEvent = new Proxy(event, {
29425
- get(target, prop) {
29426
- if (prop === "source") return proxiedSource;
29427
- const val = Reflect.get(target, prop, target);
29428
- return typeof val === "function" ? val.bind(target) : val;
29429
- }
29430
- });
29431
- bridge.handleMessage(syntheticEvent);
29432
- const data = event.data;
29433
- if (data && typeof data === "object" && data.type === "shell.ready") {
29434
- if (launcher) launcher.ready();
29435
- if (sourceTab) {
29436
- if (source && !markRuntimeTabReady(
29437
- state,
29438
- context,
29439
- sourceTab,
29440
- source,
29441
- registeredWindowId,
29442
- { setReadyStatus: (current) => setStatus(current, "ready") }
29443
- )) return;
29444
- } else {
29445
- if (sourceWindowId) runtime.readyWindowIds.add(sourceWindowId);
29446
- setStatus(state, "ready");
29447
- }
29448
- }
29449
- if (launcher && data && typeof data === "object" && data.type === "paja.intent.launcher.result" && typeof data.correlation === "string") {
29450
- launcher.result(data.correlation, data.result);
29451
- }
29452
- });
29682
+ window.addEventListener("message", (event) => handlePajaWindowMessage(state, context, event));
29453
29683
  frame?.addEventListener("error", () => {
29454
29684
  setStatus(state, "error");
29455
29685
  });