@kehto/paja 0.20.0 → 0.21.0

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.
@@ -5262,6 +5262,7 @@ function handleStorageNap(windowId, msg, sendToNapplet, sessionRegistry2, aclSta
5262
5262
  }
5263
5263
  function createRuntimeDomainHandlers(context) {
5264
5264
  return {
5265
+ gamepad: (windowId, msg) => handleServiceOnlyMessage(context, "gamepad", windowId, msg),
5265
5266
  storage: (windowId, msg) => handleStorageMessage(context, windowId, msg),
5266
5267
  media: (windowId, msg) => handleMediaMessage(context, windowId, msg),
5267
5268
  keys: (windowId, msg) => handleKeysMessage(context, windowId, msg),
@@ -5410,6 +5411,7 @@ function createNapEnvelopeDispatcher(handlers) {
5410
5411
  const adapt = (handler) => (msg) => {
5411
5412
  if (currentWindowId !== null) handler(currentWindowId, msg);
5412
5413
  };
5414
+ napDispatch.registerNap("gamepad", adapt(handlers.gamepad));
5413
5415
  napDispatch.registerNap("relay", adapt(handlers.relay));
5414
5416
  napDispatch.registerNap("identity", adapt(handlers.identity));
5415
5417
  napDispatch.registerNap("count", adapt(handlers.count));
@@ -5551,7 +5553,7 @@ function createDenialResponse(envelope, error) {
5551
5553
  }
5552
5554
  function createMessageHandler(hooks, sessionRegistry2, enforceNap, dispatchNapEnvelope, firewallGate) {
5553
5555
  return (windowId, msg) => {
5554
- if (typeof msg !== "object" || msg === null || !("type" in msg)) return;
5556
+ if (typeof msg !== "object" || msg === null || Array.isArray(msg) || !("type" in msg) || typeof msg.type !== "string") return;
5555
5557
  const envelope = msg;
5556
5558
  const dotIdx = envelope.type.indexOf(".");
5557
5559
  if (dotIdx === -1) return;
@@ -5637,8 +5639,8 @@ function createRuntimeInstance(context) {
5637
5639
  try {
5638
5640
  if (isDomainAllowed && !isDomainAllowed(windowId, domain)) return false;
5639
5641
  const { recipientCap } = resolveCapabilitiesNap(message2);
5640
- if (!recipientCap) return false;
5641
- if (!aclState.check("", entry.dTag, entry.aggregateHash, recipientCap)) {
5642
+ if (!recipientCap && message2.type !== "gamepad.state") return false;
5643
+ if (recipientCap && !aclState.check("", entry.dTag, entry.aggregateHash, recipientCap)) {
5642
5644
  return false;
5643
5645
  }
5644
5646
  sendToNapplet(windowId, message2);
@@ -12328,6 +12330,169 @@ function createFsService(options) {
12328
12330
  }
12329
12331
  };
12330
12332
  }
12333
+ var SUBSCRIBE_WINDOW_MS = 1e3;
12334
+ var MAX_SUBSCRIPTIONS_PER_WINDOW = 32;
12335
+ function clamp(value, minimum, maximum) {
12336
+ return Number.isFinite(value) ? Math.max(minimum, Math.min(maximum, value)) : 0;
12337
+ }
12338
+ function readSample(read) {
12339
+ if (!read) return { available: false, reason: "unavailable", pads: [] };
12340
+ try {
12341
+ return {
12342
+ available: true,
12343
+ pads: Array.from(read(), (pad3) => !pad3?.connected ? null : {
12344
+ index: pad3.index,
12345
+ id: pad3.id,
12346
+ mapping: pad3.mapping,
12347
+ connected: true,
12348
+ timestamp: Number.isFinite(pad3.timestamp) ? pad3.timestamp : 0,
12349
+ axes: Array.from(pad3.axes, (axis) => clamp(axis, -1, 1)),
12350
+ buttons: Array.from(pad3.buttons, (button2) => ({
12351
+ value: clamp(button2.value, 0, 1),
12352
+ pressed: button2.pressed,
12353
+ touched: button2.touched ?? button2.pressed
12354
+ }))
12355
+ })
12356
+ };
12357
+ } catch (error) {
12358
+ const blocked = typeof error === "object" && error !== null && "name" in error && error.name === "SecurityError";
12359
+ if (!blocked) throw error;
12360
+ return { available: false, reason: "blocked", pads: [] };
12361
+ }
12362
+ }
12363
+ function padsFor(sample, focused) {
12364
+ return sample.pads.map((pad3) => pad3 === null ? null : {
12365
+ index: pad3.index,
12366
+ id: pad3.id,
12367
+ mapping: pad3.mapping,
12368
+ connected: true,
12369
+ timestamp: focused ? pad3.timestamp : 0,
12370
+ axes: pad3.axes.map((axis) => focused ? axis : 0),
12371
+ buttons: pad3.buttons.map((button2) => focused ? { ...button2 } : { value: 0, pressed: false, touched: false })
12372
+ });
12373
+ }
12374
+ function createGamepadService(options = {}) {
12375
+ const recipients = /* @__PURE__ */ new Map();
12376
+ const changes = /* @__PURE__ */ new Map();
12377
+ const now2 = options.now ?? Date.now;
12378
+ let context;
12379
+ let frame;
12380
+ let generation = 0;
12381
+ let detach;
12382
+ let closed = false;
12383
+ let sample = { available: false, reason: "unavailable", pads: [] };
12384
+ function cancel() {
12385
+ generation += 1;
12386
+ if (frame !== void 0) options.cancelFrame?.(frame);
12387
+ frame = void 0;
12388
+ }
12389
+ function schedule() {
12390
+ if (closed || recipients.size === 0 || !sample.available || frame !== void 0 || !options.requestFrame) return;
12391
+ const scheduled = ++generation;
12392
+ frame = options.requestFrame(() => {
12393
+ if (scheduled !== generation) return;
12394
+ frame = void 0;
12395
+ refresh();
12396
+ });
12397
+ }
12398
+ function deliver(windowId, recipient, force = false) {
12399
+ const focused = sample.available && (options.isHostActive?.() ?? true) && options.getFocusedWindow?.() === windowId;
12400
+ const message2 = { type: "gamepad.state", ...sample, focused, pads: padsFor(sample, focused) };
12401
+ const signature = JSON.stringify(message2);
12402
+ if (!force && signature === recipient.previous) return;
12403
+ recipient.previous = signature;
12404
+ if (context) {
12405
+ if (!context.sendToEligibleNapplet(windowId, message2)) recipients.delete(windowId);
12406
+ } else recipient.send(message2);
12407
+ }
12408
+ function refresh() {
12409
+ if (closed || recipients.size === 0) return;
12410
+ sample = readSample(options.readGamepads);
12411
+ const current = [...recipients];
12412
+ for (const [windowId, recipient] of current) {
12413
+ if (recipients.get(windowId) === recipient) deliver(windowId, recipient);
12414
+ }
12415
+ if (recipients.size === 0 || !sample.available) cancel();
12416
+ schedule();
12417
+ }
12418
+ function unsubscribe(windowId) {
12419
+ recipients.delete(windowId);
12420
+ if (recipients.size === 0) cancel();
12421
+ }
12422
+ function allowSubscribe(windowId) {
12423
+ const time = now2();
12424
+ let bucket = changes.get(windowId);
12425
+ if (!bucket || time < bucket.start || time - bucket.start >= SUBSCRIBE_WINDOW_MS) {
12426
+ bucket = { start: time, count: 0 };
12427
+ changes.set(windowId, bucket);
12428
+ }
12429
+ bucket.count += 1;
12430
+ return bucket.count <= MAX_SUBSCRIPTIONS_PER_WINDOW;
12431
+ }
12432
+ return {
12433
+ descriptor: { name: "gamepad", version: "1.0.0", description: "NAP-GAMEPAD focus-scoped controller snapshots" },
12434
+ refresh,
12435
+ onRegistered(runtime) {
12436
+ context = runtime;
12437
+ closed = false;
12438
+ detach?.();
12439
+ detach = options.subscribeChanges?.(refresh);
12440
+ },
12441
+ onUnregistered() {
12442
+ closed = true;
12443
+ cancel();
12444
+ detach?.();
12445
+ detach = void 0;
12446
+ recipients.clear();
12447
+ changes.clear();
12448
+ context = void 0;
12449
+ },
12450
+ handleMessage(windowId, message2, send) {
12451
+ if (closed || !message2 || typeof message2 !== "object" || Array.isArray(message2) || "id" in message2) return;
12452
+ if (message2.type === "gamepad.unsubscribe") {
12453
+ unsubscribe(windowId);
12454
+ return;
12455
+ }
12456
+ if (message2.type !== "gamepad.subscribe" || !allowSubscribe(windowId)) return;
12457
+ const recipient = recipients.get(windowId) ?? { send };
12458
+ recipients.set(windowId, recipient);
12459
+ sample = readSample(options.readGamepads);
12460
+ deliver(windowId, recipient, true);
12461
+ schedule();
12462
+ },
12463
+ onWindowDestroyed(windowId) {
12464
+ unsubscribe(windowId);
12465
+ changes.delete(windowId);
12466
+ }
12467
+ };
12468
+ }
12469
+ function browserGamepadOptions(host, resolveWindow = () => void 0) {
12470
+ if (!host) return {};
12471
+ const doc = host.document;
12472
+ const nav = host.navigator;
12473
+ return {
12474
+ readGamepads: typeof nav.getGamepads === "function" ? () => nav.getGamepads() : void 0,
12475
+ getFocusedWindow: () => {
12476
+ const active = doc.activeElement;
12477
+ if (!active || active.tagName !== "IFRAME") return null;
12478
+ const target = active.contentWindow;
12479
+ return target ? resolveWindow(target) ?? null : null;
12480
+ },
12481
+ isHostActive: () => doc.visibilityState !== "hidden" && doc.hasFocus(),
12482
+ requestFrame: typeof host.requestAnimationFrame === "function" ? (callback) => host.requestAnimationFrame(callback) : void 0,
12483
+ cancelFrame: (frame) => host.cancelAnimationFrame(frame),
12484
+ subscribeChanges(refresh) {
12485
+ const windowEvents = ["focus", "blur", "gamepadconnected", "gamepaddisconnected"];
12486
+ const documentEvents = ["focusin", "focusout", "visibilitychange"];
12487
+ for (const type of windowEvents) host.addEventListener(type, refresh);
12488
+ for (const type of documentEvents) doc.addEventListener(type, refresh);
12489
+ return () => {
12490
+ for (const type of windowEvents) host.removeEventListener(type, refresh);
12491
+ for (const type of documentEvents) doc.removeEventListener(type, refresh);
12492
+ };
12493
+ }
12494
+ };
12495
+ }
12331
12496
 
12332
12497
  // src/simulation.ts
12333
12498
  var PajaSimulationError = class extends Error {
@@ -12337,6 +12502,8 @@ var PajaSimulationError = class extends Error {
12337
12502
  }
12338
12503
  };
12339
12504
  var PAJA_SIMULATION_DOMAINS = [
12505
+ "shell",
12506
+ "gamepad",
12340
12507
  "relay",
12341
12508
  "outbox",
12342
12509
  "storage",
@@ -13854,6 +14021,7 @@ var audioManager = {
13854
14021
  }
13855
14022
  };
13856
14023
  var RUNTIME_NATIVE_DOMAINS = [
14024
+ "shell",
13857
14025
  "relay",
13858
14026
  "identity",
13859
14027
  "storage",
@@ -13878,7 +14046,8 @@ var SERVICE_ONLY_DOMAINS = [
13878
14046
  "webrtc",
13879
14047
  "dm",
13880
14048
  "count",
13881
- "fs"
14049
+ "fs",
14050
+ "gamepad"
13882
14051
  ];
13883
14052
  function buildShellCapabilities(hooks) {
13884
14053
  const disabled = new Set(hooks.capabilities?.disabledDomains ?? []);
@@ -13972,14 +14141,21 @@ function handleShellReady({
13972
14141
  if (state.initSent.get(sourceWindow) === sourceRegistrationId) {
13973
14142
  return;
13974
14143
  }
13975
- const identity = resolveNip5dIdentity(hooks, windowId, sourceWindow);
13976
- if (!identity) return;
13977
- registerNip5dSessionIfNeeded({ origin, runtime, state, sourceRegistrationId, windowId, identity });
13978
- const environment = originRegistry.getEnvironment(sourceWindow) ?? resolveShellEnvironment(hooks, identity);
13979
- state.environments.set(windowId, environment);
14144
+ const environment = registerSourceSession({ hooks, origin, runtime, state, sourceRegistrationId, sourceWindow, windowId });
14145
+ if (!environment?.capabilities.domains.includes("shell")) return;
13980
14146
  postShellInit(sourceWindow, environment);
13981
14147
  state.initSent.set(sourceWindow, sourceRegistrationId);
13982
14148
  }
14149
+ function registerSourceSession(options) {
14150
+ const { hooks, origin, runtime, state, sourceRegistrationId, sourceWindow, windowId } = options;
14151
+ const identity = resolveNip5dIdentity(hooks, windowId, sourceWindow, runtime.sessionRegistry.getEntryByWindowId(windowId));
14152
+ if (!identity) return null;
14153
+ registerNip5dSessionIfNeeded({ origin, runtime, state, sourceRegistrationId, windowId, identity });
14154
+ const existing = state.environments.get(windowId);
14155
+ const environment = originRegistry.getEnvironment(sourceWindow) ?? existing ?? resolveShellEnvironment(hooks, identity);
14156
+ state.environments.set(windowId, environment);
14157
+ return environment;
14158
+ }
13983
14159
  function registerNip5dSessionIfNeeded({
13984
14160
  origin,
13985
14161
  runtime,
@@ -13994,9 +14170,14 @@ function registerNip5dSessionIfNeeded({
13994
14170
  return;
13995
14171
  }
13996
14172
  if (existing && previousRegistration !== void 0) {
14173
+ runtime.destroyWindow(windowId);
13997
14174
  runtime.sessionRegistry.unregister(windowId);
14175
+ state.environments.delete(windowId);
14176
+ }
14177
+ if (existing && previousRegistration === void 0) {
14178
+ state.sessionRegistration.set(windowId, sourceRegistrationId);
14179
+ return;
13998
14180
  }
13999
- if (existing && previousRegistration === void 0) return;
14000
14181
  const entry = {
14001
14182
  pubkey: "",
14002
14183
  windowId,
@@ -14011,7 +14192,7 @@ function registerNip5dSessionIfNeeded({
14011
14192
  runtime.sessionRegistry.register(windowId, entry);
14012
14193
  state.sessionRegistration.set(windowId, sourceRegistrationId);
14013
14194
  }
14014
- function resolveNip5dIdentity(hooks, windowId, sourceWindow) {
14195
+ function resolveNip5dIdentity(hooks, windowId, sourceWindow, existingSession) {
14015
14196
  const hookIdentity = hooks.onNip5dIframeCreate?.(windowId);
14016
14197
  if (hookIdentity !== null && hookIdentity !== void 0) {
14017
14198
  return Object.freeze({
@@ -14021,7 +14202,8 @@ function resolveNip5dIdentity(hooks, windowId, sourceWindow) {
14021
14202
  }
14022
14203
  const originIdentity = originRegistry.getIdentity(sourceWindow);
14023
14204
  if (!originIdentity) {
14024
- return null;
14205
+ if (existingSession?.provenance !== "nip-5d" || typeof existingSession.dTag !== "string" || typeof existingSession.aggregateHash !== "string") return null;
14206
+ return Object.freeze({ dTag: existingSession.dTag, aggregateHash: existingSession.aggregateHash });
14025
14207
  }
14026
14208
  return Object.freeze({
14027
14209
  dTag: originIdentity.dTag,
@@ -14082,6 +14264,15 @@ function createShellBridge(hooks) {
14082
14264
  }
14083
14265
  const msg = event.data;
14084
14266
  if (typeof msg !== "object" || msg === null || typeof msg.type !== "string") return;
14267
+ if (!registerSourceSession({
14268
+ hooks,
14269
+ origin: event.origin,
14270
+ runtime,
14271
+ state: shellReadyState,
14272
+ sourceRegistrationId: originRegistry.getRegistrationId(sourceWindow) ?? 0,
14273
+ sourceWindow,
14274
+ windowId
14275
+ })) return;
14085
14276
  if (msg.type === "shell.ready") {
14086
14277
  handleShellReady({
14087
14278
  hooks,
@@ -14119,6 +14310,11 @@ function createShellBridge(hooks) {
14119
14310
  }
14120
14311
  };
14121
14312
  }
14313
+ var CONTROLLER_FEATURES = ["gamepad", "hid", "usb"];
14314
+ function denyNappletControllerAccess(frame) {
14315
+ const remaining = (frame.getAttribute("allow") ?? "").split(";").map((entry) => entry.trim()).filter((entry) => entry && !CONTROLLER_FEATURES.some((feature) => entry === feature || entry.startsWith(`${feature} `)));
14316
+ frame.setAttribute("allow", [...remaining, ...CONTROLLER_FEATURES.map((feature) => `${feature} 'none'`)].join("; "));
14317
+ }
14122
14318
  function createIntentUriNormalizer() {
14123
14319
  const hasOwn2 = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
14124
14320
  const fail2 = (message2) => {
@@ -14309,7 +14505,7 @@ function scriptJson(value) {
14309
14505
  return JSON.stringify(value).replace(/</g, "\\u003c");
14310
14506
  }
14311
14507
  function renderNappletNamespacePrelude(options) {
14312
- const domains = uniqueBareDomains(["shell", ...options.domains]);
14508
+ const domains = uniqueBareDomains(options.domains);
14313
14509
  return `<script data-kehto-nip5d-injection>(${nappletNamespacePrelude.toString()})(${scriptJson(domains)}, (${createIntentUriNormalizer.toString()})());<\/script>`;
14314
14510
  }
14315
14511
  function injectNappletNamespacePrelude(html, options) {
@@ -14497,12 +14693,12 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
14497
14693
  }
14498
14694
  return Object.freeze(strings);
14499
14695
  }
14500
- function supports(domain) {
14501
- return typeof domain === "string" && environment?.capabilities.domains.includes(domain) === true;
14696
+ function supports2(domain) {
14697
+ return typeof domain === "string" && !!target.napplet && Object.prototype.hasOwnProperty.call(target.napplet, domain);
14502
14698
  }
14503
14699
  const shell2 = {
14504
14700
  ready: () => ready,
14505
- supports,
14701
+ supports: supports2,
14506
14702
  get services() {
14507
14703
  return environment?.services ?? emptyServices;
14508
14704
  },
@@ -15579,6 +15775,63 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
15579
15775
  })
15580
15776
  };
15581
15777
  }
15778
+ function makeGamepad() {
15779
+ let state = { available: true, focused: false, pads: [] };
15780
+ const handlers = /* @__PURE__ */ new Set();
15781
+ const copy = (value) => ({
15782
+ available: value.available,
15783
+ focused: value.focused,
15784
+ ...value.reason === void 0 ? {} : { reason: value.reason },
15785
+ pads: value.pads.map((pad3) => pad3 === null ? null : {
15786
+ index: pad3.index,
15787
+ id: pad3.id,
15788
+ mapping: pad3.mapping,
15789
+ connected: true,
15790
+ timestamp: pad3.timestamp,
15791
+ axes: [...pad3.axes],
15792
+ buttons: pad3.buttons.map(({ value: value2, pressed, touched }) => ({ value: value2, pressed, touched }))
15793
+ })
15794
+ });
15795
+ const numberIn = (value, min, max) => typeof value === "number" && Number.isFinite(value) && value >= min && value <= max;
15796
+ const valid = (value) => {
15797
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
15798
+ const candidate = value;
15799
+ if (typeof candidate.available !== "boolean" || typeof candidate.focused !== "boolean" || !Array.isArray(candidate.pads)) return false;
15800
+ if (candidate.available ? candidate.reason !== void 0 : candidate.focused || !["blocked", "unavailable"].includes(candidate.reason ?? "")) return false;
15801
+ return Array.from(candidate.pads).every((pad3) => {
15802
+ if (pad3 === null) return true;
15803
+ if (!pad3 || typeof pad3 !== "object" || !Number.isInteger(pad3.index) || pad3.index < 0 || typeof pad3.id !== "string" || typeof pad3.mapping !== "string" || pad3.connected !== true || !Number.isFinite(pad3.timestamp) || !Array.isArray(pad3.axes) || !Array.isArray(pad3.buttons)) return false;
15804
+ if (!candidate.focused && pad3.timestamp !== 0) return false;
15805
+ if (!Array.from(pad3.axes).every((axis) => numberIn(axis, -1, 1) && (candidate.focused || axis === 0))) return false;
15806
+ return Array.from(pad3.buttons).every((button2) => button2 && numberIn(button2.value, 0, 1) && typeof button2.pressed === "boolean" && typeof button2.touched === "boolean" && (candidate.focused || button2.value === 0 && !button2.pressed && !button2.touched));
15807
+ });
15808
+ };
15809
+ listen((event) => {
15810
+ if (!isParentMessage(event)) return;
15811
+ const incoming = event.data;
15812
+ if (!incoming || incoming.type !== "gamepad.state" || "id" in incoming || !valid(incoming)) return;
15813
+ state = copy(incoming);
15814
+ const snapshot = copy(state);
15815
+ const recipients = Array.from(handlers);
15816
+ for (const entry of recipients) if (handlers.has(entry)) entry.handler(copy(snapshot));
15817
+ });
15818
+ const api = {
15819
+ get available() {
15820
+ return state.available;
15821
+ },
15822
+ get focused() {
15823
+ return state.focused;
15824
+ },
15825
+ getGamepads: () => copy(state).pads,
15826
+ onChange(handler) {
15827
+ const entry = { handler };
15828
+ handlers.add(entry);
15829
+ return subscriptionHandle(() => handlers.delete(entry));
15830
+ }
15831
+ };
15832
+ post({ type: "gamepad.subscribe" });
15833
+ return api;
15834
+ }
15582
15835
  function makeDm() {
15583
15836
  const req = (type, payload) => request({ type, ...payload }, `${type}.result`, withoutEnvelope, { rejectOnError: false });
15584
15837
  return {
@@ -15625,7 +15878,8 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
15625
15878
  };
15626
15879
  }
15627
15880
  const intentDelivery = allowed2.has("intent") ? makeIntentDelivery() : void 0;
15628
- const shell = makeShell();
15881
+ const shell = allowed2.has("shell") ? makeShell() : void 0;
15882
+ let gamepad;
15629
15883
  let inc;
15630
15884
  let identity;
15631
15885
  let theme;
@@ -15648,9 +15902,10 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
15648
15902
  return intent;
15649
15903
  }
15650
15904
  function isProtectedDomain(domain) {
15651
- return domain === "shell" || domain === "inc" || domain === "identity" || domain === "theme" || domain === "intent";
15905
+ return domain === "gamepad" || domain === "shell" || domain === "inc" || domain === "identity" || domain === "theme" || domain === "intent";
15652
15906
  }
15653
15907
  function makeDomain(domain, existing) {
15908
+ if (domain === "gamepad") return gamepad ??= makeGamepad();
15654
15909
  if (domain === "shell") return shell;
15655
15910
  if (domain === "inc") return makeProtectedInc(existing);
15656
15911
  if (domain === "identity") return makeProtectedIdentity();
@@ -21172,6 +21427,9 @@ function createDevServices(backend, getSimulation, relayConfig, onThemeService,
21172
21427
  }
21173
21428
  }
21174
21429
  };
21430
+ if (getSimulation().capabilities.domains.gamepad) {
21431
+ services.gamepad = createGamepadService(browserGamepadOptions(typeof window === "undefined" ? void 0 : window, (target) => originRegistry.getWindowId(target)));
21432
+ }
21175
21433
  if (getSimulation().capabilities.domains.keys && typeof document !== "undefined") {
21176
21434
  services.keys = createKeysService({ listenerTarget: document });
21177
21435
  }
@@ -21580,6 +21838,7 @@ function registerFrameForGeneration(frame, config, generation, identity, environ
21580
21838
  return windowId;
21581
21839
  }
21582
21840
  async function navigateFrame(frame, config, generation, adapter, resolvedTarget, windowId, isCurrent, onRegistered) {
21841
+ denyNappletControllerAccess(frame);
21583
21842
  const identity = getTargetOriginIdentity(config, resolvedTarget);
21584
21843
  const environment = resolvePajaFrameEnvironment(adapter, identity);
21585
21844
  const domains = environment.capabilities.domains;
@@ -23142,6 +23401,7 @@ function createRuntimeTabFrame(tab, state, context) {
23142
23401
  frame.id = `napplet-frame-${tab.id}`;
23143
23402
  frame.className = "tab-panel";
23144
23403
  frame.title = `Napplet runtime target: ${tab.title}`;
23404
+ denyNappletControllerAccess(frame);
23145
23405
  frame.sandbox.add("allow-scripts");
23146
23406
  frame.sandbox.remove("allow-same-origin");
23147
23407
  frame.dataset.tabId = tab.id;
@@ -23732,6 +23992,21 @@ function createPajaThemeBroadcastLink() {
23732
23992
 
23733
23993
  // src/browser-host-storage.ts
23734
23994
  var PAJA_INTENT_DEFAULTS_STORAGE_KEY = "kehto.paja.intent-defaults.v1";
23995
+ var PAJA_INTENT_CATALOG_STORAGE_KEY = "kehto.paja.intent-catalog.v1";
23996
+ function readPajaIntentCatalogPointers() {
23997
+ try {
23998
+ const value = JSON.parse(window.localStorage.getItem(PAJA_INTENT_CATALOG_STORAGE_KEY) ?? "[]");
23999
+ return Array.isArray(value) ? value.filter((pointer) => typeof pointer === "string" && pointer.length > 0) : [];
24000
+ } catch {
24001
+ return [];
24002
+ }
24003
+ }
24004
+ function writePajaIntentCatalogPointers(pointers) {
24005
+ try {
24006
+ window.localStorage.setItem(PAJA_INTENT_CATALOG_STORAGE_KEY, JSON.stringify([...new Set(pointers)]));
24007
+ } catch {
24008
+ }
24009
+ }
23735
24010
  function runtimeTabsStorage(config) {
23736
24011
  if (config.target.mode !== "runtime-pointer") return null;
23737
24012
  try {
@@ -23957,193 +24232,139 @@ function createPajaIntentLink(descriptor, href) {
23957
24232
  }
23958
24233
 
23959
24234
  // src/browser-intent-links.ts
23960
- function createPajaIntentLinkReviewController(document2 = window.document, options = {}) {
24235
+ function createPajaIntentLinkController(document2 = window.document, options = {}) {
23961
24236
  const dialog = document2.getElementById("paja-intent-link-dialog");
23962
- const uri = document2.getElementById("paja-intent-link-uri");
23963
- const payload = document2.getElementById("paja-intent-link-payload");
23964
- const target = document2.getElementById("paja-intent-link-target");
23965
- const status = document2.getElementById("paja-intent-link-status");
24237
+ const title = document2.getElementById("paja-intent-link-title");
24238
+ const copy = document2.getElementById("paja-intent-link-copy");
24239
+ const apps = document2.getElementById("paja-intent-link-apps");
24240
+ const remember = document2.getElementById("paja-intent-link-save-default");
23966
24241
  const cancel = document2.getElementById("paja-intent-link-cancel");
23967
- const launch = document2.getElementById("paja-intent-link-launch");
24242
+ const notice = document2.getElementById("paja-intent-link-notice");
24243
+ const status = document2.getElementById("paja-intent-link-status");
23968
24244
  const retry = document2.getElementById("paja-intent-link-retry");
23969
- const choose2 = document2.getElementById("paja-intent-link-choose");
23970
- const handler = document2.getElementById("paja-intent-link-handler");
23971
- const useHandler = document2.getElementById("paja-intent-link-use-handler");
23972
- const saveDefault = document2.getElementById("paja-intent-link-save-default");
23973
- const clearDefault = document2.getElementById("paja-intent-link-clear-default");
23974
- if (!(dialog instanceof HTMLDialogElement) || !(uri instanceof HTMLInputElement) || !(payload instanceof HTMLTextAreaElement) || !(target instanceof HTMLElement) || !(status instanceof HTMLElement) || !(cancel instanceof HTMLButtonElement) || !(launch instanceof HTMLButtonElement) || !(retry instanceof HTMLButtonElement) || !(choose2 instanceof HTMLButtonElement) || !(handler instanceof HTMLSelectElement) || !(useHandler instanceof HTMLButtonElement) || !(saveDefault instanceof HTMLInputElement)) return null;
23975
- const clearDefaultButton = clearDefault instanceof HTMLButtonElement ? clearDefault : null;
23976
- let settle6 = null;
23977
- let trigger = null;
23978
- let pointer;
23979
- let forceChooser = false;
23980
- let run = null;
23981
- let chooseSettle = null;
23982
- let activeArchetype;
24245
+ const dismiss = document2.getElementById("paja-intent-link-dismiss");
24246
+ if (!(dialog instanceof HTMLDialogElement) || !(title instanceof HTMLElement) || !(copy instanceof HTMLElement) || !(apps instanceof HTMLElement) || !(remember instanceof HTMLInputElement) || !(cancel instanceof HTMLButtonElement) || !(notice instanceof HTMLElement) || !(status instanceof HTMLElement) || !(retry instanceof HTMLButtonElement) || !(dismiss instanceof HTMLButtonElement)) return null;
23983
24247
  let generation = 0;
23984
- let busy = false;
23985
- const isCurrent = (runGeneration) => generation === runGeneration && settle6 !== null;
23986
- const setBusy = (value) => {
23987
- busy = value;
23988
- launch.disabled = value;
23989
- retry.disabled = value || !run;
23990
- choose2.disabled = value;
23991
- };
23992
- const setTargetCopy = () => {
23993
- target.textContent = pointer ? "This link names one verified target. If it cannot satisfy this exact convention, choose another deliberately." : forceChooser ? "Choose a compatible handler deliberately. This launch will not use a saved default or recommendation." : "Paja will use your saved default, recommendation, or ask you to choose a compatible handler.";
23994
- };
23995
- const finish = () => {
23996
- generation += 1;
23997
- busy = false;
23998
- const done = settle6;
23999
- settle6 = null;
24000
- run = null;
24001
- chooseSettle?.(void 0);
24002
- chooseSettle = null;
24248
+ let run;
24249
+ let archetype = "";
24250
+ let settleChoice;
24251
+ let trigger = null;
24252
+ const closeChoice = (id) => {
24253
+ const settle6 = settleChoice;
24254
+ settleChoice = void 0;
24255
+ if (id && remember.checked) options.setDefault?.(archetype, id);
24003
24256
  if (dialog.open) dialog.close();
24004
24257
  trigger?.focus();
24005
24258
  trigger = null;
24006
- done?.();
24007
- };
24008
- const cancelReview = () => finish();
24009
- const chooseAnother = () => {
24010
- pointer = void 0;
24011
- forceChooser = true;
24012
- setTargetCopy();
24013
- status.textContent = "Choose another will open the compatible-handler chooser and bypass saved defaults.";
24014
- };
24015
- const retryReview = () => {
24016
- if (!busy) run?.();
24017
- };
24018
- const launchReview = () => {
24019
- if (!busy) run?.();
24020
- };
24021
- const useSelectedHandler = () => {
24022
- const settleChoice = chooseSettle;
24023
- chooseSettle = null;
24024
- handler.disabled = true;
24025
- useHandler.disabled = true;
24026
- settleChoice?.(handler.value || void 0);
24027
- };
24028
- const clearSavedDefault = () => {
24029
- if (!activeArchetype) return;
24030
- options.clearDefault?.(activeArchetype);
24031
- status.textContent = `Cleared the saved default for ${activeArchetype}.`;
24032
- };
24033
- cancel.addEventListener("click", cancelReview);
24034
- launch.addEventListener("click", launchReview);
24035
- retry.addEventListener("click", retryReview);
24036
- choose2.addEventListener("click", chooseAnother);
24037
- useHandler.addEventListener("click", useSelectedHandler);
24038
- clearDefaultButton?.addEventListener("click", clearSavedDefault);
24039
- dialog.addEventListener("cancel", cancelReview);
24259
+ settle6?.(id);
24260
+ };
24261
+ const cancelChoice = () => {
24262
+ closeChoice();
24263
+ generation += 1;
24264
+ notice.hidden = true;
24265
+ run = void 0;
24266
+ };
24267
+ const dismissNotice = () => {
24268
+ generation += 1;
24269
+ notice.hidden = true;
24270
+ run = void 0;
24271
+ closeChoice();
24272
+ };
24273
+ const retryLink = () => run?.();
24274
+ const showError = (_error) => {
24275
+ status.textContent = "Couldn\u2019t open this shared content. Try again, or ask the sender for a new link.";
24276
+ notice.hidden = false;
24277
+ retry.hidden = !run;
24278
+ };
24279
+ const choose2 = (heading, description, candidates) => {
24280
+ closeChoice();
24281
+ trigger = document2.activeElement instanceof HTMLElement ? document2.activeElement : null;
24282
+ title.textContent = heading;
24283
+ copy.textContent = description;
24284
+ remember.checked = false;
24285
+ apps.replaceChildren();
24286
+ for (const candidate of candidates) {
24287
+ const button2 = document2.createElement("button");
24288
+ button2.type = "button";
24289
+ button2.textContent = `Open with ${candidate.title}`;
24290
+ button2.addEventListener("click", () => closeChoice(candidate.id));
24291
+ apps.append(button2);
24292
+ }
24293
+ notice.hidden = true;
24294
+ const result2 = new Promise((resolve) => {
24295
+ settleChoice = resolve;
24296
+ });
24297
+ dialog.showModal();
24298
+ return result2;
24299
+ };
24300
+ cancel.addEventListener("click", cancelChoice);
24301
+ dialog.addEventListener("cancel", cancelChoice);
24302
+ dismiss.addEventListener("click", dismissNotice);
24303
+ retry.addEventListener("click", retryLink);
24040
24304
  return {
24041
- review(link, onLaunch) {
24042
- if (settle6) finish();
24043
- uri.value = link.uri;
24044
- pointer = link.pointer;
24045
- forceChooser = false;
24046
- payload.value = Object.hasOwn(link, "payload") ? JSON.stringify(link.payload) : "";
24047
- trigger = document2.activeElement instanceof HTMLElement ? document2.activeElement : null;
24048
- activeArchetype = link.request.archetype;
24049
- setTargetCopy();
24050
- status.textContent = "Review the URI and payload, then explicitly launch.";
24305
+ open(link, launch) {
24306
+ dismissNotice();
24307
+ archetype = link.request.archetype;
24051
24308
  run = () => {
24052
- if (busy) return;
24053
- const runGeneration = ++generation;
24054
- let review;
24055
- try {
24056
- const hasPayload = payload.value.trim().length > 0;
24057
- const parsedPayload = hasPayload ? JSON.parse(payload.value) : void 0;
24058
- const request = normalizeIntentUri(uri.value, {
24059
- ...hasPayload ? { payload: parsedPayload } : {},
24060
- ...forceChooser ? { handler: "choose" } : {}
24061
- });
24062
- if (pointer !== void 0 && request.handlerHint !== void 0) {
24063
- throw new TypeError("Paja intent link cannot combine a target pointer with a URI recommendation");
24064
- }
24065
- activeArchetype = request.archetype;
24066
- review = { uri: uri.value, ...pointer === void 0 ? {} : { pointer }, ...hasPayload ? { payload: parsedPayload } : {}, request };
24067
- } catch (error) {
24068
- if (isCurrent(runGeneration)) status.textContent = error instanceof Error ? error.message : "Intent link is invalid.";
24069
- return;
24070
- }
24071
- setBusy(true);
24072
- status.textContent = "Resolving verified handler policy\u2026";
24309
+ const current = ++generation;
24073
24310
  let terminal = false;
24311
+ let consumed = false;
24312
+ const isActive = () => current === generation;
24313
+ const consume = () => {
24314
+ if (!consumed) {
24315
+ consumed = true;
24316
+ options.onAccepted?.();
24317
+ }
24318
+ };
24319
+ status.textContent = "Opening shared content\u2026";
24320
+ notice.hidden = false;
24321
+ retry.hidden = true;
24074
24322
  const progress = {
24075
- isActive: () => isCurrent(runGeneration),
24076
- selectedTarget(title) {
24077
- if (!isCurrent(runGeneration)) return;
24078
- target.textContent = `Verified target: ${title}`;
24323
+ isActive,
24324
+ selectedTarget(name) {
24325
+ if (isActive() && !terminal) status.textContent = `Opening ${name}\u2026`;
24079
24326
  },
24327
+ chooseConflict: (saved, shared) => choose2(
24328
+ "Which app would you like to use?",
24329
+ `This link uses ${shared.title}. Your saved preference is ${saved.title}.`,
24330
+ [saved, shared]
24331
+ ),
24080
24332
  accepted() {
24081
- if (!isCurrent(runGeneration) || terminal) return;
24082
- status.textContent = "Accepted: delivery is queued and the target may still be loading.";
24333
+ if (isActive()) consume();
24083
24334
  },
24084
24335
  delivered() {
24085
- if (!isCurrent(runGeneration) || terminal) return;
24336
+ if (!isActive() || terminal) return;
24086
24337
  terminal = true;
24087
- status.textContent = "Delivered to the verified target.";
24088
- setBusy(false);
24338
+ consume();
24339
+ notice.hidden = true;
24340
+ run = void 0;
24089
24341
  },
24090
24342
  failed(error) {
24091
- if (!isCurrent(runGeneration) || terminal) return;
24092
- terminal = true;
24093
- status.textContent = `Delivery failed: ${error instanceof Error ? error.message : String(error)}`;
24094
- setBusy(false);
24343
+ if (isActive() && !terminal) {
24344
+ terminal = true;
24345
+ showError(error);
24346
+ }
24095
24347
  }
24096
24348
  };
24097
- void Promise.resolve().then(() => onLaunch(review, progress)).then(void 0, (error) => progress.failed(error));
24349
+ void Promise.resolve().then(() => launch(link, progress)).catch(progress.failed);
24098
24350
  };
24099
- setBusy(false);
24100
- dialog.showModal();
24101
- uri.focus();
24102
- return new Promise((resolve) => {
24103
- settle6 = resolve;
24104
- });
24105
- },
24106
- chooseHandler(archetype, candidates) {
24107
- if (chooseSettle) chooseSettle(void 0);
24108
- activeArchetype = archetype;
24109
- if (!dialog.open) {
24110
- trigger = document2.activeElement instanceof HTMLElement ? document2.activeElement : null;
24111
- pointer = void 0;
24112
- forceChooser = true;
24113
- uri.value = "";
24114
- payload.value = "";
24115
- setTargetCopy();
24116
- dialog.showModal();
24117
- }
24118
- handler.replaceChildren();
24119
- for (const candidate of candidates) {
24120
- const option = document2.createElement("option");
24121
- option.value = candidate.id;
24122
- option.textContent = candidate.title ?? candidate.id;
24123
- handler.append(option);
24124
- }
24125
- handler.disabled = candidates.length === 0;
24126
- useHandler.disabled = candidates.length === 0;
24127
- saveDefault.checked = false;
24128
- status.textContent = `Choose a compatible handler for ${archetype}.`;
24129
- return new Promise((resolve) => {
24130
- chooseSettle = resolve;
24131
- });
24351
+ run();
24132
24352
  },
24133
- consumeSaveDefault() {
24134
- const selected = saveDefault.checked;
24135
- saveDefault.checked = false;
24136
- return selected;
24353
+ chooseHandler(role, candidates) {
24354
+ archetype = role;
24355
+ return choose2(
24356
+ "Choose an app",
24357
+ "Open this shared content with:",
24358
+ candidates.map((candidate) => ({ id: candidate.id, title: candidate.title ?? "Untitled app" }))
24359
+ );
24137
24360
  },
24361
+ showError,
24138
24362
  dispose() {
24139
- cancel.removeEventListener("click", cancelReview);
24140
- launch.removeEventListener("click", launchReview);
24141
- retry.removeEventListener("click", retryReview);
24142
- choose2.removeEventListener("click", chooseAnother);
24143
- useHandler.removeEventListener("click", useSelectedHandler);
24144
- clearDefaultButton?.removeEventListener("click", clearSavedDefault);
24145
- dialog.removeEventListener("cancel", cancelReview);
24146
- finish();
24363
+ dismissNotice();
24364
+ cancel.removeEventListener("click", cancelChoice);
24365
+ dialog.removeEventListener("cancel", cancelChoice);
24366
+ dismiss.removeEventListener("click", dismissNotice);
24367
+ retry.removeEventListener("click", retryLink);
24147
24368
  }
24148
24369
  };
24149
24370
  }
@@ -24456,6 +24677,7 @@ Routing: ${targetDescription}`;
24456
24677
  appendIntentLinkBuilderOption(routing.control, "default", "Recipient default");
24457
24678
  appendIntentLinkBuilderOption(routing.control, "recommend", "Recommend this app", nextTarget.event.kind !== 35129 || !nextTarget.manifest.dTag);
24458
24679
  appendIntentLinkBuilderOption(routing.control, "exact", "Exact target pointer");
24680
+ routing.control.value = nextTarget.event.kind === 35129 && nextTarget.manifest.dTag ? "recommend" : "exact";
24459
24681
  appendIntentLinkBuilderOption(payloadMode.control, "text", "Text fields");
24460
24682
  appendIntentLinkBuilderOption(payloadMode.control, "json", "JSON payload");
24461
24683
  json.value = "";
@@ -24542,6 +24764,61 @@ Routing: ${targetDescription}`;
24542
24764
  };
24543
24765
  }
24544
24766
 
24767
+ // src/browser-intent-link-target.ts
24768
+ function supports(target, link) {
24769
+ const contracts = "manifest" in target ? target.manifest.archetypes : target.archetypes;
24770
+ return contracts.some((entry) => entry.slug === link.request.archetype && entry.convention === link.request.convention);
24771
+ }
24772
+ function permitted(context, target) {
24773
+ const identity = "manifest" in target ? { dTag: target.dTag, aggregateHash: target.aggregateHash, requires: target.manifest.requires, optional: target.manifest.optional } : target;
24774
+ return resolveShellEnvironment(context.adapter, identity).capabilities.domains.includes("intent");
24775
+ }
24776
+ async function recommended(context, link) {
24777
+ const hint2 = link.request.handlerHint;
24778
+ if (!hint2) return null;
24779
+ const installed = context.runtime.catalog.get(`nip5d:${hint2.address}`);
24780
+ if (installed && supports(installed, link)) return installed;
24781
+ const match = /^35129:([a-f0-9]{64}):(.+)$/.exec(hint2.address);
24782
+ if (!match) return null;
24783
+ const [, pubkey2, identifier] = match;
24784
+ try {
24785
+ const pointer = naddrEncode({ identifier, pubkey: pubkey2, kind: 35129, relays: [...hint2.relays ?? []] });
24786
+ const target = await resolvePajaPointer(pointer, pajaPointerResolverOptions(context));
24787
+ return target.event.kind === 35129 && target.event.pubkey === pubkey2 && target.manifest.dTag === identifier && supports(target, link) ? target : null;
24788
+ } catch {
24789
+ return null;
24790
+ }
24791
+ }
24792
+ async function resolvePajaSharedLinkHandler(context, link, progress) {
24793
+ if (link.request.handler === "choose") return void 0;
24794
+ const shared = link.pointer ? await resolvePajaPointer(link.pointer, pajaPointerResolverOptions(context)) : await recommended(context, link);
24795
+ if (!progress.isActive() || !shared) return void 0;
24796
+ if (!supports(shared, link) || !permitted(context, shared)) {
24797
+ if (link.pointer) throw new Error("The named app cannot open this shared content");
24798
+ return void 0;
24799
+ }
24800
+ const id = "manifest" in shared ? shared.manifest.catalogId : shared.id;
24801
+ const title = ("manifest" in shared ? shared.manifest.title : shared.title) ?? shared.dTag;
24802
+ const savedId = context.runtime.intentDefaults.get(link.request.archetype);
24803
+ const saved = savedId ? context.runtime.catalog.get(savedId) : void 0;
24804
+ let selected = id;
24805
+ let explicit = link.pointer !== void 0;
24806
+ if (!link.pointer && saved && saved.id !== id && supports(saved, link) && permitted(context, saved)) {
24807
+ const choice = await progress.chooseConflict(
24808
+ { id: saved.id, title: saved.title ?? saved.dTag },
24809
+ { id, title }
24810
+ );
24811
+ if (!progress.isActive()) return void 0;
24812
+ if (choice !== id && choice !== saved.id) throw new Error("App choice cancelled");
24813
+ selected = choice;
24814
+ explicit = true;
24815
+ }
24816
+ if (!progress.isActive()) return void 0;
24817
+ if (selected === id && "manifest" in shared) context.runtime.catalog.install(shared);
24818
+ progress.selectedTarget(selected === id ? title : saved.title ?? saved.dTag);
24819
+ return explicit ? selected : void 0;
24820
+ }
24821
+
24545
24822
  // src/intent-launcher.ts
24546
24823
  var LAUNCHER_HTML = `<!doctype html><meta charset="utf-8"><title>Paja intent launcher</title><script>let launched=false;addEventListener('message',(event)=>{if(launched||event.source!==parent)return;const data=event.data;if(!data||data.type!=='paja.intent.launch'||typeof data.uri!=='string'||typeof data.correlation!=='string')return;launched=true;window.napplet?.intent?.invoke(data.uri,data.options).then((result)=>parent.postMessage({type:'paja.intent.launcher.result',correlation:data.correlation,result},'*')).catch(()=>parent.postMessage({type:'paja.intent.launcher.result',correlation:data.correlation,result:{ok:false,error:'invoke rejected'}},'*'));});parent.postMessage({type:'paja.intent.launcher.ready'},'*');<\/script>`;
24547
24824
  var LAUNCHER_EVENT = {
@@ -24585,32 +24862,16 @@ function postPajaIntentLauncherMessage(frame, message2) {
24585
24862
  }
24586
24863
 
24587
24864
  // src/browser-intent-launcher-host.ts
24588
- async function launchPajaReviewedIntent(state, context, intent, progress, setPointerStatus2) {
24865
+ async function launchPajaSharedIntent(state, context, intent, progress, setPointerStatus2) {
24589
24866
  const { runtime } = context;
24590
- let explicitHandler;
24591
24867
  if (!progress.isActive()) return;
24592
- if (intent.pointer) {
24593
- const target = await resolvePajaPointer(intent.pointer, pajaPointerResolverOptions(context));
24594
- if (!progress.isActive()) return;
24595
- const exact = target.manifest.archetypes.some((contract) => contract.slug === intent.request.archetype && contract.convention === intent.request.convention);
24596
- if (!exact) throw new Error("The explicitly named napplet does not advertise this exact intent convention");
24597
- runtime.catalog.install(target);
24598
- progress.selectedTarget(target.manifest.title ?? target.manifest.dTag);
24599
- explicitHandler = target.manifest.catalogId;
24600
- }
24601
- if (intent.request.handlerHint && shouldResolveRecommendation(intent, runtime)) {
24602
- const target = await resolveRecommendedIntentTarget(context, intent.request.handlerHint, intent.request.archetype, intent.request.convention);
24603
- if (!progress.isActive()) return;
24604
- if (target) {
24605
- runtime.catalog.install(target);
24606
- progress.selectedTarget(target.manifest.title ?? target.manifest.dTag);
24607
- }
24608
- }
24868
+ const explicitHandler = await resolvePajaSharedLinkHandler(context, intent, progress);
24609
24869
  if (!progress.isActive()) return;
24610
24870
  const launcher = await resolvePajaIntentLauncher();
24611
24871
  if (!progress.isActive()) return;
24612
24872
  const frame = document.createElement("iframe");
24613
24873
  frame.hidden = true;
24874
+ denyNappletControllerAccess(frame);
24614
24875
  frame.sandbox.add("allow-scripts");
24615
24876
  frame.setAttribute("aria-hidden", "true");
24616
24877
  context.stage.append(frame);
@@ -24690,32 +24951,6 @@ async function launchPajaReviewedIntent(state, context, intent, progress, setPoi
24690
24951
  teardown();
24691
24952
  }
24692
24953
  }
24693
- function shouldResolveRecommendation(intent, runtime) {
24694
- if (intent.request.handler !== void 0) return false;
24695
- const defaultId = runtime.intentDefaults.get(intent.request.archetype);
24696
- if (!defaultId) return true;
24697
- const record2 = runtime.catalog.get(defaultId);
24698
- return !record2 || !record2.archetypes.some((entry) => entry.slug === intent.request.archetype && entry.convention === intent.request.convention);
24699
- }
24700
- async function resolveRecommendedIntentTarget(context, hint2, archetype, convention) {
24701
- const match = /^35129:([a-f0-9]{64}):(.+)$/.exec(hint2.address);
24702
- if (!match) return null;
24703
- const [, pubkey2, identifier] = match;
24704
- const existing = context.runtime.catalog.installed().find((record2) => record2.id === `nip5d:${hint2.address}` && record2.archetypes.some((entry) => entry.slug === archetype && entry.convention === convention));
24705
- if (existing) return null;
24706
- const pointer = naddrEncode({ identifier, pubkey: pubkey2, kind: 35129, relays: [...hint2.relays ?? []] });
24707
- let target;
24708
- try {
24709
- target = await resolvePajaPointer(pointer, pajaPointerResolverOptions(context));
24710
- } catch {
24711
- return null;
24712
- }
24713
- const exactCoordinate = target.event.kind === 35129 && target.event.pubkey === pubkey2 && target.manifest.dTag === identifier;
24714
- const exactContract = target.manifest.archetypes.some((entry) => entry.slug === archetype && entry.convention === convention);
24715
- if (!exactCoordinate || !exactContract) return null;
24716
- if (!window.confirm(`Install and use recommended handler ${target.manifest.title ?? target.manifest.dTag}?`)) return null;
24717
- return target;
24718
- }
24719
24954
 
24720
24955
  // src/browser-target-diagnostics.ts
24721
24956
  async function reportTargetCorsDiagnostic(state) {
@@ -25369,8 +25604,8 @@ async function restorePersistedRuntimeTabs(state, context, snapshot) {
25369
25604
  persistRuntimeTabs2(state);
25370
25605
  }
25371
25606
  async function hydratePersistedIntentCatalog(state, context, snapshot) {
25372
- if (!snapshot) return;
25373
- await Promise.all(snapshot.pointers.map(async (pointer) => {
25607
+ const pointers = /* @__PURE__ */ new Set([...readPajaIntentCatalogPointers(), ...snapshot?.pointers ?? []]);
25608
+ await Promise.all([...pointers].map(async (pointer) => {
25374
25609
  try {
25375
25610
  const resolved = await resolvePajaPointer(pointer, pajaPointerResolverOptions(context));
25376
25611
  context.runtime.catalog.install(resolved);
@@ -25528,7 +25763,7 @@ async function installPajaHost() {
25528
25763
  const themeBroadcast = createPajaThemeBroadcastLink();
25529
25764
  let stateRef = null;
25530
25765
  let contextRef = null;
25531
- let intentReview = null;
25766
+ let intentLinks = null;
25532
25767
  const intentController = new BrowserIntentController(createPajaIntentTargetOptions(
25533
25768
  () => stateRef,
25534
25769
  () => contextRef,
@@ -25594,12 +25829,7 @@ async function installPajaHost() {
25594
25829
  return runtime.intentDefaults.get(archetype);
25595
25830
  },
25596
25831
  async chooseHandler(archetype, candidates) {
25597
- const selected = await intentReview?.chooseHandler(archetype, candidates);
25598
- if (selected && intentReview?.consumeSaveDefault()) {
25599
- runtime.intentDefaults.set(archetype, selected);
25600
- writePajaIntentDefaults(runtime.intentDefaults);
25601
- }
25602
- return selected;
25832
+ return intentLinks?.chooseHandler(archetype, candidates);
25603
25833
  },
25604
25834
  resolveHandlerHint(hint2, candidates) {
25605
25835
  const id = `nip5d:${hint2.address}`;
@@ -25636,6 +25866,19 @@ async function installPajaHost() {
25636
25866
  stateRef = state;
25637
25867
  const stopIntentCatalogChanges = subscribePajaIntentCatalogChanges(state, context);
25638
25868
  window.addEventListener("pagehide", stopIntentCatalogChanges, { once: true });
25869
+ const catalogPointers = /* @__PURE__ */ new Map();
25870
+ const stopCatalogPersistence = runtime.catalog.onChanged((id) => {
25871
+ const pointers = new Set(readPajaIntentCatalogPointers());
25872
+ const previous = catalogPointers.get(id);
25873
+ if (previous) pointers.delete(previous);
25874
+ const record2 = runtime.catalog.get(id);
25875
+ if (record2) {
25876
+ pointers.add(record2.pointer.value);
25877
+ catalogPointers.set(id, record2.pointer.value);
25878
+ } else catalogPointers.delete(id);
25879
+ writePajaIntentCatalogPointers([...pointers]);
25880
+ });
25881
+ window.addEventListener("pagehide", stopCatalogPersistence, { once: true });
25639
25882
  window.addEventListener("pagehide", stopIdentityChanges, { once: true });
25640
25883
  window.addEventListener("pagehide", () => confirmationController.dispose(), { once: true });
25641
25884
  window.addEventListener("pagehide", () => notifyController?.dispose(), { once: true });
@@ -25689,24 +25932,30 @@ async function installPajaHost() {
25689
25932
  setStatus(state, "error");
25690
25933
  });
25691
25934
  installPajaControlListeners(state);
25692
- const review = createPajaIntentLinkReviewController(void 0, {
25693
- clearDefault(archetype) {
25694
- runtime.intentDefaults.delete(archetype);
25935
+ const links = createPajaIntentLinkController(void 0, {
25936
+ setDefault(archetype, id) {
25937
+ runtime.intentDefaults.set(archetype, id);
25695
25938
  writePajaIntentDefaults(runtime.intentDefaults);
25939
+ },
25940
+ onAccepted() {
25941
+ const url = new URL(window.location.href);
25942
+ if (!url.searchParams.has("intent")) return;
25943
+ url.search = "";
25944
+ window.history.replaceState(window.history.state, "", url);
25696
25945
  }
25697
25946
  });
25698
- intentReview = review;
25947
+ intentLinks = links;
25699
25948
  const builder = createPajaIntentLinkBuilder({
25700
25949
  onTest(link) {
25701
- if (!review) return;
25702
- void review.review(link, (intent, progress) => launchPajaReviewedIntent(state, context, intent, progress, setPointerStatus));
25950
+ if (!links) return;
25951
+ links.open(link, (intent, progress) => launchPajaSharedIntent(state, context, intent, progress, setPointerStatus));
25703
25952
  }
25704
25953
  });
25705
25954
  state.createIntentLink = (tab) => {
25706
25955
  if (isPajaLocalTarget(tab.resolvedTarget) || tab.resolvedTarget.manifest.archetypes.length === 0) return;
25707
25956
  builder.open(tab.resolvedTarget);
25708
25957
  };
25709
- window.addEventListener("pagehide", () => review?.dispose(), { once: true });
25958
+ window.addEventListener("pagehide", () => links?.dispose(), { once: true });
25710
25959
  window.addEventListener("pagehide", () => builder.dispose(), { once: true });
25711
25960
  window.addEventListener("pagehide", () => {
25712
25961
  for (const [source, launcher] of runtime.launcherFrames) {
@@ -25728,18 +25977,19 @@ async function installPajaHost() {
25728
25977
  } catch (error) {
25729
25978
  setStatus(state, "error");
25730
25979
  setPointerStatus(state, error instanceof Error ? error.message : String(error));
25980
+ links?.showError(error);
25731
25981
  return;
25732
25982
  }
25733
25983
  const persistedTabs = readPersistedRuntimeTabs(config);
25734
25984
  const input = document.getElementById("runtime-pointer-input");
25735
25985
  if (input instanceof HTMLInputElement) input.value = state.pointerValue;
25736
- if (incomingIntent && review) {
25986
+ if (incomingIntent && links) {
25737
25987
  void hydratePersistedIntentCatalog(state, context, persistedTabs).then(() => {
25738
25988
  setStatus(state, "ready");
25739
25989
  setEmptyStageVisible(true);
25740
25990
  renderRuntimeTabs(state);
25741
- void review.review(incomingIntent, (intent, progress) => launchPajaReviewedIntent(state, context, intent, progress, setPointerStatus));
25742
- });
25991
+ links.open(incomingIntent, (intent, progress) => launchPajaSharedIntent(state, context, intent, progress, setPointerStatus));
25992
+ }).catch((error) => links.showError(error));
25743
25993
  } else if (state.pointerValue) void state.loadPointer(state.pointerValue);
25744
25994
  else if (persistedTabs) void restorePersistedRuntimeTabs(state, context, persistedTabs);
25745
25995
  else {