@kehto/paja 0.22.0 → 0.24.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.
@@ -10504,7 +10504,7 @@ function createUploadService(options) {
10504
10504
  const uploadInfo = options.uploadInfo ?? DEFAULT_UPLOAD_INFO;
10505
10505
  const generateId2 = options.generateId ?? (() => crypto.randomUUID());
10506
10506
  const now2 = options.now ?? (() => Date.now());
10507
- const entries = /* @__PURE__ */ new Map();
10507
+ const windows = /* @__PURE__ */ new Map();
10508
10508
  function normalizeUploadInfo(info) {
10509
10509
  return {
10510
10510
  rails: Array.isArray(info.rails) ? info.rails.filter((rail) => typeof rail?.rail === "string").map((rail) => ({
@@ -10525,7 +10525,7 @@ function createUploadService(options) {
10525
10525
  send({ type: "upload.info.result", id, error: toErrorMessage2(err2) });
10526
10526
  });
10527
10527
  }
10528
- function handleUpload(windowId, msg, send) {
10528
+ function handleUpload(windowId, msg, send, entries) {
10529
10529
  const m = msg;
10530
10530
  const id = m.id ?? "";
10531
10531
  const request = m.request;
@@ -10534,29 +10534,31 @@ function createUploadService(options) {
10534
10534
  return;
10535
10535
  }
10536
10536
  const uploadId = generateId2();
10537
- const key = `${windowId}:${uploadId}`;
10538
- entries.set(key, { uploadId });
10537
+ const entry = { uploadId };
10538
+ entries.set(uploadId, entry);
10539
+ const isActive = () => windows.get(windowId) === entries && entries.get(uploadId) === entry;
10539
10540
  const ctx = {
10540
10541
  uploadId,
10541
10542
  windowId,
10542
10543
  onStatus: (status) => {
10544
+ if (!isActive()) return;
10543
10545
  const stamped = { ...status, uploadId, updatedAt: status.updatedAt || now2() };
10544
- const entry = entries.get(key);
10545
- if (entry) entry.status = stamped;
10546
+ entry.status = stamped;
10546
10547
  send({ type: "upload.status.changed", status: stamped });
10547
10548
  }
10548
10549
  };
10549
10550
  void uploader.upload(request, ctx).then((result2) => {
10551
+ if (!isActive()) return;
10550
10552
  const stamped = { ...result2, uploadId };
10551
- const entry = entries.get(key);
10552
- if (entry) entry.status = { ...stamped, updatedAt: now2() };
10553
+ entry.status = { ...stamped, updatedAt: now2() };
10553
10554
  send({ type: "upload.upload.result", id, result: stamped });
10554
10555
  }).catch((err2) => {
10555
- entries.delete(key);
10556
+ if (!isActive()) return;
10557
+ entries.delete(uploadId);
10556
10558
  send({ type: "upload.upload.result", id, error: toErrorMessage2(err2) });
10557
10559
  });
10558
10560
  }
10559
- function handleStatus(windowId, msg, send) {
10561
+ function handleStatus(msg, send, entries) {
10560
10562
  const m = msg;
10561
10563
  const id = m.id ?? "";
10562
10564
  const uploadId = m.uploadId;
@@ -10564,7 +10566,7 @@ function createUploadService(options) {
10564
10566
  send({ type: "upload.status.result", id, error: "invalid uploadId" });
10565
10567
  return;
10566
10568
  }
10567
- const tracked = entries.get(`${windowId}:${uploadId}`)?.status;
10569
+ const tracked = entries.get(uploadId)?.status;
10568
10570
  if (tracked) {
10569
10571
  send({ type: "upload.status.result", id, status: tracked });
10570
10572
  return;
@@ -10581,31 +10583,52 @@ function createUploadService(options) {
10581
10583
  }
10582
10584
  send({ type: "upload.status.result", id, error: "unknown upload" });
10583
10585
  }
10586
+ function cancelUploads(entries) {
10587
+ if (!entries) return;
10588
+ for (const entry of entries.values()) {
10589
+ try {
10590
+ uploader.cancel?.(entry.uploadId);
10591
+ } catch {
10592
+ }
10593
+ }
10594
+ }
10595
+ function destroyWindow(windowId) {
10596
+ const entries = windows.get(windowId);
10597
+ windows.delete(windowId);
10598
+ cancelUploads(entries);
10599
+ }
10584
10600
  return {
10585
10601
  descriptor: UPLOAD_DESCRIPTOR,
10586
10602
  handleMessage(windowId, message2, send) {
10603
+ if (!["upload.info", "upload.upload", "upload.status"].includes(message2.type)) return;
10604
+ let entries = windows.get(windowId);
10605
+ if (!entries) {
10606
+ entries = /* @__PURE__ */ new Map();
10607
+ windows.set(windowId, entries);
10608
+ }
10609
+ const lifetime = entries;
10610
+ const sendIfActive = (response) => {
10611
+ if (windows.get(windowId) === lifetime) send(response);
10612
+ };
10587
10613
  switch (message2.type) {
10588
10614
  case "upload.info":
10589
- handleInfo2(windowId, message2, send);
10615
+ handleInfo2(windowId, message2, sendIfActive);
10590
10616
  return;
10591
10617
  case "upload.upload":
10592
- handleUpload(windowId, message2, send);
10618
+ handleUpload(windowId, message2, sendIfActive, entries);
10593
10619
  return;
10594
10620
  case "upload.status":
10595
- handleStatus(windowId, message2, send);
10621
+ handleStatus(message2, sendIfActive, entries);
10596
10622
  return;
10597
10623
  default:
10598
10624
  return;
10599
10625
  }
10600
10626
  },
10601
- onWindowDestroyed(windowId) {
10602
- const prefix = `${windowId}:`;
10603
- for (const [key, entry] of entries) {
10604
- if (key.startsWith(prefix)) {
10605
- uploader.cancel?.(entry.uploadId);
10606
- entries.delete(key);
10607
- }
10608
- }
10627
+ onWindowDestroyed: destroyWindow,
10628
+ onUnregistered() {
10629
+ const pending = [...windows.values()];
10630
+ windows.clear();
10631
+ for (const entries of pending) cancelUploads(entries);
10609
10632
  }
10610
10633
  };
10611
10634
  }
@@ -16355,6 +16378,93 @@ function installPajaSidebarSections() {
16355
16378
  return () => disposers.forEach((dispose) => dispose());
16356
16379
  }
16357
16380
 
16381
+ // src/browser-gamepad-indicators.ts
16382
+ var ICON = '<svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="1.7" aria-hidden="true"><path d="M7 6h10c3 0 5 10 3 12-2 2-5-3-6-3h-4c-1 0-4 5-6 3C2 16 4 6 7 6Z"/><path d="M7 9v6m-3-3h6"/><circle cx="16" cy="10" r="1" fill="currentColor"/><circle cx="19" cy="13" r="1" fill="currentColor"/></svg>';
16383
+ function installPajaGamepadIndicators() {
16384
+ const container = document.getElementById("paja-gamepads");
16385
+ if (!container || typeof navigator.getGamepads !== "function") return () => {
16386
+ };
16387
+ const icons = /* @__PURE__ */ new Map();
16388
+ const activeUntil = /* @__PURE__ */ new Map();
16389
+ let frame;
16390
+ let disposed = false;
16391
+ const makeIcon = (pad3) => {
16392
+ const icon = document.createElement("span");
16393
+ icon.className = "gamepad-indicator";
16394
+ icon.dataset.gamepadIndex = String(pad3.index);
16395
+ icon.setAttribute("role", "img");
16396
+ icon.style.setProperty("--pad-color", `hsl(${(pad3.index * 137.508 + 155) % 360} 75% 70%)`);
16397
+ icon.style.setProperty("--pad-turn", `${(pad3.index % 2 ? -1 : 1) * (6 + pad3.index * 2)}deg`);
16398
+ icon.style.setProperty("--pad-lift", `${-2 - pad3.index % 4}px`);
16399
+ icon.style.setProperty("--pad-duration", `${480 + pad3.index * 85}ms`);
16400
+ icon.style.setProperty("--pad-animation", ["gamepad-bounce", "gamepad-rock", "gamepad-pulse", "gamepad-nudge"][pad3.index % 4]);
16401
+ icon.innerHTML = ICON;
16402
+ const number = document.createElement("small");
16403
+ number.textContent = String(pad3.index + 1);
16404
+ icon.append(number);
16405
+ container.append(icon);
16406
+ icons.set(pad3.index, icon);
16407
+ return icon;
16408
+ };
16409
+ const sample = () => {
16410
+ let pads;
16411
+ try {
16412
+ pads = Array.from(navigator.getGamepads());
16413
+ } catch {
16414
+ pads = [];
16415
+ }
16416
+ const connected = /* @__PURE__ */ new Set();
16417
+ const focused = document.visibilityState !== "hidden" && document.hasFocus();
16418
+ const now2 = performance.now();
16419
+ for (const pad3 of pads) {
16420
+ if (!pad3?.connected) continue;
16421
+ connected.add(pad3.index);
16422
+ const icon = icons.get(pad3.index) ?? makeIcon(pad3);
16423
+ const input = focused && (pad3.axes.some((axis) => Math.abs(axis) > 0.12) || pad3.buttons.some((button2) => button2.pressed || button2.value > 0.05));
16424
+ if (input) activeUntil.set(pad3.index, now2 + 420);
16425
+ if (!focused) activeUntil.delete(pad3.index);
16426
+ const active = now2 < (activeUntil.get(pad3.index) ?? 0);
16427
+ const activity = active ? "active" : "idle";
16428
+ if (icon.dataset.activity !== activity || icon.dataset.model !== pad3.id) {
16429
+ icon.dataset.activity = activity;
16430
+ icon.dataset.model = pad3.id;
16431
+ const label = `Controller ${pad3.index + 1}: ${pad3.id} \u2014 ${activity}`;
16432
+ icon.setAttribute("aria-label", label);
16433
+ icon.title = label;
16434
+ }
16435
+ }
16436
+ for (const [index, icon] of icons) {
16437
+ if (connected.has(index)) continue;
16438
+ icon.remove();
16439
+ icons.delete(index);
16440
+ activeUntil.delete(index);
16441
+ }
16442
+ };
16443
+ const tick = () => {
16444
+ frame = void 0;
16445
+ if (disposed) return;
16446
+ sample();
16447
+ if (document.visibilityState !== "hidden") frame = requestAnimationFrame(tick);
16448
+ };
16449
+ const refresh = () => {
16450
+ if (frame !== void 0) cancelAnimationFrame(frame);
16451
+ tick();
16452
+ };
16453
+ const events = ["gamepadconnected", "gamepaddisconnected", "focus", "blur"];
16454
+ for (const event of events) window.addEventListener(event, refresh);
16455
+ document.addEventListener("visibilitychange", refresh);
16456
+ tick();
16457
+ return () => {
16458
+ disposed = true;
16459
+ if (frame !== void 0) cancelAnimationFrame(frame);
16460
+ for (const event of events) window.removeEventListener(event, refresh);
16461
+ document.removeEventListener("visibilitychange", refresh);
16462
+ container.replaceChildren();
16463
+ icons.clear();
16464
+ activeUntil.clear();
16465
+ };
16466
+ }
16467
+
16358
16468
  // ../../node_modules/.pnpm/nostr-tools@2.23.3_typescript@5.9.3/node_modules/nostr-tools/lib/esm/pool.js
16359
16469
  var verifiedSymbol3 = /* @__PURE__ */ Symbol("verified");
16360
16470
  var isRecord4 = (obj) => obj instanceof Object;
@@ -18331,208 +18441,39 @@ function createBrowserBleController(activation, api = browserBluetoothApi()) {
18331
18441
  };
18332
18442
  }
18333
18443
 
18334
- // src/browser-intent-controller.ts
18335
- var MAX_INTENT_DELIVERY_ATTEMPTS = 10;
18336
- var BrowserIntentController = class {
18337
- constructor(options) {
18338
- this.options = options;
18339
- this.maxAttempts = normalizeAttempts(options.maxAttempts);
18340
- }
18341
- options;
18342
- maxAttempts;
18343
- /** Retain delivery work immediately; completion remains host-observable only. */
18344
- accept(params) {
18345
- const acceptance = Object.freeze({ completion: this.dispatch(params) });
18346
- this.options.onAccepted?.(params, acceptance);
18347
- return acceptance;
18348
- }
18349
- /** Complete an already accepted delivery. Kept public for host diagnostics and tests. */
18350
- async dispatch(params) {
18351
- const dispatch2 = freezeDispatch(params);
18352
- let reason = "no-current-target";
18353
- for (let attempt = 1; attempt <= this.maxAttempts; attempt += 1) {
18354
- let generation;
18355
- try {
18356
- generation = await this.options.openOrReuse(dispatch2, attempt);
18357
- } catch {
18358
- reason = "open-failed";
18359
- continue;
18360
- }
18361
- if (!generation) {
18362
- reason = "open-failed";
18363
- continue;
18364
- }
18365
- try {
18366
- await this.options.waitForReady(generation);
18367
- } catch {
18368
- reason = "ready-failed";
18369
- continue;
18370
- }
18371
- if (!await this.options.isCurrent(generation)) {
18372
- reason = "no-current-target";
18373
- continue;
18374
- }
18375
- try {
18376
- await this.options.send(generation, dispatch2);
18377
- this.options.onDelivered?.(dispatch2);
18378
- return;
18379
- } catch {
18380
- this.options.onTerminal?.(dispatch2, "send-failed");
18381
- throw new Error("intent target send failed");
18382
- }
18383
- }
18384
- this.options.onTerminal?.(dispatch2, reason);
18385
- throw new Error(`intent target ${reason}`);
18386
- }
18387
- };
18388
- function normalizeAttempts(value) {
18389
- if (value === void 0) return 2;
18390
- if (!Number.isFinite(value)) throw new TypeError("maxAttempts must be finite");
18391
- return Math.min(MAX_INTENT_DELIVERY_ATTEMPTS, Math.max(1, Math.floor(value)));
18392
- }
18393
- function freezeDispatch(params) {
18394
- if (!params || typeof params.handler !== "string" || params.handler.length === 0) {
18395
- throw new TypeError("Intent dispatch requires a handler");
18396
- }
18397
- 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) {
18398
- throw new TypeError("Intent dispatch requires canonical routing fields");
18399
- }
18400
- const payload = freezeValue(params.payload);
18401
- const behavior = params.behavior === void 0 ? void 0 : freezeValue({ ...params.behavior });
18402
- return Object.freeze({
18403
- handler: params.handler,
18404
- sender: params.sender,
18405
- archetype: params.archetype,
18406
- action: params.action,
18407
- convention: params.convention,
18408
- ...params.payload === void 0 ? {} : { payload },
18409
- ...behavior === void 0 ? {} : { behavior },
18410
- ...params.sourceWindowId === void 0 ? {} : { sourceWindowId: params.sourceWindowId }
18444
+ // src/browser-catalog-intent-service.ts
18445
+ function createPajaCatalogIntentService(adapter, host) {
18446
+ const resolver = createCatalogIntentResolver({
18447
+ loadCatalog: () => host.catalog.intentCatalog(
18448
+ (record2) => resolveShellEnvironment(adapter, record2).capabilities.domains.includes("intent")
18449
+ ),
18450
+ targets: host.controller,
18451
+ getDefaultHandler: host.getDefaultHandler,
18452
+ chooseHandler: host.chooseHandler,
18453
+ authorizeExplicitHandler: host.authorizeExplicitHandler,
18454
+ resolveHandlerHint: host.resolveHandlerHint
18411
18455
  });
18412
- }
18413
- function freezeValue(value, seen = /* @__PURE__ */ new WeakMap()) {
18414
- if (typeof value !== "object" || value === null) return value;
18415
- const existing = seen.get(value);
18416
- if (existing !== void 0) return existing;
18417
- if (Array.isArray(value)) {
18418
- const copy2 = [];
18419
- seen.set(value, copy2);
18420
- for (const item of value) copy2.push(freezeValue(item, seen));
18421
- return Object.freeze(copy2);
18422
- }
18423
- const copy = {};
18424
- seen.set(value, copy);
18425
- for (const [key, item] of Object.entries(value)) copy[key] = freezeValue(item, seen);
18426
- return Object.freeze(copy);
18427
- }
18428
-
18429
- // src/installed-napplet-catalog.ts
18430
- function matchesInstalledNappletRecord(record2, target) {
18431
- return target.id === record2.id && target.aggregateHash === record2.aggregateHash;
18432
- }
18433
- var InstalledNappletCatalog = class {
18434
- records = /* @__PURE__ */ new Map();
18435
- listeners = /* @__PURE__ */ new Set();
18436
- /** Insert or replace a record from an already resolver-verified pointer. */
18437
- install(resolved) {
18438
- const record2 = freezeRecord({
18439
- id: resolved.manifest.catalogId,
18440
- dTag: resolved.dTag,
18441
- aggregateHash: resolved.aggregateHash,
18442
- pointer: copyPointer(resolved.pointer),
18443
- ...resolved.manifest.title === void 0 ? {} : { title: resolved.manifest.title },
18444
- requires: [...resolved.manifest.requires],
18445
- optional: [...resolved.manifest.optional ?? []],
18446
- archetypes: resolved.manifest.archetypes.map((archetype) => ({
18447
- slug: archetype.slug,
18448
- convention: archetype.convention,
18449
- params: [...archetype.params]
18450
- }))
18451
- });
18452
- this.records.set(record2.id, record2);
18453
- this.notify(record2.id);
18454
- return record2;
18455
- }
18456
- /** Remove an artifact explicitly; frame teardown never calls this method. */
18457
- remove(id) {
18458
- const removed = this.records.delete(id);
18459
- if (removed) this.notify(id);
18460
- return removed;
18461
- }
18462
- /** Return whether a verified installation exists for a catalog ID. */
18463
- has(id) {
18464
- return this.records.has(id);
18465
- }
18466
- /** Return immutable serializable installed-artifact facts. */
18467
- installed() {
18468
- return [...this.records.values()];
18469
- }
18470
- /** Return a verified record by catalog ID. */
18471
- get(id) {
18472
- return this.records.get(id);
18473
- }
18474
- /**
18475
- * Atomically confirm that a resolved target still belongs to the exact record
18476
- * selected before an async operation. The record object is the catalog version
18477
- * token, so even a same-identity replacement cannot pass this check.
18478
- */
18479
- validateCurrent(selected, target) {
18480
- if (this.records.get(selected.id) !== selected) return null;
18481
- return matchesInstalledNappletRecord(selected, target) ? selected : null;
18482
- }
18483
- /**
18484
- * Return declared handlers whose host environment can receive intent delivery.
18485
- * @param canReceiveIntent - Resolve intent availability for each verified identity;
18486
- * without host policy, return declared candidates for the host to filter.
18487
- * @returns Named intent candidates usable under the supplied host policy.
18488
- */
18489
- intentCatalog(canReceiveIntent = () => true) {
18490
- return this.installed().filter(canReceiveIntent).map((record2) => manifestToIntentCatalogEntry({
18491
- catalogId: record2.id,
18492
- ...record2.title === void 0 ? {} : { title: record2.title },
18493
- archetypes: record2.archetypes.map((archetype) => ({
18494
- slug: archetype.slug,
18495
- convention: archetype.convention,
18496
- params: [...archetype.params]
18497
- }))
18498
- }));
18499
- }
18500
- /** Subscribe to explicit install and artifact-removal changes. */
18501
- onChanged(listener) {
18502
- this.listeners.add(listener);
18503
- return () => this.listeners.delete(listener);
18504
- }
18505
- notify(id) {
18506
- for (const listener of this.listeners) listener(id);
18507
- }
18508
- };
18509
- function copyPointer(pointer) {
18510
- if (pointer.type === "naddr") {
18511
- return Object.freeze({
18512
- type: "naddr",
18513
- value: pointer.value,
18514
- identifier: pointer.identifier,
18515
- pubkey: pointer.pubkey,
18516
- kind: pointer.kind,
18517
- relays: Object.freeze([...pointer.relays])
18518
- });
18519
- }
18520
- return Object.freeze({
18521
- type: "nevent",
18522
- value: pointer.value,
18523
- id: pointer.id,
18524
- ...pointer.author === void 0 ? {} : { author: pointer.author },
18525
- ...pointer.kind === void 0 ? {} : { kind: pointer.kind },
18526
- relays: Object.freeze([...pointer.relays])
18527
- });
18528
- }
18529
- function freezeRecord(record2) {
18530
- return Object.freeze({
18531
- ...record2,
18532
- requires: Object.freeze([...record2.requires]),
18533
- optional: Object.freeze([...record2.optional ?? []]),
18534
- archetypes: Object.freeze(record2.archetypes.map((archetype) => Object.freeze({ ...archetype, params: Object.freeze([...archetype.params]) })))
18456
+ const intentService = createIntentService({
18457
+ resolver,
18458
+ resolveSender: host.resolveSender
18535
18459
  });
18460
+ let stopCatalogChanges;
18461
+ const service = {
18462
+ ...intentService,
18463
+ onRegistered(context) {
18464
+ stopCatalogChanges?.();
18465
+ intentService.onRegistered?.(context);
18466
+ stopCatalogChanges = host.catalog.onChanged((_id, archetypes) => {
18467
+ for (const archetype of archetypes) resolver.notifyChanged(archetype);
18468
+ });
18469
+ },
18470
+ onUnregistered() {
18471
+ stopCatalogChanges?.();
18472
+ stopCatalogChanges = void 0;
18473
+ intentService.onUnregistered?.();
18474
+ }
18475
+ };
18476
+ return { service, notifyChanged: (archetype) => resolver.notifyChanged(archetype) };
18536
18477
  }
18537
18478
 
18538
18479
  // src/browser-upload.ts
@@ -21944,6 +21885,8 @@ function createPajaAdapter(config, getSimulation, onThemeService, onThemeBroadca
21944
21885
  });
21945
21886
  const adapter = {
21946
21887
  ready,
21888
+ notifyIntentChanged: () => {
21889
+ },
21947
21890
  setWindowBlossomServers: serviceBundle.setWindowBlossomServers,
21948
21891
  relayPool: createPajaRelayHooks(relayBackend, getSimulation, relayConfig),
21949
21892
  relayConfig,
@@ -21983,20 +21926,9 @@ function createPajaAdapter(config, getSimulation, onThemeService, onThemeBroadca
21983
21926
  }
21984
21927
  };
21985
21928
  if (getSimulation().intent.enabled && intentHost) {
21986
- const resolver = createCatalogIntentResolver({
21987
- loadCatalog: () => intentHost.catalog.intentCatalog(
21988
- (record2) => resolveShellEnvironment(adapter, record2).capabilities.domains.includes("intent")
21989
- ),
21990
- targets: intentHost.controller,
21991
- getDefaultHandler: intentHost.getDefaultHandler,
21992
- chooseHandler: intentHost.chooseHandler,
21993
- authorizeExplicitHandler: intentHost.authorizeExplicitHandler,
21994
- resolveHandlerHint: intentHost.resolveHandlerHint
21995
- });
21996
- services.intent = createIntentService({
21997
- resolver,
21998
- resolveSender: intentHost.resolveSender
21999
- });
21929
+ const intent = createPajaCatalogIntentService(adapter, intentHost);
21930
+ services.intent = intent.service;
21931
+ adapter.notifyIntentChanged = intent.notifyChanged;
22000
21932
  }
22001
21933
  return adapter;
22002
21934
  }
@@ -22861,25 +22793,32 @@ function createNipEncryptionMethods(state, prefix) {
22861
22793
  decrypt: async (pubkey2, ciphertext) => sendRequestWithId(state, crypto.randomUUID(), `${prefix}_decrypt`, [pubkey2, ciphertext])
22862
22794
  };
22863
22795
  }
22796
+ var HEX_PUBKEY2 = /^[0-9a-f]{64}$/i;
22797
+ function readPubkey(value) {
22798
+ if (typeof value === "string") {
22799
+ const normalized = value.trim().toLowerCase();
22800
+ return HEX_PUBKEY2.test(normalized) ? normalized : null;
22801
+ }
22802
+ if (value && typeof value === "object" && "pubkey" in value) {
22803
+ return readPubkey(value.pubkey);
22804
+ }
22805
+ return null;
22806
+ }
22807
+ async function requestPublicKey(state) {
22808
+ const result2 = await sendRequestWithId(state, crypto.randomUUID(), "get_public_key", []);
22809
+ const pubkey2 = readPubkey(result2);
22810
+ if (!pubkey2) throw new Error("NIP-46 signer returned an invalid public key");
22811
+ state.authorizedPubkey = pubkey2;
22812
+ return pubkey2;
22813
+ }
22864
22814
  async function connectNip46State(state, secret) {
22865
22815
  await openWebSocket(state);
22866
- const result2 = await sendRequestWithId(state, crypto.randomUUID(), "connect", [state.bunkerPubkey, secret ?? ""]);
22867
- if (typeof result2 === "string") {
22868
- state.authorizedPubkey = result2;
22869
- } else if (result2 && typeof result2 === "object" && "pubkey" in result2) {
22870
- state.authorizedPubkey = result2.pubkey;
22871
- } else {
22872
- const pkResult = await sendRequestWithId(state, crypto.randomUUID(), "get_public_key", []);
22873
- state.authorizedPubkey = pkResult;
22874
- }
22875
- return state.authorizedPubkey;
22816
+ await sendRequestWithId(state, crypto.randomUUID(), "connect", [state.bunkerPubkey, secret ?? ""]);
22817
+ return requestPublicKey(state);
22876
22818
  }
22877
22819
  function createNip46Signer(state) {
22878
22820
  return {
22879
- getPublicKey: async () => {
22880
- if (state.authorizedPubkey) return state.authorizedPubkey;
22881
- return sendRequestWithId(state, crypto.randomUUID(), "get_public_key", []);
22882
- },
22821
+ getPublicKey: async () => state.authorizedPubkey ?? requestPublicKey(state),
22883
22822
  signEvent: async (event) => {
22884
22823
  const result2 = await sendRequestWithId(state, crypto.randomUUID(), "sign_event", [JSON.stringify(event)]);
22885
22824
  if (typeof result2 === "string") {
@@ -23667,6 +23606,7 @@ function parseRuntimeTabsSnapshot(value) {
23667
23606
  };
23668
23607
  }
23669
23608
  function renderRuntimeTabs(state) {
23609
+ document.title = getActiveTab(state)?.title || "@kehto/paja";
23670
23610
  const tabsEl = document.getElementById("napplet-tabs");
23671
23611
  if (!(tabsEl instanceof HTMLElement)) return;
23672
23612
  tabsEl.replaceChildren(...state.tabs.map((tab) => renderTab(state, tab)));
@@ -24111,6 +24051,216 @@ function installLocalFileControls(load) {
24111
24051
  function disposeNothing() {
24112
24052
  }
24113
24053
 
24054
+ // src/browser-intent-controller.ts
24055
+ var MAX_INTENT_DELIVERY_ATTEMPTS = 10;
24056
+ var BrowserIntentController = class {
24057
+ constructor(options) {
24058
+ this.options = options;
24059
+ this.maxAttempts = normalizeAttempts(options.maxAttempts);
24060
+ }
24061
+ options;
24062
+ maxAttempts;
24063
+ /** Retain delivery work immediately; completion remains host-observable only. */
24064
+ accept(params) {
24065
+ const acceptance = Object.freeze({ completion: this.dispatch(params) });
24066
+ this.options.onAccepted?.(params, acceptance);
24067
+ return acceptance;
24068
+ }
24069
+ /** Complete an already accepted delivery. Kept public for host diagnostics and tests. */
24070
+ async dispatch(params) {
24071
+ const dispatch2 = freezeDispatch(params);
24072
+ let reason = "no-current-target";
24073
+ for (let attempt = 1; attempt <= this.maxAttempts; attempt += 1) {
24074
+ let generation;
24075
+ try {
24076
+ generation = await this.options.openOrReuse(dispatch2, attempt);
24077
+ } catch {
24078
+ reason = "open-failed";
24079
+ continue;
24080
+ }
24081
+ if (!generation) {
24082
+ reason = "open-failed";
24083
+ continue;
24084
+ }
24085
+ try {
24086
+ await this.options.waitForReady(generation);
24087
+ } catch {
24088
+ reason = "ready-failed";
24089
+ continue;
24090
+ }
24091
+ if (!await this.options.isCurrent(generation)) {
24092
+ reason = "no-current-target";
24093
+ continue;
24094
+ }
24095
+ try {
24096
+ await this.options.send(generation, dispatch2);
24097
+ this.options.onDelivered?.(dispatch2);
24098
+ return;
24099
+ } catch {
24100
+ this.options.onTerminal?.(dispatch2, "send-failed");
24101
+ throw new Error("intent target send failed");
24102
+ }
24103
+ }
24104
+ this.options.onTerminal?.(dispatch2, reason);
24105
+ throw new Error(`intent target ${reason}`);
24106
+ }
24107
+ };
24108
+ function normalizeAttempts(value) {
24109
+ if (value === void 0) return 2;
24110
+ if (!Number.isFinite(value)) throw new TypeError("maxAttempts must be finite");
24111
+ return Math.min(MAX_INTENT_DELIVERY_ATTEMPTS, Math.max(1, Math.floor(value)));
24112
+ }
24113
+ function freezeDispatch(params) {
24114
+ if (!params || typeof params.handler !== "string" || params.handler.length === 0) {
24115
+ throw new TypeError("Intent dispatch requires a handler");
24116
+ }
24117
+ 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) {
24118
+ throw new TypeError("Intent dispatch requires canonical routing fields");
24119
+ }
24120
+ const payload = freezeValue(params.payload);
24121
+ const behavior = params.behavior === void 0 ? void 0 : freezeValue({ ...params.behavior });
24122
+ return Object.freeze({
24123
+ handler: params.handler,
24124
+ sender: params.sender,
24125
+ archetype: params.archetype,
24126
+ action: params.action,
24127
+ convention: params.convention,
24128
+ ...params.payload === void 0 ? {} : { payload },
24129
+ ...behavior === void 0 ? {} : { behavior },
24130
+ ...params.sourceWindowId === void 0 ? {} : { sourceWindowId: params.sourceWindowId }
24131
+ });
24132
+ }
24133
+ function freezeValue(value, seen = /* @__PURE__ */ new WeakMap()) {
24134
+ if (typeof value !== "object" || value === null) return value;
24135
+ const existing = seen.get(value);
24136
+ if (existing !== void 0) return existing;
24137
+ if (Array.isArray(value)) {
24138
+ const copy2 = [];
24139
+ seen.set(value, copy2);
24140
+ for (const item of value) copy2.push(freezeValue(item, seen));
24141
+ return Object.freeze(copy2);
24142
+ }
24143
+ const copy = {};
24144
+ seen.set(value, copy);
24145
+ for (const [key, item] of Object.entries(value)) copy[key] = freezeValue(item, seen);
24146
+ return Object.freeze(copy);
24147
+ }
24148
+
24149
+ // src/installed-napplet-catalog.ts
24150
+ function matchesInstalledNappletRecord(record2, target) {
24151
+ return target.id === record2.id && target.aggregateHash === record2.aggregateHash;
24152
+ }
24153
+ var InstalledNappletCatalog = class {
24154
+ records = /* @__PURE__ */ new Map();
24155
+ listeners = /* @__PURE__ */ new Set();
24156
+ /** Insert or replace a record from an already resolver-verified pointer. */
24157
+ install(resolved) {
24158
+ const record2 = freezeRecord({
24159
+ id: resolved.manifest.catalogId,
24160
+ dTag: resolved.dTag,
24161
+ aggregateHash: resolved.aggregateHash,
24162
+ pointer: copyPointer(resolved.pointer),
24163
+ ...resolved.manifest.title === void 0 ? {} : { title: resolved.manifest.title },
24164
+ requires: [...resolved.manifest.requires],
24165
+ optional: [...resolved.manifest.optional ?? []],
24166
+ archetypes: resolved.manifest.archetypes.map((archetype) => ({
24167
+ slug: archetype.slug,
24168
+ convention: archetype.convention,
24169
+ params: [...archetype.params]
24170
+ }))
24171
+ });
24172
+ const previous = this.records.get(record2.id);
24173
+ this.records.set(record2.id, record2);
24174
+ this.notify(record2.id, previous, record2);
24175
+ return record2;
24176
+ }
24177
+ /** Remove an artifact explicitly; frame teardown never calls this method. */
24178
+ remove(id) {
24179
+ const previous = this.records.get(id);
24180
+ const removed = this.records.delete(id);
24181
+ if (removed) this.notify(id, previous);
24182
+ return removed;
24183
+ }
24184
+ /** Return whether a verified installation exists for a catalog ID. */
24185
+ has(id) {
24186
+ return this.records.has(id);
24187
+ }
24188
+ /** Return immutable serializable installed-artifact facts. */
24189
+ installed() {
24190
+ return [...this.records.values()];
24191
+ }
24192
+ /** Return a verified record by catalog ID. */
24193
+ get(id) {
24194
+ return this.records.get(id);
24195
+ }
24196
+ /**
24197
+ * Atomically confirm that a resolved target still belongs to the exact record
24198
+ * selected before an async operation. The record object is the catalog version
24199
+ * token, so even a same-identity replacement cannot pass this check.
24200
+ */
24201
+ validateCurrent(selected, target) {
24202
+ if (this.records.get(selected.id) !== selected) return null;
24203
+ return matchesInstalledNappletRecord(selected, target) ? selected : null;
24204
+ }
24205
+ /**
24206
+ * Return declared handlers whose host environment can receive intent delivery.
24207
+ * @param canReceiveIntent - Resolve intent availability for each verified identity;
24208
+ * without host policy, return declared candidates for the host to filter.
24209
+ * @returns Named intent candidates usable under the supplied host policy.
24210
+ */
24211
+ intentCatalog(canReceiveIntent = () => true) {
24212
+ return this.installed().filter(canReceiveIntent).map((record2) => manifestToIntentCatalogEntry({
24213
+ catalogId: record2.id,
24214
+ ...record2.title === void 0 ? {} : { title: record2.title },
24215
+ archetypes: record2.archetypes.map((archetype) => ({
24216
+ slug: archetype.slug,
24217
+ convention: archetype.convention,
24218
+ params: [...archetype.params]
24219
+ }))
24220
+ }));
24221
+ }
24222
+ /** Subscribe to explicit install and artifact-removal changes. */
24223
+ onChanged(listener) {
24224
+ this.listeners.add(listener);
24225
+ return () => this.listeners.delete(listener);
24226
+ }
24227
+ notify(id, previous, current) {
24228
+ const archetypes = Object.freeze([.../* @__PURE__ */ new Set([
24229
+ ...(previous?.archetypes ?? []).map(({ slug }) => slug),
24230
+ ...(current?.archetypes ?? []).map(({ slug }) => slug)
24231
+ ])]);
24232
+ for (const listener of this.listeners) listener(id, archetypes);
24233
+ }
24234
+ };
24235
+ function copyPointer(pointer) {
24236
+ if (pointer.type === "naddr") {
24237
+ return Object.freeze({
24238
+ type: "naddr",
24239
+ value: pointer.value,
24240
+ identifier: pointer.identifier,
24241
+ pubkey: pointer.pubkey,
24242
+ kind: pointer.kind,
24243
+ relays: Object.freeze([...pointer.relays])
24244
+ });
24245
+ }
24246
+ return Object.freeze({
24247
+ type: "nevent",
24248
+ value: pointer.value,
24249
+ id: pointer.id,
24250
+ ...pointer.author === void 0 ? {} : { author: pointer.author },
24251
+ ...pointer.kind === void 0 ? {} : { kind: pointer.kind },
24252
+ relays: Object.freeze([...pointer.relays])
24253
+ });
24254
+ }
24255
+ function freezeRecord(record2) {
24256
+ return Object.freeze({
24257
+ ...record2,
24258
+ requires: Object.freeze([...record2.requires]),
24259
+ optional: Object.freeze([...record2.optional ?? []]),
24260
+ archetypes: Object.freeze(record2.archetypes.map((archetype) => Object.freeze({ ...archetype, params: Object.freeze([...archetype.params]) })))
24261
+ });
24262
+ }
24263
+
24114
24264
  // src/runtime-resolver.ts
24115
24265
  var PAJA_NAPPLET_MANIFEST_KINDS = NAPPLET_KINDS;
24116
24266
  function decodePajaPointer(value) {
@@ -26291,6 +26441,8 @@ function createPajaBrowserState(context, relayEventCounts, relayInventory) {
26291
26441
  };
26292
26442
  }
26293
26443
  async function installPajaHost() {
26444
+ const disposeGamepadIndicators = installPajaGamepadIndicators();
26445
+ window.addEventListener("pagehide", disposeGamepadIndicators, { once: true });
26294
26446
  const disposeConsolePanel = installPajaConsolePanel();
26295
26447
  const disposeSidebarSections = installPajaSidebarSections();
26296
26448
  window.addEventListener("pagehide", disposeSidebarSections, { once: true });
@@ -26504,6 +26656,7 @@ async function installPajaHost() {
26504
26656
  setDefault(archetype, id) {
26505
26657
  runtime.intentDefaults.set(archetype, id);
26506
26658
  writePajaIntentDefaults(runtime.intentDefaults);
26659
+ adapter.notifyIntentChanged(archetype);
26507
26660
  },
26508
26661
  onAccepted() {
26509
26662
  const url = new URL(window.location.href);