@kehto/paja 0.16.0 → 0.16.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.
@@ -11234,6 +11234,7 @@ async function fetchResourceItem(options, windowId, info, request, signal) {
11234
11234
  const response = await options.fetch(url, {
11235
11235
  method: "GET",
11236
11236
  signal,
11237
+ windowId,
11237
11238
  ...parsedUrl.protocol === "blossom:" && request.servers !== void 0 ? { servers: [...request.servers] } : {}
11238
11239
  });
11239
11240
  const buffer = await response.arrayBuffer();
@@ -11547,7 +11548,7 @@ function createOutboxService(options) {
11547
11548
  if (!options || typeof options.router !== "object" || options.router === null) {
11548
11549
  throw new Error("createOutboxService: options.router is required");
11549
11550
  }
11550
- const { router, getQueryRouter } = options;
11551
+ const { router, getReadRouter, getQueryRouter } = options;
11551
11552
  let runtimeContext;
11552
11553
  const subscriptions = /* @__PURE__ */ new Map();
11553
11554
  function handleQuery(windowId, msg, send) {
@@ -11558,7 +11559,7 @@ function createOutboxService(options) {
11558
11559
  send({ type: "outbox.query.result", id, events: [], error: "invalid filter" });
11559
11560
  return;
11560
11561
  }
11561
- const queryRouter = getQueryRouter?.(windowId, runtimeContext) ?? router;
11562
+ const queryRouter = getQueryRouter?.(windowId, runtimeContext) ?? getReadRouter?.(windowId, runtimeContext) ?? router;
11562
11563
  void queryRouter.query(filters, sanitizeQueryOptions(m.options)).then(
11563
11564
  (result2) => send({
11564
11565
  type: "outbox.query.result",
@@ -11590,7 +11591,8 @@ function createOutboxService(options) {
11590
11591
  send({ type: "outbox.closed", subId, ...reason === void 0 ? {} : { reason } });
11591
11592
  }
11592
11593
  };
11593
- subscriptions.set(subKey, router.subscribe(filters, sanitizeSubscribeOptions(m.options), sink));
11594
+ const readRouter = getReadRouter?.(windowId, runtimeContext) ?? router;
11595
+ subscriptions.set(subKey, readRouter.subscribe(filters, sanitizeSubscribeOptions(m.options), sink));
11594
11596
  }
11595
11597
  function handleClose(windowId, msg, send) {
11596
11598
  const m = msg;
@@ -11645,7 +11647,7 @@ function createOutboxService(options) {
11645
11647
  handleMessage(windowId, message, send) {
11646
11648
  switch (message.type) {
11647
11649
  case "outbox.getEvent":
11648
- handleGetEvent(router, message, send);
11650
+ handleGetEvent(getReadRouter?.(windowId, runtimeContext) ?? router, message, send);
11649
11651
  return;
11650
11652
  case "outbox.query":
11651
11653
  handleQuery(windowId, message, send);
@@ -16266,2224 +16268,2498 @@ function cancelled2(uploadId) {
16266
16268
  return { ok: false, uploadId, status: "cancelled", rail: "blossom", error: "user cancelled" };
16267
16269
  }
16268
16270
 
16269
- // ../nip/dist/chunk-PSENX3MS.js
16270
- function parseNip65RelayList(event) {
16271
- return event.tags.flatMap((tag) => {
16272
- if (tag[0] !== "r" || typeof tag[1] !== "string" || tag[1].length === 0) return [];
16273
- const marker = tag[2];
16274
- const read = marker !== "write";
16275
- const write = marker !== "read";
16276
- return [{ url: tag[1], read, write }];
16277
- });
16278
- }
16279
- function selectWriteRelays(entries) {
16280
- return dedupe(entries.filter((e) => e.write).map((e) => e.url));
16281
- }
16282
- function selectReadRelays(entries) {
16283
- return dedupe(entries.filter((e) => e.read).map((e) => e.url));
16271
+ // ../nip/dist/chunk-JT5WCCCX.js
16272
+ function computeAggregateHash(entries) {
16273
+ const lines = entries.map((entry) => `${entry.sha256} ${entry.path}
16274
+ `);
16275
+ lines.sort();
16276
+ return bytesToHex2(sha256(new TextEncoder().encode(lines.join(""))));
16284
16277
  }
16285
- function createNip65Registry() {
16286
- const lists = /* @__PURE__ */ new Map();
16287
- function setRelayList(pubkey2, entries) {
16288
- lists.set(pubkey2, entries.map((e) => ({ ...e })));
16289
- }
16290
- function ingest(event) {
16291
- const entries = parseNip65RelayList(event);
16292
- setRelayList(event.pubkey, entries);
16293
- return entries;
16294
- }
16295
- function getRelayList(pubkey2) {
16296
- const entries = lists.get(pubkey2);
16297
- return entries ? entries.map((e) => ({ ...e })) : void 0;
16298
- }
16299
- function resolve(pubkeys, want) {
16300
- const urls = [];
16301
- const seen = /* @__PURE__ */ new Set();
16302
- for (const pubkey2 of pubkeys) {
16303
- const entries = lists.get(pubkey2);
16304
- if (!entries) continue;
16305
- for (const entry of entries) {
16306
- if (entry[want] && !seen.has(entry.url)) {
16307
- seen.add(entry.url);
16308
- urls.push(entry.url);
16309
- }
16310
- }
16278
+ function pathEntriesFromTags(tags) {
16279
+ const entries = [];
16280
+ for (const tag of tags) {
16281
+ if (tag[0] === "path" && typeof tag[1] === "string" && typeof tag[2] === "string" && tag[1].length > 0 && tag[2].length > 0) {
16282
+ entries.push({ path: tag[1], sha256: tag[2] });
16311
16283
  }
16312
- return urls;
16313
16284
  }
16314
- return {
16315
- ingest,
16316
- setRelayList,
16317
- getRelayList,
16318
- has: (pubkey2) => lists.has(pubkey2),
16319
- resolveOutboxRelays: (pubkeys) => resolve(pubkeys, "write"),
16320
- resolveReadRelays: (pubkeys) => resolve(pubkeys, "read"),
16321
- delete: (pubkey2) => lists.delete(pubkey2),
16322
- clear: () => lists.clear()
16323
- };
16285
+ return entries;
16324
16286
  }
16325
- function dedupe(urls) {
16326
- const seen = /* @__PURE__ */ new Set();
16327
- const out = [];
16328
- for (const url of urls) {
16329
- if (!seen.has(url)) {
16330
- seen.add(url);
16331
- out.push(url);
16287
+ function aggregateTagValue(tags) {
16288
+ for (const tag of tags) {
16289
+ if (tag[0] === "x" && tag[2] === "aggregate" && typeof tag[1] === "string" && tag[1].length > 0) {
16290
+ return tag[1];
16332
16291
  }
16333
16292
  }
16334
- return out;
16293
+ return void 0;
16335
16294
  }
16336
16295
 
16337
- // src/browser-relay-runtime.ts
16338
- var PAJA_NIP65_RELAY_LIST_KIND = 10002;
16339
- var PAJA_CONTACT_LIST_KIND = 3;
16340
- var PAJA_WEBRTC_SIGNAL_KIND = 25050;
16341
- var NIP17_GIFT_WRAP_KIND2 = 1059;
16342
- var PAJA_CONTACT_LIST_CANDIDATE_LIMIT = 64;
16343
- var PAJA_LIVE_QUERY_WAIT_MS = 4e3;
16344
- var contactListCandidateQueries = /* @__PURE__ */ new WeakMap();
16345
- function matchesFilter2(event, filter) {
16346
- const ids = filter.ids;
16347
- if (ids && !ids.some((id) => event.id === id || event.id.startsWith(id))) return false;
16348
- const authors = filter.authors;
16349
- if (authors && !authors.some((author) => event.pubkey === author || event.pubkey.startsWith(author))) return false;
16350
- const kinds = filter.kinds;
16351
- if (kinds && !kinds.includes(event.kind)) return false;
16352
- if (typeof filter.since === "number" && event.created_at < filter.since) return false;
16353
- if (typeof filter.until === "number" && event.created_at > filter.until) return false;
16354
- for (const [key, value] of Object.entries(filter)) {
16355
- if (!key.startsWith("#") || !Array.isArray(value)) continue;
16356
- const tagName = key.slice(1);
16357
- const allowed2 = value.filter((item) => typeof item === "string");
16358
- if (allowed2.length === 0) continue;
16359
- if (!event.tags.some((tag) => tag[0] === tagName && typeof tag[1] === "string" && allowed2.includes(tag[1]))) return false;
16360
- }
16361
- return true;
16296
+ // ../nip/dist/chunk-F6ABV5KZ.js
16297
+ var MIB = 1024 * 1024;
16298
+ var NAPPLET_ARTIFACT_CACHE_NAME = "kehto:napplet-artifacts:v1";
16299
+ var SCHEMA_VERSION = 1;
16300
+ var DEFAULT_BASE_URL = "https://kehto.invalid";
16301
+ var DEFAULT_UNKNOWN_BUDGET_BYTES = 32 * MIB;
16302
+ var DEFAULT_SOFT_CEILING_BYTES = 128 * MIB;
16303
+ var DEFAULT_HARD_CEILING_BYTES = 256 * MIB;
16304
+ var DEFAULT_FOREGROUND_TTL_MS = 15 * 60 * 1e3;
16305
+ var DEFAULT_BACKGROUND_TTL_MS = 60 * 60 * 1e3;
16306
+ function emptyIndex(now2) {
16307
+ return {
16308
+ schemaVersion: SCHEMA_VERSION,
16309
+ updatedAt: now2,
16310
+ blobs: {},
16311
+ aggregates: {},
16312
+ coordinates: {}
16313
+ };
16362
16314
  }
16363
- function matchesAnyFilter2(event, filters) {
16364
- return filters.length === 0 || filters.some((filter) => matchesFilter2(event, filter));
16315
+ function aggregateKey(dTag, aggregateHash) {
16316
+ return `${encodeURIComponent(dTag)}:${aggregateHash}`;
16365
16317
  }
16366
- function normalizedFilters(filters) {
16367
- return Array.isArray(filters) ? filters : [filters];
16318
+ function coordinateKey(kind, pubkey2, dTag) {
16319
+ return `${kind}:${pubkey2}:${encodeURIComponent(dTag)}`;
16368
16320
  }
16369
- function applyFilterLimit(events, filter) {
16370
- const limit = typeof filter.limit === "number" && filter.limit >= 0 ? filter.limit : void 0;
16371
- if (limit === void 0) return events;
16372
- return [...events].sort((a, b) => b.created_at - a.created_at).slice(0, limit);
16321
+ function isCoordinateFresh(coordinate, options = {}) {
16322
+ const now2 = options.now ?? Date.now();
16323
+ const ttl = options.background ? coordinate.backgroundTtlMs : coordinate.foregroundTtlMs;
16324
+ return ttl === Number.POSITIVE_INFINITY || now2 - coordinate.lastResolvedAt <= ttl;
16373
16325
  }
16374
- function collectMemoryEvents(events, filters) {
16375
- const out = /* @__PURE__ */ new Map();
16376
- const activeFilters = filters.length > 0 ? filters : [{}];
16377
- for (const filter of activeFilters) {
16378
- for (const event of applyFilterLimit(events.filter((candidate) => matchesFilter2(candidate, filter)), filter)) {
16379
- out.set(event.id, event);
16380
- }
16381
- }
16382
- return [...out.values()].sort((a, b) => b.created_at - a.created_at);
16326
+ function byteLength2(bytes) {
16327
+ return bytes.byteLength;
16383
16328
  }
16384
- function subscribeLive(pool, relayUrls2, filters, next) {
16385
- const activeFilters = filters.length > 0 ? filters : [{}];
16386
- const requests = relayUrls2.flatMap((url) => activeFilters.map((filter) => ({ url, filter })));
16387
- if (requests.length === 0) {
16388
- queueMicrotask(() => next("EOSE"));
16389
- return { unsubscribe() {
16390
- } };
16391
- }
16392
- const sub = pool.subscribeMap(requests, {
16393
- label: "kehto-paja-runtime",
16394
- maxWait: PAJA_LIVE_QUERY_WAIT_MS,
16395
- onevent: (event) => next(event),
16396
- oneose: () => next("EOSE")
16397
- });
16398
- return {
16399
- unsubscribe() {
16400
- void sub.close("paja unsubscribe");
16401
- }
16402
- };
16329
+ function encodeKeyPart(value) {
16330
+ return encodeURIComponent(value).replaceAll("%2F", "%252F");
16403
16331
  }
16404
- function queryLiveBounded(pool, relayUrls2, filter, maxWaitMs, limit, signal) {
16405
- if (limit === 0 || signal?.aborted) return Promise.resolve([]);
16406
- return new Promise((resolve) => {
16407
- const events = [];
16408
- let settled = false;
16409
- let closeRequested = false;
16410
- let closeReason = "paja query limit reached";
16411
- let subscription;
16412
- let abort;
16413
- const finish = () => {
16414
- if (settled) return;
16415
- settled = true;
16416
- if (abort) signal?.removeEventListener("abort", abort);
16417
- resolve(events);
16418
- };
16419
- const close = (reason = closeReason) => {
16420
- closeRequested = true;
16421
- closeReason = reason;
16422
- if (!subscription) return;
16423
- void Promise.resolve(subscription.close(reason)).catch(() => {
16424
- });
16425
- finish();
16426
- };
16427
- abort = () => close("paja query aborted");
16428
- signal?.addEventListener("abort", abort, { once: true });
16429
- subscription = pool.subscribeEose(relayUrls2, filter, {
16430
- label: "kehto-paja-runtime",
16431
- maxWait: maxWaitMs,
16432
- onevent(event) {
16433
- if (events.length >= limit) return;
16434
- events.push(event);
16435
- if (events.length === limit) close();
16436
- },
16437
- onclose: finish
16438
- });
16439
- if (closeRequested) close();
16440
- });
16332
+ function cloneBytes(bytes) {
16333
+ return new Uint8Array(bytes);
16441
16334
  }
16442
- async function queryLive(pool, relayUrls2, filters, maxWaitMs = PAJA_LIVE_QUERY_WAIT_MS, collectUntilLimit = false, signal) {
16443
- const activeFilters = filters.length > 0 ? filters : [{}];
16444
- const batches = await Promise.all(activeFilters.map((filter) => {
16445
- const limit = typeof filter.limit === "number" && filter.limit >= 0 ? filter.limit : void 0;
16446
- if (collectUntilLimit && limit !== void 0) return queryLiveBounded(pool, relayUrls2, filter, maxWaitMs, limit, signal);
16447
- return pool.querySync(relayUrls2, filter, {
16448
- label: "kehto-paja-runtime",
16449
- maxWait: maxWaitMs
16450
- });
16451
- }));
16452
- const out = /* @__PURE__ */ new Map();
16453
- for (const event of batches.flat()) out.set(event.id, event);
16454
- return [...out.values()].sort((a, b) => b.created_at - a.created_at);
16335
+ function responseBody(bytes) {
16336
+ return cloneBytes(bytes).buffer;
16455
16337
  }
16456
- async function publishLive(pool, relayUrls2, event) {
16457
- const results = await Promise.allSettled(pool.publish(relayUrls2, event));
16458
- return Object.fromEntries(relayUrls2.map((relayUrl2, index) => [relayUrl2, results[index]?.status === "fulfilled"]));
16338
+ function normalizeBaseUrl(baseUrl) {
16339
+ return baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
16459
16340
  }
16460
- async function countLive(pool, relayUrls2, filters) {
16461
- let failure3 = new Error("count unavailable");
16462
- for (const relayUrl2 of relayUrls2) {
16463
- const controller = new AbortController();
16464
- let timeout;
16465
- const timedOut = new Promise((_resolve, reject2) => {
16466
- timeout = setTimeout(() => {
16467
- controller.abort();
16468
- reject2(new Error("count timeout"));
16469
- }, PAJA_LIVE_QUERY_WAIT_MS);
16470
- });
16471
- try {
16472
- const relay = await Promise.race([
16473
- pool.ensureRelay(relayUrl2, {
16474
- connectionTimeout: PAJA_LIVE_QUERY_WAIT_MS,
16475
- abort: controller.signal
16476
- }),
16477
- timedOut
16478
- ]);
16479
- const count = await Promise.race([
16480
- relay.count(filters, { id: null }),
16481
- timedOut
16482
- ]);
16483
- if (!Number.isSafeInteger(count) || count < 0) throw new Error("invalid count");
16484
- return { count, relay: relayUrl2 };
16485
- } catch (error) {
16486
- failure3 = error;
16487
- } finally {
16488
- if (timeout !== void 0) clearTimeout(timeout);
16489
- }
16490
- }
16491
- throw failure3;
16492
- }
16493
- function createPajaRelayBackend(getSimulation, confirmRequest, livePool = new SimplePool()) {
16494
- livePool.trackRelays = true;
16495
- const fixtureEvents = getSimulation().relay.fixtures.flatMap(toNostrEvent);
16496
- const acceptedMemoryEvents = [];
16497
- const subscribers = /* @__PURE__ */ new Set();
16498
- const isAvailable = () => getSimulation().relay.mode !== "disabled" && getPajaRelayUrls(getSimulation()).length > 0;
16499
- const cachedEvents = () => getSimulation().relay.mode === "memory" ? [...fixtureEvents, ...acceptedMemoryEvents] : [];
16500
- const query = async (relayUrls2, filters, maxWaitMs) => {
16501
- const cached = collectMemoryEvents(cachedEvents(), filters);
16502
- if (getSimulation().relay.mode !== "live" || relayUrls2.length === 0) return cached;
16503
- const liveEvents = await queryLive(livePool, relayUrls2, filters, maxWaitMs);
16504
- const out = /* @__PURE__ */ new Map();
16505
- for (const event of [...cached, ...liveEvents]) out.set(event.id, event);
16506
- return [...out.values()].sort((a, b) => b.created_at - a.created_at);
16507
- };
16508
- const queryContactListCandidates = async (relayUrls2, filters, maxWaitMs, signal) => {
16509
- const cached = collectMemoryEvents(cachedEvents(), filters);
16510
- if (signal?.aborted || getSimulation().relay.mode !== "live" || relayUrls2.length === 0) return cached;
16511
- const liveEvents = await queryLive(livePool, relayUrls2, filters, maxWaitMs, true, signal);
16512
- const out = /* @__PURE__ */ new Map();
16513
- for (const event of [...cached, ...liveEvents]) out.set(event.id, event);
16514
- return [...out.values()].sort((a, b) => b.created_at - a.created_at);
16515
- };
16516
- function retainPublishedEvent(event, mode) {
16517
- if (mode !== "memory") return;
16518
- acceptedMemoryEvents.push(event);
16519
- for (const subscriber of subscribers) {
16520
- if (matchesAnyFilter2(event, subscriber.filters)) subscriber.next(event);
16521
- }
16522
- }
16523
- async function attemptPublish(relayUrls2, event) {
16524
- const simulation = getSimulation();
16525
- const rejected = Object.fromEntries(relayUrls2.map((url) => [url, false]));
16526
- if (simulation.relay.mode === "disabled") {
16527
- return { outcomes: rejected, error: "relay unavailable" };
16528
- }
16529
- if (!await confirmRequest({ action: "publish", event })) {
16530
- return { outcomes: rejected, error: "publish denied" };
16531
- }
16532
- const outcomes = simulation.relay.mode === "live" ? await publishLive(livePool, relayUrls2, event) : Object.fromEntries(relayUrls2.map((url) => [url, true]));
16533
- if (!Object.values(outcomes).some(Boolean)) {
16534
- return { outcomes, error: "publish failed" };
16535
- }
16536
- retainPublishedEvent(event, simulation.relay.mode);
16537
- return { outcomes };
16538
- }
16539
- const backend = {
16540
- subscription(relayUrls2, filtersInput) {
16541
- return {
16542
- subscribe(next) {
16543
- const filters = normalizedFilters(filtersInput);
16544
- const subscriber = {
16545
- filters,
16546
- next: (item) => next(item)
16547
- };
16548
- subscribers.add(subscriber);
16549
- for (const event of collectMemoryEvents(cachedEvents(), filters)) next(event);
16550
- const liveSub = getSimulation().relay.mode === "live" ? subscribeLive(livePool, relayUrls2, filters, subscriber.next) : null;
16551
- queueMicrotask(() => {
16552
- if (subscribers.has(subscriber) && !liveSub) next("EOSE");
16553
- });
16554
- return {
16555
- unsubscribe() {
16556
- subscribers.delete(subscriber);
16557
- liveSub?.unsubscribe();
16558
- }
16559
- };
16560
- }
16561
- };
16562
- },
16563
- async publish(relayUrls2, event) {
16564
- const attempt = await attemptPublish(relayUrls2, event);
16565
- if (attempt.error) throw new Error(attempt.error);
16566
- },
16567
- request(relayUrls2, filtersInput) {
16568
- return {
16569
- subscribe(observer) {
16570
- const filters = normalizedFilters(filtersInput);
16571
- let active = true;
16572
- query(relayUrls2, filters).then((matched) => {
16573
- if (!active) return;
16574
- for (const event of matched) observer.next(event);
16575
- observer.complete();
16576
- }).catch(() => {
16577
- if (active) observer.error();
16578
- });
16579
- return { unsubscribe() {
16580
- active = false;
16581
- } };
16582
- }
16583
- };
16584
- },
16585
- async count(relayUrls2, filters) {
16586
- if (getSimulation().relay.mode !== "live") throw new Error("count unavailable");
16587
- return (await countLive(livePool, relayUrls2, normalizedFilters(filters))).count;
16588
- },
16589
- async countWithRelay(relayUrls2, filters) {
16590
- if (getSimulation().relay.mode !== "live") throw new Error("count unavailable");
16591
- return countLive(livePool, relayUrls2, normalizedFilters(filters));
16592
- },
16593
- observedRelayUrls(eventId) {
16594
- return [...livePool.seenOn?.get(eventId) ?? []].map((relay) => relay.url);
16595
- },
16596
- query,
16597
- async publishToRelays(relayUrls2, event) {
16598
- return (await attemptPublish(relayUrls2, event)).outcomes;
16599
- },
16600
- async publishWebrtcSignal(relayUrls2, event) {
16601
- if (getSimulation().relay.mode !== "live" || relayUrls2.length === 0 || event.kind !== PAJA_WEBRTC_SIGNAL_KIND || !verifyEvent(event)) {
16602
- throw new Error("signaling unavailable");
16603
- }
16604
- const outcomes = await publishLive(livePool, relayUrls2, event);
16605
- if (!Object.values(outcomes).some(Boolean)) throw new Error("signaling unavailable");
16606
- retainPublishedEvent(event, "live");
16607
- },
16608
- async publishDmGiftWrap(relayUrls2, event) {
16609
- if (getSimulation().relay.mode !== "live" || relayUrls2.length === 0 || event.kind !== NIP17_GIFT_WRAP_KIND2 || !verifyEvent(event)) {
16610
- throw new Error("DM relay publication failed");
16611
- }
16612
- const outcomes = await publishLive(livePool, relayUrls2, event);
16613
- if (!Object.values(outcomes).some(Boolean)) throw new Error("DM relay publication failed");
16614
- retainPublishedEvent(event, "live");
16615
- },
16616
- isAvailable,
16617
- close() {
16618
- livePool.destroy();
16619
- }
16620
- };
16621
- contactListCandidateQueries.set(backend, queryContactListCandidates);
16622
- return backend;
16623
- }
16624
- function toNostrEvent(value) {
16625
- if (typeof value === "object" && value !== null && typeof value.id === "string" && typeof value.pubkey === "string" && typeof value.kind === "number" && Array.isArray(value.tags) && typeof value.content === "string" && typeof value.sig === "string") {
16626
- return [value];
16627
- }
16628
- return [];
16341
+ function resolveBaseUrl(baseUrl) {
16342
+ if (baseUrl) return normalizeBaseUrl(baseUrl);
16343
+ const maybeLocation = globalThis;
16344
+ if (maybeLocation.location?.origin) return normalizeBaseUrl(maybeLocation.location.origin);
16345
+ return normalizeBaseUrl(DEFAULT_BASE_URL);
16629
16346
  }
16630
- function getPajaRelayUrls(simulation) {
16631
- return simulation.relay.mode === "disabled" ? [] : [...simulation.relay.urls];
16347
+ async function responseBytes(response) {
16348
+ return new Uint8Array(await response.arrayBuffer());
16632
16349
  }
16633
- function dedupeRelayUrls(urls) {
16634
- const out = /* @__PURE__ */ new Set();
16635
- for (const url of urls) {
16636
- const trimmed = url.trim();
16637
- if (trimmed.length > 0) out.add(trimmed);
16638
- }
16639
- return [...out];
16350
+ async function responseJson(response) {
16351
+ return response.json();
16640
16352
  }
16641
- async function getSignerRelayUrls(signerProvider, direction) {
16642
- const signer = signerProvider?.getSigner();
16643
- if (!signer?.getRelays) return [];
16644
- try {
16645
- const relays = await signer.getRelays();
16646
- return dedupeRelayUrls(Object.entries(relays).flatMap(([url, permissions]) => {
16647
- if (direction === "read" && permissions.read) return [url];
16648
- if (direction === "write" && permissions.write) return [url];
16649
- return [];
16650
- }));
16651
- } catch {
16652
- return [];
16353
+ function refCounts(index) {
16354
+ const counts = {};
16355
+ for (const aggregate of Object.values(index.aggregates)) {
16356
+ for (const hash of aggregate.blobHashes) counts[hash] = (counts[hash] ?? 0) + 1;
16653
16357
  }
16358
+ return counts;
16654
16359
  }
16655
- async function getBootstrapRelayUrls(getSimulation, signerProvider, getHostRelayUrls) {
16656
- return dedupeRelayUrls([
16657
- ...getHostRelayUrls?.() ?? getPajaRelayUrls(getSimulation()),
16658
- ...await getSignerRelayUrls(signerProvider, "read")
16659
- ]);
16660
- }
16661
- function createPajaContactListLoader(backend, getSimulation, signerProvider, getHostRelayUrls) {
16662
- return async (pubkey2, signal) => {
16663
- if (!/^[0-9a-fA-F]{64}$/.test(pubkey2) || signal?.aborted) return [];
16664
- const relayUrls2 = await getBootstrapRelayUrls(getSimulation, signerProvider, getHostRelayUrls);
16665
- if (signal?.aborted) return [];
16666
- const filters = [{
16667
- kinds: [PAJA_CONTACT_LIST_KIND],
16668
- authors: [pubkey2],
16669
- limit: PAJA_CONTACT_LIST_CANDIDATE_LIMIT
16670
- }];
16671
- const contactQuery = contactListCandidateQueries.get(backend);
16672
- const candidates = contactQuery ? await contactQuery(relayUrls2, filters, PAJA_LIVE_QUERY_WAIT_MS, signal) : await backend.query(relayUrls2, filters, PAJA_LIVE_QUERY_WAIT_MS);
16673
- if (signal?.aborted) return [];
16674
- return candidates.filter((event) => event.kind === PAJA_CONTACT_LIST_KIND && event.pubkey.toLowerCase() === pubkey2.toLowerCase()).sort((left, right) => right.created_at - left.created_at || left.id.localeCompare(right.id)).slice(0, PAJA_CONTACT_LIST_CANDIDATE_LIMIT);
16675
- };
16676
- }
16677
- function latestEvent(events, kind, pubkey2) {
16678
- return events.filter((event) => event.kind === kind && event.pubkey === pubkey2).sort((a, b) => b.created_at - a.created_at)[0];
16360
+ function cachedSize(index) {
16361
+ const blobBytes = Object.values(index.blobs).reduce((sum, entry) => sum + entry.size, 0);
16362
+ const aggregateBytes = Object.values(index.aggregates).reduce((sum, entry) => sum + entry.size, 0);
16363
+ return blobBytes + aggregateBytes;
16679
16364
  }
16680
- function createPajaRelayListLoader(backend, getSimulation, signerProvider, getHostRelayUrls) {
16681
- const registry2 = createNip65Registry();
16682
- return async (pubkeys) => {
16683
- const uniquePubkeys = [...new Set(pubkeys.filter((pubkey2) => /^[0-9a-fA-F]{64}$/.test(pubkey2)))];
16684
- const missing = uniquePubkeys.filter((pubkey2) => !registry2.has(pubkey2));
16685
- if (missing.length > 0) {
16686
- const events = await backend.query(await getBootstrapRelayUrls(
16687
- getSimulation,
16688
- signerProvider,
16689
- getHostRelayUrls
16690
- ), [{
16691
- kinds: [PAJA_NIP65_RELAY_LIST_KIND],
16692
- authors: missing,
16693
- limit: Math.max(missing.length * 2, 10)
16694
- }], PAJA_LIVE_QUERY_WAIT_MS);
16695
- for (const pubkey2 of missing) {
16696
- const event = latestEvent(events, PAJA_NIP65_RELAY_LIST_KIND, pubkey2);
16697
- if (event) registry2.ingest(event);
16698
- }
16365
+ var CacheStorageNappletArtifactCache = class {
16366
+ cacheStorage;
16367
+ storage;
16368
+ cacheName;
16369
+ baseUrl;
16370
+ now;
16371
+ activeAggregates = /* @__PURE__ */ new Set();
16372
+ onDiagnostic;
16373
+ unknownBudgetBytes;
16374
+ softCeilingBytes;
16375
+ hardCeilingBytes;
16376
+ cachePromise;
16377
+ constructor(options = {}) {
16378
+ const maybeCacheStorage = options.cacheStorage ?? globalThis.caches;
16379
+ if (!maybeCacheStorage) {
16380
+ throw new Error("Cache Storage is unavailable");
16699
16381
  }
16700
- const out = /* @__PURE__ */ new Map();
16701
- for (const pubkey2 of uniquePubkeys) {
16702
- const entries = registry2.getRelayList(pubkey2);
16703
- if (entries) {
16704
- out.set(pubkey2, {
16705
- read: selectReadRelays(entries),
16706
- write: selectWriteRelays(entries)
16707
- });
16382
+ this.cacheStorage = maybeCacheStorage;
16383
+ this.storage = options.storage ?? globalThis.navigator?.storage;
16384
+ this.cacheName = options.cacheName ?? NAPPLET_ARTIFACT_CACHE_NAME;
16385
+ this.baseUrl = resolveBaseUrl(options.baseUrl);
16386
+ this.now = options.now ?? Date.now;
16387
+ this.onDiagnostic = options.onDiagnostic;
16388
+ this.unknownBudgetBytes = options.unknownBudgetBytes ?? DEFAULT_UNKNOWN_BUDGET_BYTES;
16389
+ this.softCeilingBytes = options.softCeilingBytes ?? DEFAULT_SOFT_CEILING_BYTES;
16390
+ this.hardCeilingBytes = options.hardCeilingBytes ?? DEFAULT_HARD_CEILING_BYTES;
16391
+ }
16392
+ async readBlob(sha256Hex) {
16393
+ try {
16394
+ const cache2 = await this.open();
16395
+ const response = await cache2.match(this.blobUrl(sha256Hex));
16396
+ if (!response) return void 0;
16397
+ const bytes = await responseBytes(response);
16398
+ const index = await this.readIndex(cache2);
16399
+ const entry = index.blobs[sha256Hex];
16400
+ if (entry) {
16401
+ entry.lastAccessed = this.now();
16402
+ index.updatedAt = entry.lastAccessed;
16403
+ await this.writeIndex(cache2, index);
16708
16404
  }
16405
+ return bytes;
16406
+ } catch (cause) {
16407
+ this.diagnostic({ type: "cache-read-failed", message: `failed to read blob ${sha256Hex}`, cause });
16408
+ return void 0;
16709
16409
  }
16710
- return out;
16711
- };
16712
- }
16713
- function createPajaOutboxRelayPool(backend) {
16714
- return {
16715
- subscribe(filters, relayUrls2, callback) {
16716
- return backend.subscription(relayUrls2, filters).subscribe((item) => callback(item));
16717
- },
16718
- publish(event, relayUrls2) {
16719
- return backend.publishToRelays(relayUrls2, event);
16720
- },
16721
- isAvailable() {
16722
- return backend.isAvailable();
16723
- }
16724
- };
16725
- }
16726
-
16727
- // src/browser-social-cache.ts
16728
- var HEX_PUBKEY = /^[0-9a-f]{64}$/i;
16729
- var FOLLOW_PARSE_YIELD_EVERY = 64;
16730
- var PROFILE_WARM_YIELD_EVERY = 64;
16731
- function createPajaSocialCache(options) {
16732
- let generation = 0;
16733
- let activeRefreshController;
16734
- const snapshots = /* @__PURE__ */ new Map();
16735
- async function loadFollows(capturedPubkey) {
16736
- const normalizedPubkey = normalizePubkey(capturedPubkey);
16737
- if (!normalizedPubkey) return [];
16738
- const existing = snapshots.get(normalizedPubkey);
16739
- if (existing) return [...existing.follows];
16740
- const capturedGeneration = generation;
16741
- const follows = await verifiedFollows(normalizedPubkey);
16742
- const warmed = snapshots.get(normalizedPubkey);
16743
- if (warmed) return [...warmed.follows];
16744
- if (generation === capturedGeneration) {
16745
- snapshots.set(normalizedPubkey, { follows, profiles: /* @__PURE__ */ new Map() });
16410
+ }
16411
+ async deleteBlob(sha256Hex) {
16412
+ try {
16413
+ const cache2 = await this.open();
16414
+ await cache2.delete(this.blobUrl(sha256Hex));
16415
+ const index = await this.readIndex(cache2);
16416
+ delete index.blobs[sha256Hex];
16417
+ index.updatedAt = this.now();
16418
+ await this.writeIndex(cache2, index);
16419
+ } catch (cause) {
16420
+ this.diagnostic({ type: "cache-delete-failed", message: `failed to delete blob ${sha256Hex}`, cause });
16746
16421
  }
16747
- return [...follows];
16748
16422
  }
16749
- async function verifiedFollows(capturedPubkey, isStillCurrent, signal) {
16750
- const candidates = await options.loadContactList(capturedPubkey, signal);
16751
- const verified = [];
16752
- for (const candidate of candidates) {
16753
- if (isStillCurrent && !isStillCurrent()) return [];
16754
- if (!isContactCandidate(candidate, capturedPubkey)) continue;
16423
+ async writeVerifiedResolution(input) {
16424
+ try {
16425
+ await this.writeVerifiedResolutionOnce(input);
16426
+ } catch (firstCause) {
16755
16427
  try {
16756
- if (await options.verifyEvent(candidate)) verified.push(candidate);
16757
- } catch {
16428
+ await this.prune(input.now ?? this.now());
16429
+ await this.writeVerifiedResolutionOnce(input);
16430
+ } catch (cause) {
16431
+ this.diagnostic({
16432
+ type: "cache-write-failed",
16433
+ message: "failed to write verified napplet artifacts after prune retry",
16434
+ cause: cause ?? firstCause
16435
+ });
16758
16436
  }
16759
16437
  }
16760
- return contactPubkeys(selectReplacement(verified), isStillCurrent);
16761
16438
  }
16762
- async function refreshActiveIdentity() {
16763
- activeRefreshController?.abort();
16764
- activeRefreshController = void 0;
16765
- const currentGeneration = ++generation;
16766
- const capturedPubkey = normalizePubkey(options.getActivePubkey() ?? "");
16767
- if (!capturedPubkey) return;
16768
- const controller = new AbortController();
16769
- activeRefreshController = controller;
16770
- const isStillCurrent = () => !controller.signal.aborted && isCurrent(capturedPubkey, currentGeneration);
16439
+ async writeCoordinate(input) {
16440
+ const cache2 = await this.open();
16441
+ const now2 = this.now();
16442
+ const index = await this.readIndex(cache2);
16443
+ const key = coordinateKey(input.kind, input.pubkey, input.dTag);
16444
+ index.coordinates[key] = {
16445
+ key,
16446
+ kind: input.kind,
16447
+ pubkey: input.pubkey,
16448
+ dTag: input.dTag,
16449
+ aggregateHash: input.aggregateHash,
16450
+ lastResolvedAt: input.lastResolvedAt ?? now2,
16451
+ foregroundTtlMs: input.foregroundTtlMs ?? DEFAULT_FOREGROUND_TTL_MS,
16452
+ backgroundTtlMs: input.backgroundTtlMs ?? DEFAULT_BACKGROUND_TTL_MS
16453
+ };
16454
+ index.updatedAt = now2;
16455
+ await this.writeIndex(cache2, index);
16456
+ }
16457
+ async getCoordinate(input, options = {}) {
16458
+ const cache2 = await this.open();
16459
+ const index = await this.readIndex(cache2);
16460
+ const coordinate = index.coordinates[coordinateKey(input.kind, input.pubkey, input.dTag)];
16461
+ if (!coordinate) return void 0;
16462
+ return { ...coordinate, fresh: isCoordinateFresh(coordinate, options) };
16463
+ }
16464
+ async touchAggregate(dTag, aggregateHash, now2 = this.now()) {
16465
+ const cache2 = await this.open();
16466
+ const index = await this.readIndex(cache2);
16467
+ const key = aggregateKey(dTag, aggregateHash);
16468
+ const aggregate = index.aggregates[key];
16469
+ if (!aggregate) return;
16470
+ aggregate.lastAccessed = now2;
16471
+ for (const hash of aggregate.blobHashes) {
16472
+ if (index.blobs[hash]) index.blobs[hash].lastAccessed = now2;
16473
+ }
16474
+ index.updatedAt = now2;
16475
+ await this.writeIndex(cache2, index);
16476
+ }
16477
+ markAggregateActive(dTag, aggregateHash) {
16478
+ this.activeAggregates.add(aggregateKey(dTag, aggregateHash));
16479
+ }
16480
+ releaseAggregateActive(dTag, aggregateHash) {
16481
+ this.activeAggregates.delete(aggregateKey(dTag, aggregateHash));
16482
+ }
16483
+ async prune(now2 = this.now()) {
16771
16484
  try {
16772
- const follows = await verifiedFollows(capturedPubkey, isStillCurrent, controller.signal);
16773
- if (!isStillCurrent()) return;
16774
- const snapshot = { follows, profiles: /* @__PURE__ */ new Map() };
16775
- snapshots.set(capturedPubkey, snapshot);
16776
- for (let index = 0; index < follows.length; index += 1) {
16777
- if (!isStillCurrent()) return;
16778
- const author = follows[index];
16779
- let warmed;
16780
- try {
16781
- warmed = await options.baseRouter.query(
16782
- [{ kinds: [0], authors: [author], limit: 1 }],
16783
- { authors: [author], limit: 1 }
16784
- );
16785
- } catch {
16786
- }
16787
- if (!isStillCurrent()) return;
16788
- if (warmed) {
16789
- const profile = profileResult(warmed, author);
16790
- if (profile) snapshot.profiles.set(author, profile);
16485
+ const cache2 = await this.open();
16486
+ const index = await this.readIndex(cache2);
16487
+ let size = cachedSize(index);
16488
+ const budget = await this.budgetBytes();
16489
+ const hardBudget = await this.hardBudgetBytes();
16490
+ const shouldPrune = size > budget || await this.originPressureHigh();
16491
+ if (!shouldPrune) return;
16492
+ this.rewriteRefCounts(index);
16493
+ for (const [hash, blob] of Object.entries(index.blobs)) {
16494
+ if (size <= budget) break;
16495
+ if (blob.refCount > 0) continue;
16496
+ await cache2.delete(this.blobUrl(hash));
16497
+ delete index.blobs[hash];
16498
+ size -= blob.size;
16499
+ }
16500
+ const currentAggregateHashes = new Set(
16501
+ Object.values(index.coordinates).map((coordinate) => coordinate.aggregateHash)
16502
+ );
16503
+ const aggregates = Object.values(index.aggregates).filter((entry) => !this.activeAggregates.has(entry.key)).sort((a, b) => {
16504
+ const currentA = currentAggregateHashes.has(a.aggregateHash) ? 1 : 0;
16505
+ const currentB = currentAggregateHashes.has(b.aggregateHash) ? 1 : 0;
16506
+ if (currentA !== currentB) return currentA - currentB;
16507
+ return a.lastAccessed - b.lastAccessed;
16508
+ });
16509
+ for (const aggregate of aggregates) {
16510
+ if (size <= budget) break;
16511
+ await cache2.delete(this.aggregateUrl(aggregate.key));
16512
+ delete index.aggregates[aggregate.key];
16513
+ size -= aggregate.size;
16514
+ this.rewriteRefCounts(index);
16515
+ }
16516
+ if (size > hardBudget) {
16517
+ const active = Object.values(index.aggregates).filter((entry) => this.activeAggregates.has(entry.key)).sort((a, b) => a.lastAccessed - b.lastAccessed);
16518
+ for (const aggregate of active) {
16519
+ if (size <= hardBudget) break;
16520
+ await cache2.delete(this.aggregateUrl(aggregate.key));
16521
+ delete index.aggregates[aggregate.key];
16522
+ size -= aggregate.size;
16791
16523
  }
16792
- if ((index + 1) % PROFILE_WARM_YIELD_EVERY === 0 && index + 1 < follows.length) {
16793
- if (!isStillCurrent()) return;
16794
- await yieldToEventLoop();
16795
- if (!isStillCurrent()) return;
16524
+ }
16525
+ this.rewriteRefCounts(index);
16526
+ for (const [hash, blob] of Object.entries(index.blobs)) {
16527
+ if (blob.refCount === 0) {
16528
+ await cache2.delete(this.blobUrl(hash));
16529
+ delete index.blobs[hash];
16796
16530
  }
16797
16531
  }
16798
- } catch {
16799
- } finally {
16800
- if (activeRefreshController === controller) activeRefreshController = void 0;
16532
+ index.updatedAt = now2;
16533
+ await this.writeIndex(cache2, index);
16534
+ } catch (cause) {
16535
+ this.diagnostic({ type: "cache-prune-failed", message: "failed to prune napplet artifact cache", cause });
16801
16536
  }
16802
16537
  }
16803
- function isCurrent(capturedPubkey, currentGeneration) {
16804
- return generation === currentGeneration && normalizePubkey(options.getActivePubkey() ?? "") === capturedPubkey;
16538
+ async snapshotIndex() {
16539
+ return this.readIndex(await this.open());
16805
16540
  }
16806
- function decorate(router, canReadIdentity) {
16807
- return {
16808
- ...router.getEvent ? { getEvent: router.getEvent.bind(router) } : {},
16809
- async query(filters, queryOptions) {
16810
- const canAugmentAtStart = canReadIdentity?.() ?? true;
16811
- const activePubkey = normalizePubkey(options.getActivePubkey() ?? "");
16812
- const snapshot = canAugmentAtStart && activePubkey ? snapshots.get(activePubkey) : void 0;
16813
- const base = await router.query(filters, queryOptions);
16814
- if (!canAugmentAtStart || !(canReadIdentity?.() ?? true)) return base;
16815
- const cached = matchingCachedProfiles(snapshot?.profiles, filters);
16816
- return mergeResult(base, cached, filters, queryOptions);
16541
+ async writeVerifiedResolutionOnce(input) {
16542
+ const cache2 = await this.open();
16543
+ const now2 = input.now ?? this.now();
16544
+ const index = await this.readIndex(cache2);
16545
+ const blobHashes = [];
16546
+ for (const pathEntry of input.manifest.paths) {
16547
+ const bytes = input.files.get(pathEntry.path);
16548
+ if (!bytes) continue;
16549
+ blobHashes.push(pathEntry.sha256);
16550
+ await cache2.put(this.blobUrl(pathEntry.sha256), new Response(responseBody(bytes)));
16551
+ index.blobs[pathEntry.sha256] = {
16552
+ size: byteLength2(bytes),
16553
+ lastAccessed: now2,
16554
+ refCount: index.blobs[pathEntry.sha256]?.refCount ?? 0
16555
+ };
16556
+ }
16557
+ const key = aggregateKey(input.manifest.dTag, input.manifest.aggregateHash);
16558
+ const record = {
16559
+ schemaVersion: SCHEMA_VERSION,
16560
+ dTag: input.manifest.dTag,
16561
+ aggregateHash: input.manifest.aggregateHash,
16562
+ manifest: {
16563
+ kind: input.manifest.kind,
16564
+ pubkey: input.manifest.pubkey,
16565
+ dTag: input.manifest.dTag,
16566
+ paths: input.manifest.paths.map((entry) => ({ path: entry.path, sha256: entry.sha256 })),
16567
+ requires: [...input.manifest.requires],
16568
+ ...input.manifest.title === void 0 ? {} : { title: input.manifest.title },
16569
+ ...input.manifest.description === void 0 ? {} : { description: input.manifest.description }
16817
16570
  },
16818
- subscribe: router.subscribe.bind(router),
16819
- publish: router.publish.bind(router),
16820
- resolveRelays: router.resolveRelays.bind(router)
16571
+ indexHtml: input.indexHtml,
16572
+ blobHashes,
16573
+ writtenAt: now2
16574
+ };
16575
+ const aggregateBytes = new TextEncoder().encode(JSON.stringify(record));
16576
+ await cache2.put(this.aggregateUrl(key), new Response(responseBody(aggregateBytes), {
16577
+ headers: { "content-type": "application/json" }
16578
+ }));
16579
+ const coordKey = coordinateKey(input.manifest.kind, input.manifest.pubkey, input.manifest.dTag);
16580
+ index.aggregates[key] = {
16581
+ dTag: input.manifest.dTag,
16582
+ aggregateHash: input.manifest.aggregateHash,
16583
+ key,
16584
+ blobHashes,
16585
+ size: byteLength2(aggregateBytes),
16586
+ lastAccessed: now2,
16587
+ coordinateKey: coordKey
16588
+ };
16589
+ index.coordinates[coordKey] = {
16590
+ key: coordKey,
16591
+ kind: input.manifest.kind,
16592
+ pubkey: input.manifest.pubkey,
16593
+ dTag: input.manifest.dTag,
16594
+ aggregateHash: input.manifest.aggregateHash,
16595
+ lastResolvedAt: now2,
16596
+ foregroundTtlMs: DEFAULT_FOREGROUND_TTL_MS,
16597
+ backgroundTtlMs: DEFAULT_BACKGROUND_TTL_MS
16821
16598
  };
16599
+ this.rewriteRefCounts(index);
16600
+ index.updatedAt = now2;
16601
+ await this.writeIndex(cache2, index);
16602
+ await this.prune(now2);
16822
16603
  }
16823
- const unsubscribe = options.subscribeSignerChange?.(() => {
16824
- void refreshActiveIdentity();
16825
- });
16826
- return {
16827
- getFollows: loadFollows,
16828
- refreshActiveIdentity,
16829
- decorate,
16830
- dispose: () => {
16831
- activeRefreshController?.abort();
16832
- unsubscribe?.();
16833
- }
16834
- };
16835
- }
16836
- function normalizePubkey(value) {
16837
- return typeof value === "string" && HEX_PUBKEY.test(value) ? value.toLowerCase() : null;
16838
- }
16839
- function isContactCandidate(candidate, capturedPubkey) {
16840
- if (typeof candidate !== "object" || candidate === null) return false;
16841
- const event = candidate;
16842
- return event.kind === 3 && normalizePubkey(event.pubkey) === capturedPubkey;
16843
- }
16844
- function selectReplacement(events) {
16845
- return [...events].sort((left, right) => {
16846
- const timestampOrder = right.created_at - left.created_at;
16847
- if (timestampOrder !== 0) return timestampOrder;
16848
- if (left.id === right.id) return 0;
16849
- return left.id < right.id ? -1 : 1;
16850
- })[0];
16851
- }
16852
- async function contactPubkeys(event, isStillCurrent) {
16853
- if (!event || !Array.isArray(event.tags)) return [];
16854
- const follows = /* @__PURE__ */ new Set();
16855
- for (let index = 0; index < event.tags.length; index += 1) {
16856
- if (isStillCurrent && !isStillCurrent()) return [];
16857
- const tag = event.tags[index];
16858
- if (Array.isArray(tag) && tag[0] === "p") {
16859
- const pubkey2 = normalizePubkey(tag[1]);
16860
- if (pubkey2) follows.add(pubkey2);
16861
- }
16862
- if ((index + 1) % FOLLOW_PARSE_YIELD_EVERY === 0 && index + 1 < event.tags.length) {
16863
- await yieldToEventLoop();
16864
- if (isStillCurrent && !isStillCurrent()) return [];
16865
- }
16604
+ async open() {
16605
+ this.cachePromise ??= this.cacheStorage.open(this.cacheName);
16606
+ return this.cachePromise;
16866
16607
  }
16867
- return [...follows];
16868
- }
16869
- function profileResult(result2, author) {
16870
- let newest;
16871
- for (const entry of result2.events) {
16872
- if (entry.event.kind !== 0 || normalizePubkey(entry.event.pubkey) !== author) continue;
16873
- if (!newest || isNewerProfile(entry, newest)) newest = entry;
16608
+ indexUrl() {
16609
+ return new URL("__kehto_napplet_cache/index.json", this.baseUrl).toString();
16874
16610
  }
16875
- return newest;
16876
- }
16877
- function isNewerProfile(candidate, existing) {
16878
- if (candidate.event.created_at !== existing.event.created_at) {
16879
- return candidate.event.created_at > existing.event.created_at;
16611
+ blobUrl(hash) {
16612
+ return new URL(`__kehto_napplet_cache/blob/${encodeKeyPart(hash)}`, this.baseUrl).toString();
16880
16613
  }
16881
- return candidate.event.id < existing.event.id;
16882
- }
16883
- function yieldToEventLoop() {
16884
- return new Promise((resolve) => setTimeout(resolve, 0));
16885
- }
16886
- function matchingCachedProfiles(profiles, filters) {
16887
- const readyProfiles = profiles ? [...profiles.values()] : [];
16888
- if (filters.length === 0) return readyProfiles;
16889
- const matched = /* @__PURE__ */ new Map();
16890
- for (const filter of filters) {
16891
- const limit = typeof filter.limit === "number" && filter.limit >= 0 ? filter.limit : void 0;
16892
- let count = 0;
16893
- for (const entry of readyProfiles) {
16894
- if (!matchesAnyFilter2(entry.event, [filter])) continue;
16895
- if (limit !== void 0 && count >= limit) continue;
16896
- count += 1;
16897
- if (!matched.has(entry.event.id)) matched.set(entry.event.id, entry);
16614
+ aggregateUrl(key) {
16615
+ return new URL(`__kehto_napplet_cache/aggregate/${encodeKeyPart(key)}.json`, this.baseUrl).toString();
16616
+ }
16617
+ async readIndex(cache2) {
16618
+ const response = await cache2.match(this.indexUrl());
16619
+ if (!response) return emptyIndex(this.now());
16620
+ try {
16621
+ const index = await responseJson(response);
16622
+ if (index.schemaVersion !== SCHEMA_VERSION) return emptyIndex(this.now());
16623
+ return index;
16624
+ } catch {
16625
+ return emptyIndex(this.now());
16898
16626
  }
16899
16627
  }
16900
- return [...matched.values()];
16901
- }
16902
- function mergeResult(base, cached, filters, queryOptions) {
16903
- const events = /* @__PURE__ */ new Map();
16904
- for (const entry of base.events) events.set(entry.event.id, entry);
16905
- for (const entry of cached) {
16906
- if (!events.has(entry.event.id)) events.set(entry.event.id, entry);
16628
+ async writeIndex(cache2, index) {
16629
+ await cache2.put(this.indexUrl(), new Response(JSON.stringify(index), {
16630
+ headers: { "content-type": "application/json" }
16631
+ }));
16907
16632
  }
16908
- return {
16909
- events: applyFinalLimits([...events.values()], filters, queryOptions),
16910
- ...base.incomplete === void 0 ? {} : { incomplete: base.incomplete },
16911
- ...base.error === void 0 ? {} : { error: base.error }
16912
- };
16913
- }
16914
- function applyFinalLimits(entries, filters, queryOptions) {
16915
- const aggregateLimit = typeof queryOptions?.limit === "number" && queryOptions.limit >= 0 ? queryOptions.limit : void 0;
16916
- const aggregateCapped = aggregateLimit === void 0 ? entries : entries.slice(0, aggregateLimit);
16917
- if (filters.length === 0) return aggregateCapped;
16918
- const counts = filters.map(() => 0);
16919
- return aggregateCapped.filter((entry) => {
16920
- const matching = filters.flatMap((filter, index) => matchesAnyFilter2(entry.event, [filter]) ? [index] : []);
16921
- const allowed2 = matching.some((index) => {
16922
- const limit = filters[index]?.limit;
16923
- return typeof limit !== "number" || limit < 0 || counts[index] < limit;
16633
+ rewriteRefCounts(index) {
16634
+ const counts = refCounts(index);
16635
+ for (const [hash, blob] of Object.entries(index.blobs)) {
16636
+ blob.refCount = counts[hash] ?? 0;
16637
+ }
16638
+ }
16639
+ async budgetBytes() {
16640
+ const estimate = await this.estimateStorage();
16641
+ if (!estimate?.quota) return this.unknownBudgetBytes;
16642
+ return Math.min(this.softCeilingBytes, Math.floor(estimate.quota * 0.1));
16643
+ }
16644
+ async hardBudgetBytes() {
16645
+ const estimate = await this.estimateStorage();
16646
+ if (!estimate?.quota) return this.unknownBudgetBytes;
16647
+ return Math.min(this.hardCeilingBytes, Math.floor(estimate.quota * 0.2));
16648
+ }
16649
+ async originPressureHigh() {
16650
+ const estimate = await this.estimateStorage();
16651
+ if (!estimate?.quota || estimate.usage === void 0) return false;
16652
+ return estimate.usage / estimate.quota >= 0.8;
16653
+ }
16654
+ async estimateStorage() {
16655
+ if (!this.storage?.estimate) return void 0;
16656
+ try {
16657
+ return this.storage.estimate();
16658
+ } catch (cause) {
16659
+ this.diagnostic({
16660
+ type: "storage-estimate-unavailable",
16661
+ message: "storage estimate failed; using unknown quota cache budget",
16662
+ cause
16663
+ });
16664
+ return void 0;
16665
+ }
16666
+ }
16667
+ diagnostic(diagnostic) {
16668
+ this.onDiagnostic?.(diagnostic);
16669
+ }
16670
+ };
16671
+ async function openNappletArtifactCache(options = {}) {
16672
+ const cacheStorage = options.cacheStorage ?? globalThis.caches;
16673
+ if (!cacheStorage) return void 0;
16674
+ const storage = options.storage ?? globalThis.navigator?.storage;
16675
+ if (options.requireStorageEstimate && !storage?.estimate) {
16676
+ options.onDiagnostic?.({
16677
+ type: "storage-estimate-unavailable",
16678
+ message: "storage estimates are unavailable; using network-only loading"
16924
16679
  });
16925
- if (!allowed2) return false;
16926
- for (const index of matching) counts[index] += 1;
16927
- return true;
16928
- });
16929
- }
16930
-
16931
- // src/browser-relay-policy.ts
16932
- var PAJA_STORAGE_PROBE_KEY = "kehto:paja:storage-probe";
16933
- function normalizeRelayUrl(value) {
16934
- try {
16935
- const url = new URL(value);
16936
- if (url.protocol !== "wss:" && url.protocol !== "ws:" || url.username || url.password) return null;
16937
- url.hash = "";
16938
- return url.href;
16939
- } catch {
16940
- return null;
16680
+ return void 0;
16941
16681
  }
16942
- }
16943
- function isVerifiedNostrEvent(value) {
16944
- if (typeof value !== "object" || value === null) return false;
16945
16682
  try {
16946
- return verifyEvent(value);
16947
- } catch {
16948
- return false;
16683
+ const cache2 = new CacheStorageNappletArtifactCache({ ...options, cacheStorage, storage });
16684
+ await cache2.snapshotIndex();
16685
+ return cache2;
16686
+ } catch (cause) {
16687
+ options.onDiagnostic?.({
16688
+ type: "cache-open-failed",
16689
+ message: "Cache Storage napplet artifact cache could not be opened",
16690
+ cause
16691
+ });
16692
+ return void 0;
16949
16693
  }
16950
16694
  }
16951
- function isPajaRelayAllowed(value, getConfiguredRelays) {
16952
- const normalized = normalizeRelayUrl(value);
16953
- if (!normalized) return false;
16954
- if (getConfiguredRelays().some((url2) => normalizeRelayUrl(url2) === normalized)) return true;
16955
- const url = new URL(normalized);
16956
- if (url.protocol !== "wss:") return false;
16957
- const hostname = url.hostname.replace(/^\[|\]$/gu, "").toLowerCase();
16958
- if (hostname === "localhost" || hostname.endsWith(".localhost") || hostname.endsWith(".local") || hostname.endsWith(".internal") || !hostname.includes(".")) return false;
16959
- if (hostname.includes(":")) {
16960
- return hostname !== "::" && hostname !== "::1" && !/^(?:fc|fd|fe[89ab])/iu.test(hostname);
16695
+ var NAPPLET_KIND_SNAPSHOT = 5129;
16696
+ var NAPPLET_KIND_ROOT = 15129;
16697
+ var NAPPLET_KIND_NAMED = 35129;
16698
+ var NAPPLET_KINDS = [
16699
+ NAPPLET_KIND_SNAPSHOT,
16700
+ NAPPLET_KIND_ROOT,
16701
+ NAPPLET_KIND_NAMED
16702
+ ];
16703
+ function isNappletManifestKind(kind) {
16704
+ return NAPPLET_KINDS.includes(kind);
16705
+ }
16706
+ var NappletResolutionError = class extends Error {
16707
+ code;
16708
+ constructor(code, message) {
16709
+ super(message);
16710
+ this.name = "NappletResolutionError";
16711
+ this.code = code;
16961
16712
  }
16962
- const octets = hostname.split(".").map(Number);
16963
- if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) return true;
16964
- const [first, second] = octets;
16965
- return first !== 0 && first !== 10 && first !== 127 && first < 224 && !(first === 100 && second >= 64 && second <= 127) && !(first === 169 && second === 254) && !(first === 172 && second >= 16 && second <= 31) && !(first === 192 && second === 168) && !(first === 198 && (second === 18 || second === 19));
16713
+ };
16714
+ function firstTagValue(tags, name) {
16715
+ for (const tag of tags) {
16716
+ if (tag[0] === name && typeof tag[1] === "string" && tag[1].length > 0) return tag[1];
16717
+ }
16718
+ return void 0;
16966
16719
  }
16967
- function createPajaRelayConfig(getSimulation) {
16968
- const tierNames = ["discovery", "super", "outbox"];
16969
- const additions = /* @__PURE__ */ new Map();
16970
- const removals = /* @__PURE__ */ new Map();
16971
- const current = { discovery: [], super: [], outbox: [] };
16972
- const allRelays = [];
16973
- function isTier(value) {
16974
- return tierNames.includes(value);
16720
+ function allTagValues(tags, name) {
16721
+ const out = [];
16722
+ for (const tag of tags) {
16723
+ if (tag[0] === name && typeof tag[1] === "string" && tag[1].length > 0) out.push(tag[1]);
16975
16724
  }
16976
- function refresh() {
16977
- for (const tier of tierNames) {
16978
- const seen = /* @__PURE__ */ new Set();
16979
- const values = [];
16980
- const removed = removals.get(tier);
16981
- for (const url of [...getPajaRelayUrls(getSimulation()), ...additions.get(tier)?.values() ?? []]) {
16982
- const normalized = normalizeRelayUrl(url);
16983
- if (!normalized || seen.has(normalized) || removed?.has(normalized)) continue;
16984
- seen.add(normalized);
16985
- values.push(url);
16986
- }
16987
- current[tier].splice(0, current[tier].length, ...values);
16725
+ return out;
16726
+ }
16727
+ function archetypesFromTags(tags) {
16728
+ const out = [];
16729
+ for (const tag of tags) {
16730
+ if (tag[0] !== "archetype") continue;
16731
+ const slug = tag[1];
16732
+ if (typeof slug !== "string" || !/^[a-z0-9][a-z0-9-]*$/.test(slug)) {
16733
+ throw new NappletResolutionError(
16734
+ "invalid-manifest",
16735
+ "archetype slug must contain lowercase letters, numbers, and hyphens"
16736
+ );
16988
16737
  }
16989
- const combined = [...new Set(tierNames.flatMap((tier) => current[tier]))];
16990
- allRelays.splice(0, allRelays.length, ...combined);
16991
- }
16992
- const runtime = {
16993
- allRelays,
16994
- outboxRelays: current.outbox,
16995
- addRelay(tier, url) {
16996
- const normalized = normalizeRelayUrl(url);
16997
- if (!isTier(tier) || !normalized) return;
16998
- const entries = additions.get(tier) ?? /* @__PURE__ */ new Map();
16999
- entries.set(normalized, url);
17000
- additions.set(tier, entries);
17001
- removals.get(tier)?.delete(normalized);
17002
- refresh();
17003
- },
17004
- removeRelay(tier, url) {
17005
- const normalized = normalizeRelayUrl(url);
17006
- if (!isTier(tier) || !normalized) return;
17007
- additions.get(tier)?.delete(normalized);
17008
- const entries = removals.get(tier) ?? /* @__PURE__ */ new Set();
17009
- entries.add(normalized);
17010
- removals.set(tier, entries);
17011
- refresh();
17012
- },
17013
- getRelayConfig() {
17014
- refresh();
17015
- return {
17016
- discovery: [...current.discovery],
17017
- super: [...current.super],
17018
- outbox: [...current.outbox]
17019
- };
17020
- },
17021
- getNip66Suggestions: () => [],
17022
- getRelayUrls(tiers = tierNames) {
17023
- refresh();
17024
- return [...new Set(tiers.flatMap((tier) => current[tier]))];
16738
+ const convention = tag[2];
16739
+ if (typeof convention !== "string" || convention.length === 0) {
16740
+ throw new NappletResolutionError("invalid-manifest", "archetype convention is required");
17025
16741
  }
17026
- };
17027
- refresh();
17028
- return runtime;
16742
+ if (/^NAP-\d+$/.test(convention)) {
16743
+ throw new NappletResolutionError(
16744
+ "invalid-manifest",
16745
+ "numbered NAP identifier is not an archetype convention"
16746
+ );
16747
+ }
16748
+ if (!/^napplet:[^/?#\s]+\/[^/?#\s]+$/.test(convention)) {
16749
+ throw new NappletResolutionError(
16750
+ "invalid-manifest",
16751
+ "archetype convention must be a queryless napplet:<archetype>/<intent> identity"
16752
+ );
16753
+ }
16754
+ if (tag.length !== 3) {
16755
+ throw new NappletResolutionError(
16756
+ "invalid-manifest",
16757
+ "archetype tags must contain exactly slug and convention"
16758
+ );
16759
+ }
16760
+ out.push({ slug, convention });
16761
+ }
16762
+ return out;
17029
16763
  }
17030
- function createPajaRelayHooks(pool, getSimulation, relayConfig) {
17031
- const cleanups = /* @__PURE__ */ new Map();
17032
- const scoped = /* @__PURE__ */ new Map();
17033
- function closeScopedRelay(windowId) {
17034
- scoped.get(windowId)?.unsubscribe();
17035
- scoped.delete(windowId);
16764
+ function parseNappletManifest(event) {
16765
+ if (!isNappletManifestKind(event.kind)) {
16766
+ throw new NappletResolutionError("invalid-manifest", `not a NIP-5D napplet kind: ${event.kind}`);
16767
+ }
16768
+ const paths = pathEntriesFromTags(event.tags);
16769
+ if (paths.length === 0) {
16770
+ throw new NappletResolutionError("invalid-manifest", "manifest has no path tags");
16771
+ }
16772
+ const aggregateHash = aggregateTagValue(event.tags);
16773
+ if (!aggregateHash) {
16774
+ throw new NappletResolutionError("invalid-manifest", "manifest has no aggregate x tag");
16775
+ }
16776
+ const dTag = firstTagValue(event.tags, "d");
16777
+ if (event.kind !== NAPPLET_KIND_NAMED && dTag !== void 0) {
16778
+ throw new NappletResolutionError("invalid-manifest", "only named manifests may carry a d tag");
17036
16779
  }
17037
16780
  return {
17038
- getRelayPool: () => pool,
17039
- trackSubscription(subKey, cleanup) {
17040
- cleanups.set(subKey, cleanup);
17041
- },
17042
- untrackSubscription(subKey) {
17043
- cleanups.get(subKey)?.();
17044
- cleanups.delete(subKey);
17045
- },
17046
- openScopedRelay(windowId, relayUrl2, subId, filters, sourceWindow) {
17047
- closeScopedRelay(windowId);
17048
- const configured = new Map(relayConfig.getRelayUrls().flatMap((url) => {
17049
- const normalized = normalizeRelayUrl(url);
17050
- return normalized ? [[normalized, url]] : [];
17051
- }));
17052
- const requested = normalizeRelayUrl(relayUrl2);
17053
- const allowedUrl = requested && isPajaRelayAllowed(relayUrl2, () => relayConfig.getRelayUrls()) ? configured.get(requested) ?? requested : void 0;
17054
- if (getSimulation().relay.mode !== "live" || !allowedUrl) {
17055
- sourceWindow.postMessage({ type: "relay.closed", subId, reason: "scoped relay unavailable" }, "*");
17056
- return;
17057
- }
17058
- const subscription = pool.subscription([allowedUrl], filters).subscribe((item) => {
17059
- if (item === "EOSE") {
17060
- sourceWindow.postMessage({ type: "relay.eose", subId }, "*");
17061
- return;
17062
- }
17063
- if (!isVerifiedNostrEvent(item)) return;
17064
- sourceWindow.postMessage({
17065
- type: "relay.event",
17066
- subId,
17067
- result: { event: item, sidecar: { relayHints: [allowedUrl] } }
17068
- }, "*");
17069
- });
17070
- scoped.set(windowId, { relayUrl: allowedUrl, unsubscribe: () => subscription.unsubscribe() });
17071
- },
17072
- closeScopedRelay,
17073
- publishToScopedRelay: async (windowId, event) => {
17074
- const active = scoped.get(windowId);
17075
- if (getSimulation().relay.mode !== "live" || !active || !verifyEvent(event)) return false;
17076
- try {
17077
- await pool.publish([active.relayUrl], event);
17078
- return true;
17079
- } catch {
17080
- return false;
17081
- }
17082
- },
17083
- selectRelayTier: () => relayConfig.getRelayUrls(["discovery", "super"])
16781
+ kind: event.kind,
16782
+ pubkey: event.pubkey,
16783
+ dTag: dTag ?? "",
16784
+ paths,
16785
+ aggregateHash,
16786
+ servers: allTagValues(event.tags, "server"),
16787
+ requires: allTagValues(event.tags, "requires"),
16788
+ archetypes: archetypesFromTags(event.tags),
16789
+ title: firstTagValue(event.tags, "title"),
16790
+ description: firstTagValue(event.tags, "description"),
16791
+ source: firstTagValue(event.tags, "source")
17084
16792
  };
17085
16793
  }
17086
- function hasWritableLocalStorage() {
17087
- if (typeof localStorage === "undefined") return false;
17088
- let previous = null;
16794
+ function verifyManifestSignature(event) {
17089
16795
  try {
17090
- previous = localStorage.getItem(PAJA_STORAGE_PROBE_KEY);
17091
- localStorage.setItem(PAJA_STORAGE_PROBE_KEY, "1");
17092
- const available = localStorage.getItem(PAJA_STORAGE_PROBE_KEY) === "1";
17093
- if (previous === null) localStorage.removeItem(PAJA_STORAGE_PROBE_KEY);
17094
- else localStorage.setItem(PAJA_STORAGE_PROBE_KEY, previous);
17095
- return available;
16796
+ return verifyEvent(event);
17096
16797
  } catch {
17097
- try {
17098
- if (previous === null) localStorage.removeItem(PAJA_STORAGE_PROBE_KEY);
17099
- else localStorage.setItem(PAJA_STORAGE_PROBE_KEY, previous);
17100
- } catch {
17101
- }
17102
16798
  return false;
17103
16799
  }
17104
16800
  }
17105
-
17106
- // src/browser-common.ts
17107
- var HEX_64 = /^[0-9a-f]{64}$/i;
17108
- var SHORTCODE = /^:[a-zA-Z0-9_+-]+:$/;
17109
- function relayUrls(values) {
17110
- const urls = /* @__PURE__ */ new Set();
17111
- for (const value of values) {
16801
+ function verifyBlobHash(bytes, sha256Hex) {
16802
+ return bytesToHex2(sha256(bytes)) === sha256Hex;
16803
+ }
16804
+ function stripTrailingSlash(url) {
16805
+ return url.endsWith("/") ? url.slice(0, -1) : url;
16806
+ }
16807
+ async function fetchBlob(servers, sha256Hex, fetchBytes) {
16808
+ for (const server of servers) {
16809
+ const url = `${stripTrailingSlash(server)}/${sha256Hex}`;
17112
16810
  try {
17113
- const url = new URL(value);
17114
- if (url.protocol === "wss:" || url.protocol === "ws:") urls.add(url.href);
16811
+ const bytes = await fetchBytes(url);
16812
+ if (verifyBlobHash(bytes, sha256Hex)) return bytes;
17115
16813
  } catch {
17116
16814
  }
17117
16815
  }
17118
- return [...urls];
16816
+ throw new NappletResolutionError("blob-unavailable", `no server served blob ${sha256Hex}`);
17119
16817
  }
17120
- function profileTarget(target, defaults) {
17121
- if (HEX_64.test(target)) return { pubkey: target.toLowerCase(), relays: relayUrls(defaults) };
17122
- try {
17123
- const decoded = decode(target);
17124
- if (decoded.type === "npub") {
17125
- return { pubkey: decoded.data.toLowerCase(), relays: relayUrls(defaults) };
16818
+ var INDEX_PATHS = ["/index.html", "index.html", "/"];
16819
+ function defaultDecode(bytes) {
16820
+ return new TextDecoder().decode(bytes);
16821
+ }
16822
+ async function resolveNapplet(options) {
16823
+ const { event, fetchBlob: fetchBlobBytes, textDecode = defaultDecode, cache: cache2 } = options;
16824
+ if (!verifyManifestSignature(event)) {
16825
+ throw new NappletResolutionError("invalid-signature", "manifest signature is invalid");
16826
+ }
16827
+ const manifest = parseNappletManifest(event);
16828
+ const recomputed = computeAggregateHash(manifest.paths);
16829
+ if (recomputed !== manifest.aggregateHash) {
16830
+ throw new NappletResolutionError(
16831
+ "aggregate-mismatch",
16832
+ `recomputed aggregate ${recomputed} != manifest ${manifest.aggregateHash}`
16833
+ );
16834
+ }
16835
+ const files = /* @__PURE__ */ new Map();
16836
+ for (const entry of manifest.paths) {
16837
+ let bytes = await cache2?.readBlob(entry.sha256);
16838
+ if (bytes && !verifyBlobHash(bytes, entry.sha256)) {
16839
+ await cache2?.deleteBlob(entry.sha256);
16840
+ bytes = void 0;
17126
16841
  }
17127
- if (decoded.type === "nprofile") {
17128
- return {
17129
- pubkey: decoded.data.pubkey.toLowerCase(),
17130
- relays: relayUrls([
17131
- ...(decoded.data.relays ?? []).filter((relay) => isPajaRelayAllowed(relay, () => defaults)),
17132
- ...defaults
17133
- ])
17134
- };
16842
+ bytes ??= await fetchBlobBytes(entry.sha256, manifest.servers);
16843
+ if (!verifyBlobHash(bytes, entry.sha256)) {
16844
+ throw new NappletResolutionError(
16845
+ "blob-hash-mismatch",
16846
+ `blob for ${entry.path} does not match hash ${entry.sha256}`
16847
+ );
17135
16848
  }
17136
- } catch {
17137
- return null;
16849
+ files.set(entry.path, bytes);
17138
16850
  }
17139
- return null;
16851
+ const indexEntry = manifest.paths.find((e) => INDEX_PATHS.includes(e.path));
16852
+ if (!indexEntry) {
16853
+ throw new NappletResolutionError("missing-index", "manifest has no /index.html entry");
16854
+ }
16855
+ const indexHtml = textDecode(files.get(indexEntry.path));
16856
+ await cache2?.writeVerifiedResolution({ event, manifest, files, indexHtml });
16857
+ return {
16858
+ dTag: manifest.dTag,
16859
+ aggregateHash: manifest.aggregateHash,
16860
+ files,
16861
+ indexHtml,
16862
+ manifest
16863
+ };
17140
16864
  }
17141
- function npub(value) {
16865
+
16866
+ // src/browser-resource.ts
16867
+ var PAJA_RESOURCE_MAX_BYTES = 10 * 1024 * 1024;
16868
+ var PAJA_RESOURCE_MAX_URLS = 100;
16869
+ var PAJA_RESOURCE_MAX_SERVERS = 8;
16870
+ var UTF8_DECODER = new TextDecoder("utf-8", { fatal: true });
16871
+ var BLOSSOM_RESOURCE_PATTERN = /^blossom:sha256:([0-9a-f]{64})$/i;
16872
+ function createPajaResourceFetch(options = {}) {
16873
+ return async (value, init) => {
16874
+ if (init.signal.aborted) throw new DOMException("Resource request cancelled", "AbortError");
16875
+ const url = new URL(value);
16876
+ if (init.method && init.method.toUpperCase() !== "GET") {
16877
+ throw new ResourceServiceError("invalid-request", "NAP-RESOURCE is read-only");
16878
+ }
16879
+ if (url.protocol === "blossom:") {
16880
+ return fetchBlossomResource(
16881
+ value,
16882
+ init.signal,
16883
+ init.servers ?? [],
16884
+ init.windowId,
16885
+ options
16886
+ );
16887
+ }
16888
+ if (url.protocol === "http:" || url.protocol === "https:") {
16889
+ return fetchNetworkResource(value, init.signal, options.fetch ?? globalThis.fetch);
16890
+ }
16891
+ if (url.protocol !== "data:") {
16892
+ throw new ResourceServiceError("unsupported-scheme", `Paja does not enable ${url.protocol}`);
16893
+ }
16894
+ if (value.length > encodedDataUrlLimit(PAJA_RESOURCE_MAX_BYTES)) {
16895
+ throw new ResourceServiceError("too-large", `resource exceeds ${PAJA_RESOURCE_MAX_BYTES} bytes`);
16896
+ }
16897
+ const decoded = await fetch(value, { signal: init.signal });
16898
+ const bytes = new Uint8Array(await decoded.arrayBuffer());
16899
+ if (bytes.byteLength > PAJA_RESOURCE_MAX_BYTES) {
16900
+ throw new ResourceServiceError("too-large", `resource exceeds ${PAJA_RESOURCE_MAX_BYTES} bytes`);
16901
+ }
16902
+ const mime = sniffSafeResourceMime(bytes);
16903
+ if (!mime) {
16904
+ throw new ResourceServiceError("decode-failed", "resource bytes are not an enabled safe media type");
16905
+ }
16906
+ return new Response(arrayBufferFor(bytes), { headers: { "content-type": mime } });
16907
+ };
16908
+ }
16909
+ function pajaResourceInfo() {
16910
+ const schemes = [
16911
+ { scheme: "data", enabled: true },
16912
+ { scheme: "https", enabled: true },
16913
+ { scheme: "http", enabled: true },
16914
+ { scheme: "blossom", enabled: true }
16915
+ ];
16916
+ return {
16917
+ schemes,
16918
+ maxBytes: PAJA_RESOURCE_MAX_BYTES,
16919
+ maxUrls: PAJA_RESOURCE_MAX_URLS,
16920
+ maxServers: PAJA_RESOURCE_MAX_SERVERS
16921
+ };
16922
+ }
16923
+ async function fetchNetworkResource(value, signal, fetcher) {
16924
+ let response;
17142
16925
  try {
17143
- const decoded = decode(value);
17144
- return decoded.type === "npub" ? decoded.data.toLowerCase() : null;
17145
- } catch {
17146
- return null;
16926
+ response = await fetcher(value, {
16927
+ method: "GET",
16928
+ signal,
16929
+ credentials: "omit",
16930
+ referrerPolicy: "no-referrer"
16931
+ });
16932
+ } catch (error) {
16933
+ if (signal.aborted || isAbortError(error)) throw error;
16934
+ throw new ResourceServiceError(
16935
+ "network-error",
16936
+ error instanceof Error ? error.message : String(error)
16937
+ );
16938
+ }
16939
+ if (response.status === 404 || response.status === 410) {
16940
+ throw new ResourceServiceError("not-found", "HTTP resource was not found");
17147
16941
  }
16942
+ if (!response.ok) {
16943
+ throw new ResourceServiceError("network-error", `HTTP resource returned ${response.status}`);
16944
+ }
16945
+ const bytes = await readCappedResponse(response, signal);
16946
+ const mime = sniffSafeResourceMime(bytes);
16947
+ if (!mime) {
16948
+ throw new ResourceServiceError("decode-failed", "resource bytes are not an enabled safe media type");
16949
+ }
16950
+ return new Response(arrayBufferFor(bytes), { headers: { "content-type": mime } });
17148
16951
  }
17149
- function pubkey(value) {
17150
- if (HEX_64.test(value)) return value.toLowerCase();
17151
- return npub(value);
16952
+ async function fetchBlossomResource(value, signal, requestServers, windowId, options) {
16953
+ const match = BLOSSOM_RESOURCE_PATTERN.exec(value);
16954
+ if (!match?.[1]) {
16955
+ throw new ResourceServiceError("invalid-request", "expected blossom:sha256:<64 hex characters>");
16956
+ }
16957
+ const expectedHash = match[1].toLowerCase();
16958
+ const configuredServers = await options.getBlossomServers?.({ url: value, windowId }) ?? [];
16959
+ if (signal.aborted) throw new DOMException("Resource request cancelled", "AbortError");
16960
+ const servers = resolveBlossomServers(requestServers, configuredServers);
16961
+ if (servers.length === 0) {
16962
+ throw new ResourceServiceError("blocked-by-policy", "Paja has no accepted Blossom server");
16963
+ }
16964
+ const fetcher = options.fetch ?? globalThis.fetch;
16965
+ let foundHashMismatch = false;
16966
+ let foundNotFound = false;
16967
+ let foundInconclusive = false;
16968
+ let lastNetworkMessage = "all accepted Blossom servers failed";
16969
+ for (const server of servers) {
16970
+ if (signal.aborted) throw new DOMException("Resource request cancelled", "AbortError");
16971
+ const resourceUrl = `${server}/${expectedHash}`;
16972
+ let response;
16973
+ try {
16974
+ response = await fetcher(resourceUrl, {
16975
+ method: "GET",
16976
+ signal,
16977
+ redirect: "error",
16978
+ cache: "no-store",
16979
+ credentials: "omit",
16980
+ referrerPolicy: "no-referrer"
16981
+ });
16982
+ } catch (error) {
16983
+ if (signal.aborted || isAbortError(error)) throw error;
16984
+ foundInconclusive = true;
16985
+ lastNetworkMessage = error instanceof Error ? error.message : String(error);
16986
+ continue;
16987
+ }
16988
+ if (response.status === 404 || response.status === 410) {
16989
+ foundNotFound = true;
16990
+ continue;
16991
+ }
16992
+ if (!response.ok) {
16993
+ foundInconclusive = true;
16994
+ lastNetworkMessage = `Blossom server returned HTTP ${response.status}`;
16995
+ continue;
16996
+ }
16997
+ const bytes = await readCappedResponse(response, signal);
16998
+ if (!verifyBlobHash(bytes, expectedHash)) {
16999
+ foundHashMismatch = true;
17000
+ continue;
17001
+ }
17002
+ const mime = sniffSafeResourceMime(bytes);
17003
+ if (!mime) {
17004
+ throw new ResourceServiceError("decode-failed", "resource bytes are not an enabled safe media type");
17005
+ }
17006
+ return new Response(arrayBufferFor(bytes), { headers: { "content-type": mime } });
17007
+ }
17008
+ if (foundHashMismatch) {
17009
+ throw new ResourceServiceError("decode-failed", "Blossom response did not match the requested SHA-256");
17010
+ }
17011
+ if (foundInconclusive) {
17012
+ throw new ResourceServiceError("network-error", lastNetworkMessage);
17013
+ }
17014
+ if (foundNotFound) {
17015
+ throw new ResourceServiceError("not-found", "Blossom resource was not found");
17016
+ }
17017
+ throw new ResourceServiceError("network-error", lastNetworkMessage);
17152
17018
  }
17153
- function newestVerified(events, predicate) {
17154
- return events.filter((event) => predicate(event) && verifyEvent(event)).sort((left, right) => right.created_at - left.created_at || left.id.localeCompare(right.id))[0] ?? null;
17019
+ function resolveBlossomServers(requestServers, configuredServers) {
17020
+ const servers = [];
17021
+ for (const value of requestServers) {
17022
+ const server = normalizePublicBlossomServer(value);
17023
+ if (server && !servers.includes(server)) servers.push(server);
17024
+ if (servers.length === PAJA_RESOURCE_MAX_SERVERS) return servers;
17025
+ }
17026
+ for (const server of usableBlossomServers(configuredServers)) {
17027
+ if (!servers.includes(server)) servers.push(server);
17028
+ if (servers.length === PAJA_RESOURCE_MAX_SERVERS) break;
17029
+ }
17030
+ return servers;
17155
17031
  }
17156
- function parseProfile(event) {
17032
+ function normalizePublicBlossomServer(value) {
17033
+ if (typeof value !== "string" || value.trim().length === 0) return null;
17157
17034
  try {
17158
- const parsed = JSON.parse(event.content);
17159
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
17160
- const profile = { ...parsed };
17161
- if (typeof profile.display_name === "string" && typeof profile.displayName !== "string") {
17162
- profile.displayName = profile.display_name;
17163
- }
17164
- return profile;
17035
+ const url = new URL(value.trim());
17036
+ if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash || url.pathname !== "/" || !isPublicHostname(url.hostname)) return null;
17037
+ return url.origin;
17165
17038
  } catch {
17166
17039
  return null;
17167
17040
  }
17168
17041
  }
17169
- function contactPubkeys2(event) {
17170
- const follows = /* @__PURE__ */ new Set();
17171
- for (const tag of event?.tags ?? []) {
17172
- if (tag[0] === "p" && typeof tag[1] === "string" && HEX_64.test(tag[1])) {
17173
- follows.add(tag[1].toLowerCase());
17174
- }
17042
+ function isPublicHostname(value) {
17043
+ const hostname = value.replace(/^\[|\]$/gu, "").toLowerCase();
17044
+ if (hostname === "localhost" || hostname.endsWith(".localhost") || hostname.endsWith(".local") || hostname.endsWith(".internal") || !hostname.includes(".")) return false;
17045
+ if (hostname.includes(":")) {
17046
+ return hostname !== "::" && hostname !== "::1" && !hostname.startsWith("::ffff:") && !/^(?:fc|fd|fe[89ab]|ff)/iu.test(hostname) && !hostname.startsWith("2001:db8:");
17175
17047
  }
17176
- return [...follows];
17177
- }
17178
- function actionError(error) {
17179
- const message = error instanceof Error ? error.message : String(error);
17180
- if (message.includes("denied")) return { ok: false, error: "user-denied" };
17181
- if (message.includes("publish")) return { ok: false, error: "publish-failed" };
17182
- return { ok: false, error: message };
17183
- }
17184
- function isSingleEmoji(value) {
17185
- const graphemes = [...new Intl.Segmenter(void 0, { granularity: "grapheme" }).segment(value)];
17186
- return graphemes.length === 1 && /[\p{Extended_Pictographic}\p{Regional_Indicator}]/u.test(value);
17048
+ const octets = hostname.split(".").map(Number);
17049
+ if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) return true;
17050
+ const [first, second] = octets;
17051
+ return first !== 0 && first !== 10 && first !== 127 && first < 224 && !(first === 100 && second >= 64 && second <= 127) && !(first === 169 && second === 254) && !(first === 172 && second >= 16 && second <= 31) && !(first === 192 && second === 168) && !(first === 198 && (second === 18 || second === 19));
17187
17052
  }
17188
- function reactionTags(target, reaction, customEmojiHref) {
17189
- if (reaction !== "+" && reaction !== "-" && !isSingleEmoji(reaction) && !SHORTCODE.test(reaction)) return null;
17190
- if (customEmojiHref && !SHORTCODE.test(reaction)) return null;
17191
- if (SHORTCODE.test(reaction) && !customEmojiHref) return null;
17192
- const tags = [["e", target.id], ["p", target.pubkey], ["k", String(target.kind)]];
17193
- if (customEmojiHref) {
17194
- let url;
17053
+ function usableBlossomServers(values) {
17054
+ const servers = [];
17055
+ for (const value of values) {
17195
17056
  try {
17196
- url = new URL(customEmojiHref);
17057
+ const [server] = normalizeUploadServers([value]);
17058
+ if (server && !servers.includes(server)) servers.push(server);
17197
17059
  } catch {
17198
- return null;
17199
17060
  }
17200
- if (url.protocol !== "https:" && url.protocol !== "http:") return null;
17201
- tags.push(["emoji", reaction.slice(1, -1), url.href]);
17202
17061
  }
17203
- return tags;
17062
+ return servers;
17204
17063
  }
17205
- function createPajaCommonBackend(options) {
17206
- const query = (filters, relays = options.getRelays()) => options.relay.query(relays, filters, PAJA_LIVE_QUERY_WAIT_MS);
17207
- const identity = async () => {
17208
- const active = options.getSigner();
17209
- if (!active?.getPublicKey) throw new Error("not-signed-in");
17210
- const activePubkey = (await active.getPublicKey()).toLowerCase();
17211
- if (!HEX_64.test(activePubkey)) throw new Error("not-signed-in");
17212
- return { signer: active, pubkey: activePubkey };
17213
- };
17214
- const signer = async () => {
17215
- const active = await identity();
17216
- if (!active.signer.signEvent) throw new Error("not-signed-in");
17217
- return active;
17218
- };
17219
- const currentContacts = async (author) => {
17220
- const events = await query([{ kinds: [3], authors: [author], limit: 16 }]);
17221
- return newestVerified(events, (event) => event.kind === 3 && event.pubkey.toLowerCase() === author);
17222
- };
17223
- const publish = async (active, author, template) => {
17224
- try {
17225
- const event = await active.signEvent(template);
17226
- if (event.pubkey.toLowerCase() !== author || !verifyEvent(event)) return { ok: false, error: "invalid-signature" };
17227
- await options.relay.publish(options.getRelays(), event);
17228
- return { ok: true, eventId: event.id, event };
17229
- } catch (error) {
17230
- return actionError(error);
17231
- }
17232
- };
17233
- const mutateFollows = async (values, add) => {
17234
- const targets = values.map(pubkey);
17235
- if (targets.some((target) => target === null)) return { ok: false, error: "invalid-pubkey" };
17236
- try {
17237
- const active = await signer();
17238
- const current = await currentContacts(active.pubkey);
17239
- const targetSet = new Set(targets);
17240
- const existing = new Set(contactPubkeys2(current));
17241
- const changed = add ? [...targetSet].some((target) => !existing.has(target)) : [...targetSet].some((target) => existing.has(target));
17242
- if (!changed) {
17243
- return current ? { ok: true, eventId: current.id, event: current } : { ok: true };
17244
- }
17245
- const tags = (current?.tags ?? []).filter((tag) => {
17246
- if (tag[0] !== "p" || typeof tag[1] !== "string") return true;
17247
- return add || !targetSet.has(tag[1].toLowerCase());
17248
- });
17249
- if (add) {
17250
- for (const target of targetSet) {
17251
- if (!existing.has(target)) tags.push(["p", target]);
17252
- }
17064
+ async function readCappedResponse(response, signal) {
17065
+ const declaredLength = Number(response.headers.get("content-length"));
17066
+ if (Number.isFinite(declaredLength) && declaredLength > PAJA_RESOURCE_MAX_BYTES) {
17067
+ throw resourceTooLarge();
17068
+ }
17069
+ if (!response.body) {
17070
+ const bytes2 = new Uint8Array(await response.arrayBuffer());
17071
+ if (bytes2.byteLength > PAJA_RESOURCE_MAX_BYTES) throw resourceTooLarge();
17072
+ return bytes2;
17073
+ }
17074
+ const reader = response.body.getReader();
17075
+ const chunks = [];
17076
+ let total = 0;
17077
+ try {
17078
+ while (true) {
17079
+ if (signal.aborted) throw new DOMException("Resource request cancelled", "AbortError");
17080
+ const { done, value } = await reader.read();
17081
+ if (done) break;
17082
+ total += value.byteLength;
17083
+ if (total > PAJA_RESOURCE_MAX_BYTES) {
17084
+ await reader.cancel();
17085
+ throw resourceTooLarge();
17253
17086
  }
17254
- return publish(active.signer, active.pubkey, {
17255
- kind: 3,
17256
- created_at: Math.floor(Date.now() / 1e3),
17257
- tags,
17258
- content: current?.content ?? ""
17259
- });
17260
- } catch (error) {
17261
- return actionError(error);
17087
+ chunks.push(value);
17262
17088
  }
17263
- };
17264
- return {
17265
- async getProfile(target) {
17266
- const resolved = profileTarget(target, options.getRelays());
17267
- if (!resolved) return { ok: false, pubkey: "", error: "invalid-profile-target" };
17268
- try {
17269
- const events = await query([{ kinds: [0], authors: [resolved.pubkey], limit: 16 }], resolved.relays);
17270
- const event = newestVerified(events, (candidate) => candidate.kind === 0 && candidate.pubkey.toLowerCase() === resolved.pubkey);
17271
- if (!event) return { ok: true, pubkey: resolved.pubkey, profile: null };
17272
- return {
17273
- ok: true,
17274
- pubkey: resolved.pubkey,
17275
- profile: parseProfile(event),
17276
- result: { event, sidecar: { relayHints: resolved.relays } }
17277
- };
17278
- } catch {
17279
- return { ok: false, pubkey: resolved.pubkey, error: "relay-timeout" };
17280
- }
17281
- },
17282
- async follows() {
17283
- try {
17284
- const active = await identity();
17285
- return { ok: true, pubkeys: contactPubkeys2(await currentContacts(active.pubkey)) };
17286
- } catch (error) {
17287
- const failure3 = actionError(error);
17288
- return { ok: false, pubkeys: [], error: failure3.error };
17289
- }
17290
- },
17291
- follow: (pubkeys) => mutateFollows(pubkeys, true),
17292
- unfollow: (pubkeys) => mutateFollows(pubkeys, false),
17293
- async react(targetEventId, reaction, customEmojiHref) {
17294
- if (!HEX_64.test(targetEventId)) return { ok: false, error: "invalid-target" };
17295
- try {
17296
- const active = await signer();
17297
- const events = await query([{ ids: [targetEventId], limit: 8 }]);
17298
- const target = newestVerified(events, (event) => event.id === targetEventId.toLowerCase());
17299
- if (!target) return { ok: false, error: "invalid-target" };
17300
- const tags = reactionTags(target, reaction, customEmojiHref);
17301
- if (!tags) return { ok: false, error: "invalid-reaction" };
17302
- return publish(active.signer, active.pubkey, {
17303
- kind: 7,
17304
- created_at: Math.floor(Date.now() / 1e3),
17305
- tags,
17306
- content: reaction
17307
- });
17308
- } catch (error) {
17309
- return actionError(error);
17310
- }
17311
- },
17312
- async report(target, reason, text) {
17313
- try {
17314
- const active = await signer();
17315
- if (target.type === "pubkey") {
17316
- const reportedPubkey = pubkey(target.pubkey);
17317
- if (!reportedPubkey) return { ok: false, error: "invalid-target" };
17318
- return publish(active.signer, active.pubkey, {
17319
- kind: 1984,
17320
- created_at: Math.floor(Date.now() / 1e3),
17321
- tags: [["p", reportedPubkey, target.relay ?? "", reason]],
17322
- content: text
17323
- });
17324
- }
17325
- if (!HEX_64.test(target.id)) return { ok: false, error: "invalid-target" };
17326
- const explicitAuthor = target.pubkey ? pubkey(target.pubkey) : void 0;
17327
- if (target.pubkey && !explicitAuthor) return { ok: false, error: "invalid-target" };
17328
- let author = explicitAuthor ?? null;
17329
- if (!author) {
17330
- const events = await query([{ ids: [target.id], limit: 8 }]);
17331
- author = newestVerified(events, (event) => event.id === target.id.toLowerCase())?.pubkey ?? null;
17089
+ } finally {
17090
+ reader.releaseLock();
17091
+ }
17092
+ const bytes = new Uint8Array(total);
17093
+ let offset = 0;
17094
+ for (const chunk of chunks) {
17095
+ bytes.set(chunk, offset);
17096
+ offset += chunk.byteLength;
17097
+ }
17098
+ return bytes;
17099
+ }
17100
+ function resourceTooLarge() {
17101
+ return new ResourceServiceError("too-large", `resource exceeds ${PAJA_RESOURCE_MAX_BYTES} bytes`);
17102
+ }
17103
+ function isAbortError(error) {
17104
+ return error instanceof Error && (error.name === "AbortError" || error.name === "DOMException");
17105
+ }
17106
+ function arrayBufferFor(bytes) {
17107
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
17108
+ }
17109
+ function encodedDataUrlLimit(maxBytes) {
17110
+ return Math.ceil(maxBytes * 4 / 3) + 1024;
17111
+ }
17112
+ function startsWith(bytes, signature, offset = 0) {
17113
+ return signature.every((value, index) => bytes[offset + index] === value);
17114
+ }
17115
+ function ascii(bytes, start, end) {
17116
+ return String.fromCharCode(...bytes.subarray(start, end));
17117
+ }
17118
+ function sniffSafeResourceMime(bytes) {
17119
+ if (startsWith(bytes, [137, 80, 78, 71, 13, 10, 26, 10])) return "image/png";
17120
+ if (startsWith(bytes, [255, 216, 255])) return "image/jpeg";
17121
+ if (ascii(bytes, 0, 6) === "GIF87a" || ascii(bytes, 0, 6) === "GIF89a") return "image/gif";
17122
+ if (ascii(bytes, 0, 4) === "RIFF" && ascii(bytes, 8, 12) === "WEBP") return "image/webp";
17123
+ if (ascii(bytes, 0, 4) === "RIFF" && ascii(bytes, 8, 12) === "WAVE") return "audio/wav";
17124
+ if (ascii(bytes, 0, 4) === "OggS") return "audio/ogg";
17125
+ if (ascii(bytes, 0, 3) === "ID3" || startsWith(bytes, [255, 251])) return "audio/mpeg";
17126
+ if (startsWith(bytes, [26, 69, 223, 163])) return "video/webm";
17127
+ if (ascii(bytes, 4, 8) === "ftyp") return "video/mp4";
17128
+ if (ascii(bytes, 0, 4) === "wOFF") return "font/woff";
17129
+ if (ascii(bytes, 0, 4) === "wOF2") return "font/woff2";
17130
+ return sniffSafeTextMime(bytes);
17131
+ }
17132
+ function sniffSafeTextMime(bytes) {
17133
+ let text;
17134
+ try {
17135
+ text = UTF8_DECODER.decode(bytes);
17136
+ } catch {
17137
+ return null;
17138
+ }
17139
+ if (/\u0000/u.test(text)) return null;
17140
+ const normalized = text.trimStart().toLowerCase();
17141
+ if (normalized.startsWith("<svg") || normalized.startsWith("<?xml") || normalized.startsWith("<!doctype html") || normalized.startsWith("<html") || normalized.startsWith("<script")) return null;
17142
+ if (normalized.startsWith("{") || normalized.startsWith("[")) {
17143
+ try {
17144
+ JSON.parse(text);
17145
+ return "application/json";
17146
+ } catch {
17147
+ return "text/plain";
17148
+ }
17149
+ }
17150
+ return "text/plain";
17151
+ }
17152
+
17153
+ // src/browser-blossom-events.ts
17154
+ var BLOSSOM_SERVER_LIST_KIND2 = 10063;
17155
+ var HEX_64 = /^[0-9a-f]{64}$/i;
17156
+ var BLOSSOM_REFERENCE = /^blossom:(?:sha256:)?([0-9a-f]{64})(?:\.[0-9a-z]+)?(?:\?([^#]*))?$/i;
17157
+ var DEFAULT_SERVER_LIST_TTL_MS = 5 * 6e4;
17158
+ var MAX_RESOURCES_PER_WINDOW = 256;
17159
+ var MAX_CONTEXTS_PER_RESOURCE = 8;
17160
+ function createPajaBlossomEventResolver(options) {
17161
+ const now2 = options.now ?? Date.now;
17162
+ const ttl = Math.max(0, options.serverListTtlMs ?? DEFAULT_SERVER_LIST_TTL_MS);
17163
+ const windows = /* @__PURE__ */ new Map();
17164
+ const serverLists = /* @__PURE__ */ new Map();
17165
+ const pendingServerLists = /* @__PURE__ */ new Map();
17166
+ function observe(windowId, results) {
17167
+ if (!windowId) return;
17168
+ let resources = windows.get(windowId);
17169
+ if (!resources) {
17170
+ resources = /* @__PURE__ */ new Map();
17171
+ windows.set(windowId, resources);
17172
+ }
17173
+ for (const result2 of results) {
17174
+ const publisher = normalizePubkey(result2.event.pubkey);
17175
+ if (!publisher) continue;
17176
+ for (const location of extractEventResourceLocations(result2.event)) {
17177
+ if (!resources.has(location.url) && resources.size >= MAX_RESOURCES_PER_WINDOW) {
17178
+ const oldest = resources.keys().next().value;
17179
+ if (oldest) resources.delete(oldest);
17332
17180
  }
17333
- if (!author) return { ok: false, error: "author-unresolved" };
17334
- return publish(active.signer, active.pubkey, {
17335
- kind: 1984,
17336
- created_at: Math.floor(Date.now() / 1e3),
17337
- tags: [
17338
- ["e", target.id.toLowerCase(), target.relay ?? "", reason],
17339
- ["p", author.toLowerCase(), "", reason]
17340
- ],
17341
- content: text
17342
- });
17343
- } catch (error) {
17344
- return actionError(error);
17181
+ const contexts = resources.get(location.url) ?? [];
17182
+ const next = {
17183
+ ...location,
17184
+ eventId: result2.event.id,
17185
+ publisher,
17186
+ createdAt: result2.event.created_at
17187
+ };
17188
+ const merged = [next, ...contexts.filter((context) => context.eventId !== next.eventId)].sort(compareResourceContext).slice(0, MAX_CONTEXTS_PER_RESOURCE);
17189
+ resources.set(location.url, merged);
17190
+ }
17191
+ }
17192
+ }
17193
+ function decorate(router, windowId) {
17194
+ const getEvent = router.getEvent ? async (eventId, eventOptions) => {
17195
+ const result2 = await router.getEvent(eventId, eventOptions);
17196
+ if (result2.result) observe(windowId, [result2.result]);
17197
+ return result2;
17198
+ } : void 0;
17199
+ return {
17200
+ ...getEvent ? { getEvent } : {},
17201
+ async query(filters, queryOptions) {
17202
+ const result2 = await router.query(filters, queryOptions);
17203
+ observe(windowId, result2.events);
17204
+ return result2;
17205
+ },
17206
+ subscribe(filters, subscribeOptions, sink) {
17207
+ const observingSink = {
17208
+ event(result2) {
17209
+ observe(windowId, [result2]);
17210
+ sink.event(result2);
17211
+ },
17212
+ closed: (reason) => sink.closed(reason)
17213
+ };
17214
+ return router.subscribe(filters, subscribeOptions, observingSink);
17215
+ },
17216
+ publish: router.publish.bind(router),
17217
+ resolveRelays: router.resolveRelays.bind(router)
17218
+ };
17219
+ }
17220
+ async function getServers(url, windowId) {
17221
+ const canonical = parseBlossomReference(url)?.url;
17222
+ const contexts = canonical && windowId ? windows.get(windowId)?.get(canonical) ?? [] : [];
17223
+ const servers = [];
17224
+ for (const context of contexts) appendUnique(servers, context.servers);
17225
+ if (servers.length < PAJA_RESOURCE_MAX_SERVERS) {
17226
+ const hintedAuthors = [];
17227
+ for (const context of contexts) appendUnique(hintedAuthors, context.authors);
17228
+ const authors = [...hintedAuthors];
17229
+ for (const context of contexts) appendUniqueWithoutLimit(authors, [context.publisher]);
17230
+ const defaultAuthors = [];
17231
+ for (const author of options.getDefaultAuthors?.() ?? []) {
17232
+ const normalized = normalizePubkey(author);
17233
+ if (normalized) appendUnique(defaultAuthors, [normalized]);
17234
+ }
17235
+ appendUniqueWithoutLimit(authors, defaultAuthors);
17236
+ const lists = await Promise.all(
17237
+ authors.map((author) => discoverServerList(author))
17238
+ );
17239
+ for (const list of lists) appendUnique(servers, list);
17240
+ }
17241
+ appendUnique(servers, options.getConfiguredServers());
17242
+ return servers.slice(0, PAJA_RESOURCE_MAX_SERVERS);
17243
+ }
17244
+ async function discoverServerList(pubkey2) {
17245
+ const cached = serverLists.get(pubkey2);
17246
+ if (cached && cached.expiresAt > now2()) return [...cached.servers];
17247
+ const pending = pendingServerLists.get(pubkey2);
17248
+ if (pending) return [...await pending];
17249
+ const lookup = loadServerList(pubkey2);
17250
+ pendingServerLists.set(pubkey2, lookup);
17251
+ try {
17252
+ return [...await lookup];
17253
+ } finally {
17254
+ if (pendingServerLists.get(pubkey2) === lookup) pendingServerLists.delete(pubkey2);
17255
+ }
17256
+ }
17257
+ async function loadServerList(pubkey2) {
17258
+ let result2;
17259
+ try {
17260
+ result2 = await options.baseRouter.query(
17261
+ [{ kinds: [BLOSSOM_SERVER_LIST_KIND2], authors: [pubkey2], limit: 1 }],
17262
+ { authors: [pubkey2], limit: 1 }
17263
+ );
17264
+ } catch {
17265
+ return [];
17266
+ }
17267
+ const newest = result2.events.map((entry) => entry.event).filter((event) => event.kind === BLOSSOM_SERVER_LIST_KIND2 && normalizePubkey(event.pubkey) === pubkey2).sort(compareNewestEvent)[0];
17268
+ if (!newest) {
17269
+ if (!result2.error && !result2.incomplete) {
17270
+ serverLists.set(pubkey2, { expiresAt: now2() + ttl, servers: [] });
17345
17271
  }
17272
+ return [];
17346
17273
  }
17274
+ const servers = newest.tags.flatMap((tag) => {
17275
+ if (tag[0] !== "server" || typeof tag[1] !== "string") return [];
17276
+ const server = normalizePublicBlossomServer(tag[1]);
17277
+ return server ? [server] : [];
17278
+ });
17279
+ const deduplicated = [];
17280
+ appendUnique(deduplicated, servers);
17281
+ serverLists.set(pubkey2, { expiresAt: now2() + ttl, servers: deduplicated });
17282
+ return deduplicated;
17283
+ }
17284
+ return {
17285
+ observe,
17286
+ decorate,
17287
+ getServers,
17288
+ clearWindow: (windowId) => windows.delete(windowId)
17347
17289
  };
17348
17290
  }
17349
-
17350
- // src/browser-lists.ts
17351
- var HEX_642 = /^[0-9a-f]{64}$/i;
17352
- var ADDRESS = /^\d+:[0-9a-f]{64}:.+$/i;
17353
- var SUPPORTED_LISTS = [
17354
- {
17355
- kind: 1e4,
17356
- type: "mute-list",
17357
- addressable: false,
17358
- supportedItemTypes: ["pubkey", "event", "hashtag", "word"],
17359
- privateItems: false,
17360
- tagByItemType: { pubkey: "p", event: "e", hashtag: "t", word: "word" }
17361
- },
17362
- {
17363
- kind: 10002,
17364
- type: "relay-list-metadata",
17365
- addressable: false,
17366
- supportedItemTypes: ["relay"],
17367
- privateItems: false,
17368
- tagByItemType: { relay: "r" }
17369
- },
17370
- {
17371
- kind: 10003,
17372
- type: "bookmarks",
17373
- addressable: false,
17374
- supportedItemTypes: ["event", "address"],
17375
- privateItems: false,
17376
- tagByItemType: { event: "e", address: "a" }
17377
- },
17378
- {
17379
- kind: 3e4,
17380
- type: "follow-sets",
17381
- addressable: true,
17382
- supportedItemTypes: ["pubkey"],
17383
- privateItems: false,
17384
- tagByItemType: { pubkey: "p" }
17291
+ function extractEventResourceLocations(event) {
17292
+ const locations = /* @__PURE__ */ new Map();
17293
+ const globalServers = event.tags.flatMap((tag) => {
17294
+ if (tag[0] !== "server" || typeof tag[1] !== "string") return [];
17295
+ const server = normalizeEventServer(tag[1]);
17296
+ return server ? [server] : [];
17297
+ });
17298
+ const add = (value, servers = [], authors = []) => {
17299
+ if (!value) return;
17300
+ const parsed = parseBlossomReference(value);
17301
+ if (!parsed) return;
17302
+ const existing = locations.get(parsed.url) ?? {
17303
+ url: parsed.url,
17304
+ servers: [],
17305
+ authors: []
17306
+ };
17307
+ appendUnique(existing.servers, [
17308
+ ...parsed.servers,
17309
+ ...servers.flatMap((server) => {
17310
+ const normalized = normalizeEventServer(server);
17311
+ return normalized ? [normalized] : [];
17312
+ }),
17313
+ ...globalServers
17314
+ ]);
17315
+ appendUnique(existing.authors, [
17316
+ ...parsed.authors,
17317
+ ...authors.flatMap((author) => {
17318
+ const normalized = normalizePubkey(author);
17319
+ return normalized ? [normalized] : [];
17320
+ })
17321
+ ]);
17322
+ locations.set(parsed.url, existing);
17323
+ };
17324
+ for (const tag of event.tags) {
17325
+ if ((tag[0] === "resource" || tag[0] === "r") && typeof tag[1] === "string") {
17326
+ add(tag[1]);
17327
+ } else if (tag[0] === "blossom" && typeof tag[1] === "string") {
17328
+ add(HEX_64.test(tag[1]) ? `blossom:sha256:${tag[1]}` : tag[1]);
17329
+ }
17330
+ }
17331
+ const content = parseEventContent(event.content);
17332
+ if (content) {
17333
+ const contentServers = stringList2(content.servers);
17334
+ for (const key of ["sources", "resources"]) {
17335
+ const entries = content[key];
17336
+ if (!Array.isArray(entries)) continue;
17337
+ for (const entry of entries) {
17338
+ if (typeof entry === "string") {
17339
+ add(entry, contentServers);
17340
+ continue;
17341
+ }
17342
+ if (!isRecord5(entry)) continue;
17343
+ const value = stringValue(entry.uri) ?? stringValue(entry.url) ?? stringValue(entry.resource) ?? (isBlossomRecord(entry) && isHash(entry.sha256) ? `blossom:sha256:${String(entry.sha256)}` : void 0);
17344
+ add(value, [...contentServers, ...stringList2(entry.servers)], stringList2(entry.authors));
17345
+ }
17346
+ }
17385
17347
  }
17386
- ];
17387
- function publicSupport() {
17388
- return SUPPORTED_LISTS.map(({ tagByItemType: _tagByItemType, ...support }) => ({
17389
- ...support,
17390
- supportedItemTypes: support.supportedItemTypes ? [...support.supportedItemTypes] : void 0
17391
- }));
17348
+ return [...locations.values()];
17392
17349
  }
17393
- function failure2(error, reason) {
17394
- return { ok: false, error, reason, supported: publicSupport() };
17350
+ function parseBlossomReference(value) {
17351
+ const match = BLOSSOM_REFERENCE.exec(value.trim());
17352
+ if (!match?.[1]) return null;
17353
+ const params = new URLSearchParams(match[2] ?? "");
17354
+ const servers = params.getAll("xs").flatMap((server) => {
17355
+ const normalized = normalizeEventServer(server);
17356
+ return normalized ? [normalized] : [];
17357
+ });
17358
+ const authors = params.getAll("as").flatMap((author) => {
17359
+ const normalized = normalizePubkey(author);
17360
+ return normalized ? [normalized] : [];
17361
+ });
17362
+ return {
17363
+ url: `blossom:sha256:${match[1].toLowerCase()}`,
17364
+ servers,
17365
+ authors
17366
+ };
17395
17367
  }
17396
- function resolveList(ref) {
17397
- const input = ref;
17398
- const hasKind = typeof input.kind === "number";
17399
- const hasType = typeof input.type === "string" && input.type.length > 0;
17400
- if (hasKind === hasType) return failure2("invalid-list-ref", "exactly one list kind or type is required");
17401
- const candidates = hasKind ? SUPPORTED_LISTS.filter((support2) => support2.kind === input.kind) : SUPPORTED_LISTS.filter((support2) => support2.type === input.type);
17402
- if (candidates.length === 0) return failure2("unsupported-list", "list kind or type is not supported");
17403
- if (candidates.length > 1) return failure2("ambiguous-list", "list type maps to multiple supported kinds");
17404
- const support = candidates[0];
17405
- const identifier = typeof input.identifier === "string" && input.identifier.length > 0 ? input.identifier : void 0;
17406
- if (support.addressable && !identifier) return failure2("missing-identifier", "addressable lists require an identifier");
17407
- if (!support.addressable && identifier) return failure2("invalid-list-ref", "replaceable list does not accept an identifier");
17408
- return { support, ...identifier ? { identifier } : {} };
17368
+ function normalizeEventServer(value) {
17369
+ const normalized = normalizePublicBlossomServer(value);
17370
+ if (normalized) return normalized;
17371
+ const trimmed = value.trim();
17372
+ if (!/^[a-z0-9.-]+(?::\d+)?$/i.test(trimmed)) return null;
17373
+ return normalizePublicBlossomServer(`https://${trimmed}`);
17409
17374
  }
17410
- function relayUrl(value) {
17375
+ function parseEventContent(value) {
17376
+ if (!value.startsWith("{") || value.length > 256 * 1024) return null;
17411
17377
  try {
17412
- const parsed = new URL(value);
17413
- return parsed.protocol === "ws:" || parsed.protocol === "wss:" ? parsed.href : null;
17378
+ const parsed = JSON.parse(value);
17379
+ return isRecord5(parsed) ? parsed : null;
17414
17380
  } catch {
17415
17381
  return null;
17416
17382
  }
17417
17383
  }
17418
- function itemTag(support, item) {
17419
- if (item.visibility === "private") return failure2("private-items-unsupported", "private list items require NIP-44 support");
17420
- const tagName = support.tagByItemType[item.itemType];
17421
- if (!tagName) return failure2("unsupported-item", `${item.itemType} is not supported by ${support.type}`);
17422
- const value = item.value.trim();
17423
- if (!value) return failure2("invalid-item", "list item value is empty");
17424
- if ((item.itemType === "pubkey" || item.itemType === "event") && !HEX_642.test(value)) {
17425
- return failure2("invalid-item", `${item.itemType} values must be 32-byte hex`);
17384
+ function compareResourceContext(left, right) {
17385
+ if (left.createdAt !== right.createdAt) return right.createdAt - left.createdAt;
17386
+ return left.eventId.localeCompare(right.eventId);
17387
+ }
17388
+ function compareNewestEvent(left, right) {
17389
+ if (left.created_at !== right.created_at) return right.created_at - left.created_at;
17390
+ return left.id.localeCompare(right.id);
17391
+ }
17392
+ function normalizePubkey(value) {
17393
+ return typeof value === "string" && HEX_64.test(value) ? value.toLowerCase() : null;
17394
+ }
17395
+ function appendUnique(target, values) {
17396
+ for (const value of values) {
17397
+ if (!target.includes(value)) target.push(value);
17398
+ if (target.length >= PAJA_RESOURCE_MAX_SERVERS) return;
17426
17399
  }
17427
- if (item.itemType === "address" && !ADDRESS.test(value)) {
17428
- return failure2("invalid-item", "address values must use kind:pubkey:identifier");
17400
+ }
17401
+ function appendUniqueWithoutLimit(target, values) {
17402
+ for (const value of values) {
17403
+ if (!target.includes(value)) target.push(value);
17429
17404
  }
17430
- if (support.kind === 10002) {
17431
- const url = relayUrl(value);
17432
- if (!url) return failure2("invalid-item", "relay list items require ws or wss URLs");
17433
- const marker = item.marker ?? "read-write";
17434
- if (marker !== "read" && marker !== "write" && marker !== "read-write") {
17435
- return failure2("invalid-item", "relay marker must be read, write, or read-write");
17405
+ }
17406
+ function stringList2(value) {
17407
+ return Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : [];
17408
+ }
17409
+ function stringValue(value) {
17410
+ return typeof value === "string" && value.length > 0 ? value : void 0;
17411
+ }
17412
+ function isHash(value) {
17413
+ return typeof value === "string" && HEX_64.test(value);
17414
+ }
17415
+ function isBlossomRecord(value) {
17416
+ return value.type === "blossom" || value.kind === "blossom";
17417
+ }
17418
+ function isRecord5(value) {
17419
+ return typeof value === "object" && value !== null;
17420
+ }
17421
+
17422
+ // ../nip/dist/chunk-PSENX3MS.js
17423
+ function parseNip65RelayList(event) {
17424
+ return event.tags.flatMap((tag) => {
17425
+ if (tag[0] !== "r" || typeof tag[1] !== "string" || tag[1].length === 0) return [];
17426
+ const marker = tag[2];
17427
+ const read = marker !== "write";
17428
+ const write = marker !== "read";
17429
+ return [{ url: tag[1], read, write }];
17430
+ });
17431
+ }
17432
+ function selectWriteRelays(entries) {
17433
+ return dedupe(entries.filter((e) => e.write).map((e) => e.url));
17434
+ }
17435
+ function selectReadRelays(entries) {
17436
+ return dedupe(entries.filter((e) => e.read).map((e) => e.url));
17437
+ }
17438
+ function createNip65Registry() {
17439
+ const lists = /* @__PURE__ */ new Map();
17440
+ function setRelayList(pubkey2, entries) {
17441
+ lists.set(pubkey2, entries.map((e) => ({ ...e })));
17442
+ }
17443
+ function ingest(event) {
17444
+ const entries = parseNip65RelayList(event);
17445
+ setRelayList(event.pubkey, entries);
17446
+ return entries;
17447
+ }
17448
+ function getRelayList(pubkey2) {
17449
+ const entries = lists.get(pubkey2);
17450
+ return entries ? entries.map((e) => ({ ...e })) : void 0;
17451
+ }
17452
+ function resolve(pubkeys, want) {
17453
+ const urls = [];
17454
+ const seen = /* @__PURE__ */ new Set();
17455
+ for (const pubkey2 of pubkeys) {
17456
+ const entries = lists.get(pubkey2);
17457
+ if (!entries) continue;
17458
+ for (const entry of entries) {
17459
+ if (entry[want] && !seen.has(entry.url)) {
17460
+ seen.add(entry.url);
17461
+ urls.push(entry.url);
17462
+ }
17463
+ }
17436
17464
  }
17437
- return marker === "read-write" ? ["r", url] : ["r", url, marker];
17465
+ return urls;
17466
+ }
17467
+ return {
17468
+ ingest,
17469
+ setRelayList,
17470
+ getRelayList,
17471
+ has: (pubkey2) => lists.has(pubkey2),
17472
+ resolveOutboxRelays: (pubkeys) => resolve(pubkeys, "write"),
17473
+ resolveReadRelays: (pubkeys) => resolve(pubkeys, "read"),
17474
+ delete: (pubkey2) => lists.delete(pubkey2),
17475
+ clear: () => lists.clear()
17476
+ };
17477
+ }
17478
+ function dedupe(urls) {
17479
+ const seen = /* @__PURE__ */ new Set();
17480
+ const out = [];
17481
+ for (const url of urls) {
17482
+ if (!seen.has(url)) {
17483
+ seen.add(url);
17484
+ out.push(url);
17485
+ }
17486
+ }
17487
+ return out;
17488
+ }
17489
+
17490
+ // src/browser-relay-runtime.ts
17491
+ var PAJA_NIP65_RELAY_LIST_KIND = 10002;
17492
+ var PAJA_CONTACT_LIST_KIND = 3;
17493
+ var PAJA_WEBRTC_SIGNAL_KIND = 25050;
17494
+ var NIP17_GIFT_WRAP_KIND2 = 1059;
17495
+ var PAJA_CONTACT_LIST_CANDIDATE_LIMIT = 64;
17496
+ var PAJA_LIVE_QUERY_WAIT_MS = 4e3;
17497
+ var contactListCandidateQueries = /* @__PURE__ */ new WeakMap();
17498
+ function matchesFilter2(event, filter) {
17499
+ const ids = filter.ids;
17500
+ if (ids && !ids.some((id) => event.id === id || event.id.startsWith(id))) return false;
17501
+ const authors = filter.authors;
17502
+ if (authors && !authors.some((author) => event.pubkey === author || event.pubkey.startsWith(author))) return false;
17503
+ const kinds = filter.kinds;
17504
+ if (kinds && !kinds.includes(event.kind)) return false;
17505
+ if (typeof filter.since === "number" && event.created_at < filter.since) return false;
17506
+ if (typeof filter.until === "number" && event.created_at > filter.until) return false;
17507
+ for (const [key, value] of Object.entries(filter)) {
17508
+ if (!key.startsWith("#") || !Array.isArray(value)) continue;
17509
+ const tagName = key.slice(1);
17510
+ const allowed2 = value.filter((item) => typeof item === "string");
17511
+ if (allowed2.length === 0) continue;
17512
+ if (!event.tags.some((tag) => tag[0] === tagName && typeof tag[1] === "string" && allowed2.includes(tag[1]))) return false;
17438
17513
  }
17439
- const tag = [tagName, value];
17440
- if (item.relay) tag.push(item.relay);
17441
- if (item.label) tag.push(item.label);
17442
- return tag;
17443
- }
17444
- function isFailure(value) {
17445
- return !Array.isArray(value);
17446
- }
17447
- function sameItem(tag, expected) {
17448
- if (tag[0] !== expected[0] || tag[1] !== expected[1]) return false;
17449
- if (expected.length > 2 && tag[2] !== expected[2]) return false;
17450
- if (expected.length > 3 && tag[3] !== expected[3]) return false;
17451
17514
  return true;
17452
17515
  }
17453
- function relayCoverage(tag) {
17454
- if (tag[2] === "read") return /* @__PURE__ */ new Set(["read"]);
17455
- if (tag[2] === "write") return /* @__PURE__ */ new Set(["write"]);
17456
- return /* @__PURE__ */ new Set(["read", "write"]);
17457
- }
17458
- function relayTag(url, coverage) {
17459
- if (coverage.size === 0) return null;
17460
- if (coverage.size === 2) return ["r", url];
17461
- return ["r", url, coverage.has("read") ? "read" : "write"];
17462
- }
17463
- function sameRelay(tag, url) {
17464
- return tag[0] === "r" && typeof tag[1] === "string" && relayUrl(tag[1]) === url;
17516
+ function matchesAnyFilter2(event, filters) {
17517
+ return filters.length === 0 || filters.some((filter) => matchesFilter2(event, filter));
17465
17518
  }
17466
- function addRelayItem(tags, expected) {
17467
- const url = expected[1];
17468
- const matching = tags.filter((tag) => sameRelay(tag, url));
17469
- const coverage = /* @__PURE__ */ new Set();
17470
- for (const tag of matching) for (const direction of relayCoverage(tag)) coverage.add(direction);
17471
- const requested = relayCoverage(expected);
17472
- const before = coverage.size;
17473
- for (const direction of requested) coverage.add(direction);
17474
- if (coverage.size === before) return { tags, changed: false };
17475
- const retained = tags.filter((tag) => !sameRelay(tag, url));
17476
- retained.push(relayTag(url, coverage));
17477
- return { tags: retained, changed: true };
17519
+ function normalizedFilters(filters) {
17520
+ return Array.isArray(filters) ? filters : [filters];
17478
17521
  }
17479
- function removeRelayItem(tags, expected) {
17480
- const url = expected[1];
17481
- const matching = tags.filter((tag) => sameRelay(tag, url));
17482
- if (matching.length === 0) return { tags, changed: false };
17483
- const retained = tags.filter((tag) => !sameRelay(tag, url));
17484
- if (expected.length === 2) return { tags: retained, changed: true };
17485
- const coverage = /* @__PURE__ */ new Set();
17486
- for (const tag of matching) for (const direction of relayCoverage(tag)) coverage.add(direction);
17487
- coverage.delete(expected[2]);
17488
- const rewritten = relayTag(url, coverage);
17489
- if (rewritten) retained.push(rewritten);
17490
- return { tags: retained, changed: true };
17522
+ function applyFilterLimit(events, filter) {
17523
+ const limit = typeof filter.limit === "number" && filter.limit >= 0 ? filter.limit : void 0;
17524
+ if (limit === void 0) return events;
17525
+ return [...events].sort((a, b) => b.created_at - a.created_at).slice(0, limit);
17491
17526
  }
17492
- function metadataTags(resolved, options) {
17493
- const tags = [];
17494
- if (resolved.identifier) tags.push(["d", resolved.identifier]);
17495
- if (options?.title) tags.push(["title", options.title]);
17496
- if (options?.description) tags.push(["description", options.description]);
17497
- if (options?.image) tags.push(["image", options.image]);
17498
- return tags;
17527
+ function collectMemoryEvents(events, filters) {
17528
+ const out = /* @__PURE__ */ new Map();
17529
+ const activeFilters = filters.length > 0 ? filters : [{}];
17530
+ for (const filter of activeFilters) {
17531
+ for (const event of applyFilterLimit(events.filter((candidate) => matchesFilter2(candidate, filter)), filter)) {
17532
+ out.set(event.id, event);
17533
+ }
17534
+ }
17535
+ return [...out.values()].sort((a, b) => b.created_at - a.created_at);
17499
17536
  }
17500
- function listFilter(resolved, author) {
17537
+ function subscribeLive(pool, relayUrls2, filters, next) {
17538
+ const activeFilters = filters.length > 0 ? filters : [{}];
17539
+ const requests = relayUrls2.flatMap((url) => activeFilters.map((filter) => ({ url, filter })));
17540
+ if (requests.length === 0) {
17541
+ queueMicrotask(() => next("EOSE"));
17542
+ return { unsubscribe() {
17543
+ } };
17544
+ }
17545
+ const sub = pool.subscribeMap(requests, {
17546
+ label: "kehto-paja-runtime",
17547
+ maxWait: PAJA_LIVE_QUERY_WAIT_MS,
17548
+ onevent: (event) => next(event),
17549
+ oneose: () => next("EOSE")
17550
+ });
17501
17551
  return {
17502
- kinds: [resolved.support.kind],
17503
- authors: [author],
17504
- limit: 16,
17505
- ...resolved.identifier ? { ["#d"]: [resolved.identifier] } : {}
17552
+ unsubscribe() {
17553
+ void sub.close("paja unsubscribe");
17554
+ }
17506
17555
  };
17507
17556
  }
17508
- function newestList(events, resolved, author) {
17509
- return events.filter((event) => event.kind === resolved.support.kind && event.pubkey.toLowerCase() === author && (!resolved.identifier || event.tags.some((tag) => tag[0] === "d" && tag[1] === resolved.identifier)) && verifyEvent(event)).sort((left, right) => right.created_at - left.created_at || left.id.localeCompare(right.id))[0] ?? null;
17557
+ function queryLiveBounded(pool, relayUrls2, filter, maxWaitMs, limit, signal) {
17558
+ if (limit === 0 || signal?.aborted) return Promise.resolve([]);
17559
+ return new Promise((resolve) => {
17560
+ const events = [];
17561
+ let settled = false;
17562
+ let closeRequested = false;
17563
+ let closeReason = "paja query limit reached";
17564
+ let subscription;
17565
+ let abort;
17566
+ const finish = () => {
17567
+ if (settled) return;
17568
+ settled = true;
17569
+ if (abort) signal?.removeEventListener("abort", abort);
17570
+ resolve(events);
17571
+ };
17572
+ const close = (reason = closeReason) => {
17573
+ closeRequested = true;
17574
+ closeReason = reason;
17575
+ if (!subscription) return;
17576
+ void Promise.resolve(subscription.close(reason)).catch(() => {
17577
+ });
17578
+ finish();
17579
+ };
17580
+ abort = () => close("paja query aborted");
17581
+ signal?.addEventListener("abort", abort, { once: true });
17582
+ subscription = pool.subscribeEose(relayUrls2, filter, {
17583
+ label: "kehto-paja-runtime",
17584
+ maxWait: maxWaitMs,
17585
+ onevent(event) {
17586
+ if (events.length >= limit) return;
17587
+ events.push(event);
17588
+ if (events.length === limit) close();
17589
+ },
17590
+ onclose: finish
17591
+ });
17592
+ if (closeRequested) close();
17593
+ });
17510
17594
  }
17511
- function createPajaListsBackend(options) {
17512
- const activeSigner = async () => {
17513
- const signer = options.getSigner();
17514
- if (!signer?.getPublicKey || !signer.signEvent) throw new Error("not-signed-in");
17515
- const pubkey2 = (await signer.getPublicKey()).toLowerCase();
17516
- if (!HEX_642.test(pubkey2)) throw new Error("not-signed-in");
17517
- return { signer, pubkey: pubkey2 };
17518
- };
17519
- const mutation = async (operation, ref, items, mutationOptions) => {
17520
- const resolved = resolveList(ref);
17521
- if ("ok" in resolved) return resolved;
17522
- if (items.length === 0) return { ok: true, [operation === "add" ? "added" : "removed"]: 0, skipped: 0 };
17523
- const itemTags = [];
17524
- for (const item of items) {
17525
- const tag = itemTag(resolved.support, item);
17526
- if (isFailure(tag)) return tag;
17527
- itemTags.push(tag);
17528
- }
17529
- let active;
17530
- try {
17531
- active = await activeSigner();
17532
- } catch {
17533
- return failure2("not-signed-in", "list mutations require an active signer");
17534
- }
17535
- let current;
17536
- try {
17537
- const events = await options.relay.query(
17538
- options.getRelays(),
17539
- [listFilter(resolved, active.pubkey)],
17540
- PAJA_LIVE_QUERY_WAIT_MS
17541
- );
17542
- current = newestList(events, resolved, active.pubkey);
17543
- } catch {
17544
- return failure2("list-unavailable", "current list could not be loaded");
17545
- }
17546
- if (!current && !(operation === "add" && mutationOptions?.create)) {
17547
- return failure2("list-not-found", "list does not exist and creation was not requested");
17548
- }
17549
- if (operation === "remove" && current?.content && items.some((item) => item.visibility !== "public")) {
17550
- return failure2("private-items-unsupported", "cannot safely remove private items without NIP-44 support");
17551
- }
17552
- let tags = current ? current.tags.map((tag) => [...tag]) : metadataTags(resolved, mutationOptions);
17553
- let changed = 0;
17554
- for (const expected of itemTags) {
17555
- if (resolved.support.kind === 10002) {
17556
- const result2 = operation === "add" ? addRelayItem(tags, expected) : removeRelayItem(tags, expected);
17557
- tags = result2.tags;
17558
- if (result2.changed) changed += 1;
17559
- continue;
17560
- }
17561
- if (operation === "add") {
17562
- if (!tags.some((tag) => sameItem(tag, expected))) {
17563
- tags.push(expected);
17564
- changed += 1;
17565
- }
17566
- } else {
17567
- const before = tags.length;
17568
- tags = tags.filter((tag) => !sameItem(tag, expected));
17569
- if (tags.length < before) changed += 1;
17570
- }
17571
- }
17572
- const skipped = items.length - changed;
17573
- if (changed === 0) {
17574
- return {
17575
- ok: true,
17576
- ...current ? { eventId: current.id, event: { ...current } } : {},
17577
- [operation === "add" ? "added" : "removed"]: 0,
17578
- skipped
17579
- };
17580
- }
17595
+ async function queryLive(pool, relayUrls2, filters, maxWaitMs = PAJA_LIVE_QUERY_WAIT_MS, collectUntilLimit = false, signal) {
17596
+ const activeFilters = filters.length > 0 ? filters : [{}];
17597
+ const batches = await Promise.all(activeFilters.map((filter) => {
17598
+ const limit = typeof filter.limit === "number" && filter.limit >= 0 ? filter.limit : void 0;
17599
+ if (collectUntilLimit && limit !== void 0) return queryLiveBounded(pool, relayUrls2, filter, maxWaitMs, limit, signal);
17600
+ return pool.querySync(relayUrls2, filter, {
17601
+ label: "kehto-paja-runtime",
17602
+ maxWait: maxWaitMs
17603
+ });
17604
+ }));
17605
+ const out = /* @__PURE__ */ new Map();
17606
+ for (const event of batches.flat()) out.set(event.id, event);
17607
+ return [...out.values()].sort((a, b) => b.created_at - a.created_at);
17608
+ }
17609
+ async function publishLive(pool, relayUrls2, event) {
17610
+ const results = await Promise.allSettled(pool.publish(relayUrls2, event));
17611
+ return Object.fromEntries(relayUrls2.map((relayUrl2, index) => [relayUrl2, results[index]?.status === "fulfilled"]));
17612
+ }
17613
+ async function countLive(pool, relayUrls2, filters) {
17614
+ let failure3 = new Error("count unavailable");
17615
+ for (const relayUrl2 of relayUrls2) {
17616
+ const controller = new AbortController();
17617
+ let timeout;
17618
+ const timedOut = new Promise((_resolve, reject2) => {
17619
+ timeout = setTimeout(() => {
17620
+ controller.abort();
17621
+ reject2(new Error("count timeout"));
17622
+ }, PAJA_LIVE_QUERY_WAIT_MS);
17623
+ });
17581
17624
  try {
17582
- const template = {
17583
- kind: resolved.support.kind,
17584
- created_at: Math.floor(Date.now() / 1e3),
17585
- tags,
17586
- content: current?.content ?? ""
17587
- };
17588
- const event = await active.signer.signEvent(template);
17589
- if (event.pubkey.toLowerCase() !== active.pubkey || !verifyEvent(event)) {
17590
- return failure2("publish-failed", "signer returned an invalid list event");
17591
- }
17592
- await options.relay.publish(options.getRelays(), event);
17593
- return {
17594
- ok: true,
17595
- eventId: event.id,
17596
- event: { ...event },
17597
- [operation === "add" ? "added" : "removed"]: changed,
17598
- skipped
17599
- };
17625
+ const relay = await Promise.race([
17626
+ pool.ensureRelay(relayUrl2, {
17627
+ connectionTimeout: PAJA_LIVE_QUERY_WAIT_MS,
17628
+ abort: controller.signal
17629
+ }),
17630
+ timedOut
17631
+ ]);
17632
+ const count = await Promise.race([
17633
+ relay.count(filters, { id: null }),
17634
+ timedOut
17635
+ ]);
17636
+ if (!Number.isSafeInteger(count) || count < 0) throw new Error("invalid count");
17637
+ return { count, relay: relayUrl2 };
17600
17638
  } catch (error) {
17601
- const message = error instanceof Error ? error.message : String(error);
17602
- return failure2(message.includes("denied") ? "user-denied" : "publish-failed", message);
17639
+ failure3 = error;
17640
+ } finally {
17641
+ if (timeout !== void 0) clearTimeout(timeout);
17603
17642
  }
17643
+ }
17644
+ throw failure3;
17645
+ }
17646
+ function createPajaRelayBackend(getSimulation, confirmRequest, livePool = new SimplePool()) {
17647
+ livePool.trackRelays = true;
17648
+ const fixtureEvents = getSimulation().relay.fixtures.flatMap(toNostrEvent);
17649
+ const acceptedMemoryEvents = [];
17650
+ const subscribers = /* @__PURE__ */ new Set();
17651
+ const isAvailable = () => getSimulation().relay.mode !== "disabled" && getPajaRelayUrls(getSimulation()).length > 0;
17652
+ const cachedEvents = () => getSimulation().relay.mode === "memory" ? [...fixtureEvents, ...acceptedMemoryEvents] : [];
17653
+ const query = async (relayUrls2, filters, maxWaitMs) => {
17654
+ const cached = collectMemoryEvents(cachedEvents(), filters);
17655
+ if (getSimulation().relay.mode !== "live" || relayUrls2.length === 0) return cached;
17656
+ const liveEvents = await queryLive(livePool, relayUrls2, filters, maxWaitMs);
17657
+ const out = /* @__PURE__ */ new Map();
17658
+ for (const event of [...cached, ...liveEvents]) out.set(event.id, event);
17659
+ return [...out.values()].sort((a, b) => b.created_at - a.created_at);
17604
17660
  };
17605
- return {
17606
- supported: publicSupport,
17607
- add: (list, items, mutationOptions) => mutation("add", list, items, mutationOptions),
17608
- remove: (list, items, mutationOptions) => mutation("remove", list, items, mutationOptions)
17661
+ const queryContactListCandidates = async (relayUrls2, filters, maxWaitMs, signal) => {
17662
+ const cached = collectMemoryEvents(cachedEvents(), filters);
17663
+ if (signal?.aborted || getSimulation().relay.mode !== "live" || relayUrls2.length === 0) return cached;
17664
+ const liveEvents = await queryLive(livePool, relayUrls2, filters, maxWaitMs, true, signal);
17665
+ const out = /* @__PURE__ */ new Map();
17666
+ for (const event of [...cached, ...liveEvents]) out.set(event.id, event);
17667
+ return [...out.values()].sort((a, b) => b.created_at - a.created_at);
17609
17668
  };
17610
- }
17611
-
17612
- // ../nip/dist/chunk-JT5WCCCX.js
17613
- function computeAggregateHash(entries) {
17614
- const lines = entries.map((entry) => `${entry.sha256} ${entry.path}
17615
- `);
17616
- lines.sort();
17617
- return bytesToHex2(sha256(new TextEncoder().encode(lines.join(""))));
17618
- }
17619
- function pathEntriesFromTags(tags) {
17620
- const entries = [];
17621
- for (const tag of tags) {
17622
- if (tag[0] === "path" && typeof tag[1] === "string" && typeof tag[2] === "string" && tag[1].length > 0 && tag[2].length > 0) {
17623
- entries.push({ path: tag[1], sha256: tag[2] });
17669
+ function retainPublishedEvent(event, mode) {
17670
+ if (mode !== "memory") return;
17671
+ acceptedMemoryEvents.push(event);
17672
+ for (const subscriber of subscribers) {
17673
+ if (matchesAnyFilter2(event, subscriber.filters)) subscriber.next(event);
17624
17674
  }
17625
17675
  }
17626
- return entries;
17627
- }
17628
- function aggregateTagValue(tags) {
17629
- for (const tag of tags) {
17630
- if (tag[0] === "x" && tag[2] === "aggregate" && typeof tag[1] === "string" && tag[1].length > 0) {
17631
- return tag[1];
17676
+ async function attemptPublish(relayUrls2, event) {
17677
+ const simulation = getSimulation();
17678
+ const rejected = Object.fromEntries(relayUrls2.map((url) => [url, false]));
17679
+ if (simulation.relay.mode === "disabled") {
17680
+ return { outcomes: rejected, error: "relay unavailable" };
17681
+ }
17682
+ if (!await confirmRequest({ action: "publish", event })) {
17683
+ return { outcomes: rejected, error: "publish denied" };
17632
17684
  }
17685
+ const outcomes = simulation.relay.mode === "live" ? await publishLive(livePool, relayUrls2, event) : Object.fromEntries(relayUrls2.map((url) => [url, true]));
17686
+ if (!Object.values(outcomes).some(Boolean)) {
17687
+ return { outcomes, error: "publish failed" };
17688
+ }
17689
+ retainPublishedEvent(event, simulation.relay.mode);
17690
+ return { outcomes };
17633
17691
  }
17634
- return void 0;
17635
- }
17636
-
17637
- // ../nip/dist/chunk-F6ABV5KZ.js
17638
- var MIB = 1024 * 1024;
17639
- var NAPPLET_ARTIFACT_CACHE_NAME = "kehto:napplet-artifacts:v1";
17640
- var SCHEMA_VERSION = 1;
17641
- var DEFAULT_BASE_URL = "https://kehto.invalid";
17642
- var DEFAULT_UNKNOWN_BUDGET_BYTES = 32 * MIB;
17643
- var DEFAULT_SOFT_CEILING_BYTES = 128 * MIB;
17644
- var DEFAULT_HARD_CEILING_BYTES = 256 * MIB;
17645
- var DEFAULT_FOREGROUND_TTL_MS = 15 * 60 * 1e3;
17646
- var DEFAULT_BACKGROUND_TTL_MS = 60 * 60 * 1e3;
17647
- function emptyIndex(now2) {
17648
- return {
17649
- schemaVersion: SCHEMA_VERSION,
17650
- updatedAt: now2,
17651
- blobs: {},
17652
- aggregates: {},
17653
- coordinates: {}
17692
+ const backend = {
17693
+ subscription(relayUrls2, filtersInput) {
17694
+ return {
17695
+ subscribe(next) {
17696
+ const filters = normalizedFilters(filtersInput);
17697
+ const subscriber = {
17698
+ filters,
17699
+ next: (item) => next(item)
17700
+ };
17701
+ subscribers.add(subscriber);
17702
+ for (const event of collectMemoryEvents(cachedEvents(), filters)) next(event);
17703
+ const liveSub = getSimulation().relay.mode === "live" ? subscribeLive(livePool, relayUrls2, filters, subscriber.next) : null;
17704
+ queueMicrotask(() => {
17705
+ if (subscribers.has(subscriber) && !liveSub) next("EOSE");
17706
+ });
17707
+ return {
17708
+ unsubscribe() {
17709
+ subscribers.delete(subscriber);
17710
+ liveSub?.unsubscribe();
17711
+ }
17712
+ };
17713
+ }
17714
+ };
17715
+ },
17716
+ async publish(relayUrls2, event) {
17717
+ const attempt = await attemptPublish(relayUrls2, event);
17718
+ if (attempt.error) throw new Error(attempt.error);
17719
+ },
17720
+ request(relayUrls2, filtersInput) {
17721
+ return {
17722
+ subscribe(observer) {
17723
+ const filters = normalizedFilters(filtersInput);
17724
+ let active = true;
17725
+ query(relayUrls2, filters).then((matched) => {
17726
+ if (!active) return;
17727
+ for (const event of matched) observer.next(event);
17728
+ observer.complete();
17729
+ }).catch(() => {
17730
+ if (active) observer.error();
17731
+ });
17732
+ return { unsubscribe() {
17733
+ active = false;
17734
+ } };
17735
+ }
17736
+ };
17737
+ },
17738
+ async count(relayUrls2, filters) {
17739
+ if (getSimulation().relay.mode !== "live") throw new Error("count unavailable");
17740
+ return (await countLive(livePool, relayUrls2, normalizedFilters(filters))).count;
17741
+ },
17742
+ async countWithRelay(relayUrls2, filters) {
17743
+ if (getSimulation().relay.mode !== "live") throw new Error("count unavailable");
17744
+ return countLive(livePool, relayUrls2, normalizedFilters(filters));
17745
+ },
17746
+ observedRelayUrls(eventId) {
17747
+ return [...livePool.seenOn?.get(eventId) ?? []].map((relay) => relay.url);
17748
+ },
17749
+ query,
17750
+ async publishToRelays(relayUrls2, event) {
17751
+ return (await attemptPublish(relayUrls2, event)).outcomes;
17752
+ },
17753
+ async publishWebrtcSignal(relayUrls2, event) {
17754
+ if (getSimulation().relay.mode !== "live" || relayUrls2.length === 0 || event.kind !== PAJA_WEBRTC_SIGNAL_KIND || !verifyEvent(event)) {
17755
+ throw new Error("signaling unavailable");
17756
+ }
17757
+ const outcomes = await publishLive(livePool, relayUrls2, event);
17758
+ if (!Object.values(outcomes).some(Boolean)) throw new Error("signaling unavailable");
17759
+ retainPublishedEvent(event, "live");
17760
+ },
17761
+ async publishDmGiftWrap(relayUrls2, event) {
17762
+ if (getSimulation().relay.mode !== "live" || relayUrls2.length === 0 || event.kind !== NIP17_GIFT_WRAP_KIND2 || !verifyEvent(event)) {
17763
+ throw new Error("DM relay publication failed");
17764
+ }
17765
+ const outcomes = await publishLive(livePool, relayUrls2, event);
17766
+ if (!Object.values(outcomes).some(Boolean)) throw new Error("DM relay publication failed");
17767
+ retainPublishedEvent(event, "live");
17768
+ },
17769
+ isAvailable,
17770
+ close() {
17771
+ livePool.destroy();
17772
+ }
17654
17773
  };
17774
+ contactListCandidateQueries.set(backend, queryContactListCandidates);
17775
+ return backend;
17655
17776
  }
17656
- function aggregateKey(dTag, aggregateHash) {
17657
- return `${encodeURIComponent(dTag)}:${aggregateHash}`;
17658
- }
17659
- function coordinateKey(kind, pubkey2, dTag) {
17660
- return `${kind}:${pubkey2}:${encodeURIComponent(dTag)}`;
17661
- }
17662
- function isCoordinateFresh(coordinate, options = {}) {
17663
- const now2 = options.now ?? Date.now();
17664
- const ttl = options.background ? coordinate.backgroundTtlMs : coordinate.foregroundTtlMs;
17665
- return ttl === Number.POSITIVE_INFINITY || now2 - coordinate.lastResolvedAt <= ttl;
17666
- }
17667
- function byteLength2(bytes) {
17668
- return bytes.byteLength;
17669
- }
17670
- function encodeKeyPart(value) {
17671
- return encodeURIComponent(value).replaceAll("%2F", "%252F");
17672
- }
17673
- function cloneBytes(bytes) {
17674
- return new Uint8Array(bytes);
17675
- }
17676
- function responseBody(bytes) {
17677
- return cloneBytes(bytes).buffer;
17777
+ function toNostrEvent(value) {
17778
+ if (typeof value === "object" && value !== null && typeof value.id === "string" && typeof value.pubkey === "string" && typeof value.kind === "number" && Array.isArray(value.tags) && typeof value.content === "string" && typeof value.sig === "string") {
17779
+ return [value];
17780
+ }
17781
+ return [];
17678
17782
  }
17679
- function normalizeBaseUrl(baseUrl) {
17680
- return baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
17783
+ function getPajaRelayUrls(simulation) {
17784
+ return simulation.relay.mode === "disabled" ? [] : [...simulation.relay.urls];
17681
17785
  }
17682
- function resolveBaseUrl(baseUrl) {
17683
- if (baseUrl) return normalizeBaseUrl(baseUrl);
17684
- const maybeLocation = globalThis;
17685
- if (maybeLocation.location?.origin) return normalizeBaseUrl(maybeLocation.location.origin);
17686
- return normalizeBaseUrl(DEFAULT_BASE_URL);
17786
+ function dedupeRelayUrls(urls) {
17787
+ const out = /* @__PURE__ */ new Set();
17788
+ for (const url of urls) {
17789
+ const trimmed = url.trim();
17790
+ if (trimmed.length > 0) out.add(trimmed);
17791
+ }
17792
+ return [...out];
17687
17793
  }
17688
- async function responseBytes(response) {
17689
- return new Uint8Array(await response.arrayBuffer());
17794
+ async function getSignerRelayUrls(signerProvider, direction) {
17795
+ const signer = signerProvider?.getSigner();
17796
+ if (!signer?.getRelays) return [];
17797
+ try {
17798
+ const relays = await signer.getRelays();
17799
+ return dedupeRelayUrls(Object.entries(relays).flatMap(([url, permissions]) => {
17800
+ if (direction === "read" && permissions.read) return [url];
17801
+ if (direction === "write" && permissions.write) return [url];
17802
+ return [];
17803
+ }));
17804
+ } catch {
17805
+ return [];
17806
+ }
17690
17807
  }
17691
- async function responseJson(response) {
17692
- return response.json();
17808
+ async function getBootstrapRelayUrls(getSimulation, signerProvider, getHostRelayUrls) {
17809
+ return dedupeRelayUrls([
17810
+ ...getHostRelayUrls?.() ?? getPajaRelayUrls(getSimulation()),
17811
+ ...await getSignerRelayUrls(signerProvider, "read")
17812
+ ]);
17693
17813
  }
17694
- function refCounts(index) {
17695
- const counts = {};
17696
- for (const aggregate of Object.values(index.aggregates)) {
17697
- for (const hash of aggregate.blobHashes) counts[hash] = (counts[hash] ?? 0) + 1;
17698
- }
17699
- return counts;
17814
+ function createPajaContactListLoader(backend, getSimulation, signerProvider, getHostRelayUrls) {
17815
+ return async (pubkey2, signal) => {
17816
+ if (!/^[0-9a-fA-F]{64}$/.test(pubkey2) || signal?.aborted) return [];
17817
+ const relayUrls2 = await getBootstrapRelayUrls(getSimulation, signerProvider, getHostRelayUrls);
17818
+ if (signal?.aborted) return [];
17819
+ const filters = [{
17820
+ kinds: [PAJA_CONTACT_LIST_KIND],
17821
+ authors: [pubkey2],
17822
+ limit: PAJA_CONTACT_LIST_CANDIDATE_LIMIT
17823
+ }];
17824
+ const contactQuery = contactListCandidateQueries.get(backend);
17825
+ const candidates = contactQuery ? await contactQuery(relayUrls2, filters, PAJA_LIVE_QUERY_WAIT_MS, signal) : await backend.query(relayUrls2, filters, PAJA_LIVE_QUERY_WAIT_MS);
17826
+ if (signal?.aborted) return [];
17827
+ return candidates.filter((event) => event.kind === PAJA_CONTACT_LIST_KIND && event.pubkey.toLowerCase() === pubkey2.toLowerCase()).sort((left, right) => right.created_at - left.created_at || left.id.localeCompare(right.id)).slice(0, PAJA_CONTACT_LIST_CANDIDATE_LIMIT);
17828
+ };
17700
17829
  }
17701
- function cachedSize(index) {
17702
- const blobBytes = Object.values(index.blobs).reduce((sum, entry) => sum + entry.size, 0);
17703
- const aggregateBytes = Object.values(index.aggregates).reduce((sum, entry) => sum + entry.size, 0);
17704
- return blobBytes + aggregateBytes;
17830
+ function latestEvent(events, kind, pubkey2) {
17831
+ return events.filter((event) => event.kind === kind && event.pubkey === pubkey2).sort((a, b) => b.created_at - a.created_at)[0];
17705
17832
  }
17706
- var CacheStorageNappletArtifactCache = class {
17707
- cacheStorage;
17708
- storage;
17709
- cacheName;
17710
- baseUrl;
17711
- now;
17712
- activeAggregates = /* @__PURE__ */ new Set();
17713
- onDiagnostic;
17714
- unknownBudgetBytes;
17715
- softCeilingBytes;
17716
- hardCeilingBytes;
17717
- cachePromise;
17718
- constructor(options = {}) {
17719
- const maybeCacheStorage = options.cacheStorage ?? globalThis.caches;
17720
- if (!maybeCacheStorage) {
17721
- throw new Error("Cache Storage is unavailable");
17833
+ function createPajaRelayListLoader(backend, getSimulation, signerProvider, getHostRelayUrls) {
17834
+ const registry2 = createNip65Registry();
17835
+ return async (pubkeys) => {
17836
+ const uniquePubkeys = [...new Set(pubkeys.filter((pubkey2) => /^[0-9a-fA-F]{64}$/.test(pubkey2)))];
17837
+ const missing = uniquePubkeys.filter((pubkey2) => !registry2.has(pubkey2));
17838
+ if (missing.length > 0) {
17839
+ const events = await backend.query(await getBootstrapRelayUrls(
17840
+ getSimulation,
17841
+ signerProvider,
17842
+ getHostRelayUrls
17843
+ ), [{
17844
+ kinds: [PAJA_NIP65_RELAY_LIST_KIND],
17845
+ authors: missing,
17846
+ limit: Math.max(missing.length * 2, 10)
17847
+ }], PAJA_LIVE_QUERY_WAIT_MS);
17848
+ for (const pubkey2 of missing) {
17849
+ const event = latestEvent(events, PAJA_NIP65_RELAY_LIST_KIND, pubkey2);
17850
+ if (event) registry2.ingest(event);
17851
+ }
17722
17852
  }
17723
- this.cacheStorage = maybeCacheStorage;
17724
- this.storage = options.storage ?? globalThis.navigator?.storage;
17725
- this.cacheName = options.cacheName ?? NAPPLET_ARTIFACT_CACHE_NAME;
17726
- this.baseUrl = resolveBaseUrl(options.baseUrl);
17727
- this.now = options.now ?? Date.now;
17728
- this.onDiagnostic = options.onDiagnostic;
17729
- this.unknownBudgetBytes = options.unknownBudgetBytes ?? DEFAULT_UNKNOWN_BUDGET_BYTES;
17730
- this.softCeilingBytes = options.softCeilingBytes ?? DEFAULT_SOFT_CEILING_BYTES;
17731
- this.hardCeilingBytes = options.hardCeilingBytes ?? DEFAULT_HARD_CEILING_BYTES;
17732
- }
17733
- async readBlob(sha256Hex) {
17734
- try {
17735
- const cache2 = await this.open();
17736
- const response = await cache2.match(this.blobUrl(sha256Hex));
17737
- if (!response) return void 0;
17738
- const bytes = await responseBytes(response);
17739
- const index = await this.readIndex(cache2);
17740
- const entry = index.blobs[sha256Hex];
17741
- if (entry) {
17742
- entry.lastAccessed = this.now();
17743
- index.updatedAt = entry.lastAccessed;
17744
- await this.writeIndex(cache2, index);
17853
+ const out = /* @__PURE__ */ new Map();
17854
+ for (const pubkey2 of uniquePubkeys) {
17855
+ const entries = registry2.getRelayList(pubkey2);
17856
+ if (entries) {
17857
+ out.set(pubkey2, {
17858
+ read: selectReadRelays(entries),
17859
+ write: selectWriteRelays(entries)
17860
+ });
17745
17861
  }
17746
- return bytes;
17747
- } catch (cause) {
17748
- this.diagnostic({ type: "cache-read-failed", message: `failed to read blob ${sha256Hex}`, cause });
17749
- return void 0;
17750
17862
  }
17751
- }
17752
- async deleteBlob(sha256Hex) {
17753
- try {
17754
- const cache2 = await this.open();
17755
- await cache2.delete(this.blobUrl(sha256Hex));
17756
- const index = await this.readIndex(cache2);
17757
- delete index.blobs[sha256Hex];
17758
- index.updatedAt = this.now();
17759
- await this.writeIndex(cache2, index);
17760
- } catch (cause) {
17761
- this.diagnostic({ type: "cache-delete-failed", message: `failed to delete blob ${sha256Hex}`, cause });
17863
+ return out;
17864
+ };
17865
+ }
17866
+ function createPajaOutboxRelayPool(backend) {
17867
+ return {
17868
+ subscribe(filters, relayUrls2, callback) {
17869
+ return backend.subscription(relayUrls2, filters).subscribe((item) => callback(item));
17870
+ },
17871
+ publish(event, relayUrls2) {
17872
+ return backend.publishToRelays(relayUrls2, event);
17873
+ },
17874
+ isAvailable() {
17875
+ return backend.isAvailable();
17876
+ }
17877
+ };
17878
+ }
17879
+
17880
+ // src/browser-social-cache.ts
17881
+ var HEX_PUBKEY = /^[0-9a-f]{64}$/i;
17882
+ var FOLLOW_PARSE_YIELD_EVERY = 64;
17883
+ var PROFILE_WARM_YIELD_EVERY = 64;
17884
+ function createPajaSocialCache(options) {
17885
+ let generation = 0;
17886
+ let activeRefreshController;
17887
+ const snapshots = /* @__PURE__ */ new Map();
17888
+ async function loadFollows(capturedPubkey) {
17889
+ const normalizedPubkey = normalizePubkey2(capturedPubkey);
17890
+ if (!normalizedPubkey) return [];
17891
+ const existing = snapshots.get(normalizedPubkey);
17892
+ if (existing) return [...existing.follows];
17893
+ const capturedGeneration = generation;
17894
+ const follows = await verifiedFollows(normalizedPubkey);
17895
+ const warmed = snapshots.get(normalizedPubkey);
17896
+ if (warmed) return [...warmed.follows];
17897
+ if (generation === capturedGeneration) {
17898
+ snapshots.set(normalizedPubkey, { follows, profiles: /* @__PURE__ */ new Map() });
17762
17899
  }
17900
+ return [...follows];
17763
17901
  }
17764
- async writeVerifiedResolution(input) {
17765
- try {
17766
- await this.writeVerifiedResolutionOnce(input);
17767
- } catch (firstCause) {
17902
+ async function verifiedFollows(capturedPubkey, isStillCurrent, signal) {
17903
+ const candidates = await options.loadContactList(capturedPubkey, signal);
17904
+ const verified = [];
17905
+ for (const candidate of candidates) {
17906
+ if (isStillCurrent && !isStillCurrent()) return [];
17907
+ if (!isContactCandidate(candidate, capturedPubkey)) continue;
17768
17908
  try {
17769
- await this.prune(input.now ?? this.now());
17770
- await this.writeVerifiedResolutionOnce(input);
17771
- } catch (cause) {
17772
- this.diagnostic({
17773
- type: "cache-write-failed",
17774
- message: "failed to write verified napplet artifacts after prune retry",
17775
- cause: cause ?? firstCause
17776
- });
17909
+ if (await options.verifyEvent(candidate)) verified.push(candidate);
17910
+ } catch {
17777
17911
  }
17778
17912
  }
17913
+ return contactPubkeys(selectReplacement(verified), isStillCurrent);
17779
17914
  }
17780
- async writeCoordinate(input) {
17781
- const cache2 = await this.open();
17782
- const now2 = this.now();
17783
- const index = await this.readIndex(cache2);
17784
- const key = coordinateKey(input.kind, input.pubkey, input.dTag);
17785
- index.coordinates[key] = {
17786
- key,
17787
- kind: input.kind,
17788
- pubkey: input.pubkey,
17789
- dTag: input.dTag,
17790
- aggregateHash: input.aggregateHash,
17791
- lastResolvedAt: input.lastResolvedAt ?? now2,
17792
- foregroundTtlMs: input.foregroundTtlMs ?? DEFAULT_FOREGROUND_TTL_MS,
17793
- backgroundTtlMs: input.backgroundTtlMs ?? DEFAULT_BACKGROUND_TTL_MS
17794
- };
17795
- index.updatedAt = now2;
17796
- await this.writeIndex(cache2, index);
17797
- }
17798
- async getCoordinate(input, options = {}) {
17799
- const cache2 = await this.open();
17800
- const index = await this.readIndex(cache2);
17801
- const coordinate = index.coordinates[coordinateKey(input.kind, input.pubkey, input.dTag)];
17802
- if (!coordinate) return void 0;
17803
- return { ...coordinate, fresh: isCoordinateFresh(coordinate, options) };
17804
- }
17805
- async touchAggregate(dTag, aggregateHash, now2 = this.now()) {
17806
- const cache2 = await this.open();
17807
- const index = await this.readIndex(cache2);
17808
- const key = aggregateKey(dTag, aggregateHash);
17809
- const aggregate = index.aggregates[key];
17810
- if (!aggregate) return;
17811
- aggregate.lastAccessed = now2;
17812
- for (const hash of aggregate.blobHashes) {
17813
- if (index.blobs[hash]) index.blobs[hash].lastAccessed = now2;
17814
- }
17815
- index.updatedAt = now2;
17816
- await this.writeIndex(cache2, index);
17817
- }
17818
- markAggregateActive(dTag, aggregateHash) {
17819
- this.activeAggregates.add(aggregateKey(dTag, aggregateHash));
17820
- }
17821
- releaseAggregateActive(dTag, aggregateHash) {
17822
- this.activeAggregates.delete(aggregateKey(dTag, aggregateHash));
17823
- }
17824
- async prune(now2 = this.now()) {
17915
+ async function refreshActiveIdentity() {
17916
+ activeRefreshController?.abort();
17917
+ activeRefreshController = void 0;
17918
+ const currentGeneration = ++generation;
17919
+ const capturedPubkey = normalizePubkey2(options.getActivePubkey() ?? "");
17920
+ if (!capturedPubkey) return;
17921
+ const controller = new AbortController();
17922
+ activeRefreshController = controller;
17923
+ const isStillCurrent = () => !controller.signal.aborted && isCurrent(capturedPubkey, currentGeneration);
17825
17924
  try {
17826
- const cache2 = await this.open();
17827
- const index = await this.readIndex(cache2);
17828
- let size = cachedSize(index);
17829
- const budget = await this.budgetBytes();
17830
- const hardBudget = await this.hardBudgetBytes();
17831
- const shouldPrune = size > budget || await this.originPressureHigh();
17832
- if (!shouldPrune) return;
17833
- this.rewriteRefCounts(index);
17834
- for (const [hash, blob] of Object.entries(index.blobs)) {
17835
- if (size <= budget) break;
17836
- if (blob.refCount > 0) continue;
17837
- await cache2.delete(this.blobUrl(hash));
17838
- delete index.blobs[hash];
17839
- size -= blob.size;
17840
- }
17841
- const currentAggregateHashes = new Set(
17842
- Object.values(index.coordinates).map((coordinate) => coordinate.aggregateHash)
17843
- );
17844
- const aggregates = Object.values(index.aggregates).filter((entry) => !this.activeAggregates.has(entry.key)).sort((a, b) => {
17845
- const currentA = currentAggregateHashes.has(a.aggregateHash) ? 1 : 0;
17846
- const currentB = currentAggregateHashes.has(b.aggregateHash) ? 1 : 0;
17847
- if (currentA !== currentB) return currentA - currentB;
17848
- return a.lastAccessed - b.lastAccessed;
17849
- });
17850
- for (const aggregate of aggregates) {
17851
- if (size <= budget) break;
17852
- await cache2.delete(this.aggregateUrl(aggregate.key));
17853
- delete index.aggregates[aggregate.key];
17854
- size -= aggregate.size;
17855
- this.rewriteRefCounts(index);
17856
- }
17857
- if (size > hardBudget) {
17858
- const active = Object.values(index.aggregates).filter((entry) => this.activeAggregates.has(entry.key)).sort((a, b) => a.lastAccessed - b.lastAccessed);
17859
- for (const aggregate of active) {
17860
- if (size <= hardBudget) break;
17861
- await cache2.delete(this.aggregateUrl(aggregate.key));
17862
- delete index.aggregates[aggregate.key];
17863
- size -= aggregate.size;
17925
+ const follows = await verifiedFollows(capturedPubkey, isStillCurrent, controller.signal);
17926
+ if (!isStillCurrent()) return;
17927
+ const snapshot = { follows, profiles: /* @__PURE__ */ new Map() };
17928
+ snapshots.set(capturedPubkey, snapshot);
17929
+ for (let index = 0; index < follows.length; index += 1) {
17930
+ if (!isStillCurrent()) return;
17931
+ const author = follows[index];
17932
+ let warmed;
17933
+ try {
17934
+ warmed = await options.baseRouter.query(
17935
+ [{ kinds: [0], authors: [author], limit: 1 }],
17936
+ { authors: [author], limit: 1 }
17937
+ );
17938
+ } catch {
17864
17939
  }
17865
- }
17866
- this.rewriteRefCounts(index);
17867
- for (const [hash, blob] of Object.entries(index.blobs)) {
17868
- if (blob.refCount === 0) {
17869
- await cache2.delete(this.blobUrl(hash));
17870
- delete index.blobs[hash];
17940
+ if (!isStillCurrent()) return;
17941
+ if (warmed) {
17942
+ const profile = profileResult(warmed, author);
17943
+ if (profile) snapshot.profiles.set(author, profile);
17944
+ }
17945
+ if ((index + 1) % PROFILE_WARM_YIELD_EVERY === 0 && index + 1 < follows.length) {
17946
+ if (!isStillCurrent()) return;
17947
+ await yieldToEventLoop();
17948
+ if (!isStillCurrent()) return;
17871
17949
  }
17872
17950
  }
17873
- index.updatedAt = now2;
17874
- await this.writeIndex(cache2, index);
17875
- } catch (cause) {
17876
- this.diagnostic({ type: "cache-prune-failed", message: "failed to prune napplet artifact cache", cause });
17951
+ } catch {
17952
+ } finally {
17953
+ if (activeRefreshController === controller) activeRefreshController = void 0;
17877
17954
  }
17878
17955
  }
17879
- async snapshotIndex() {
17880
- return this.readIndex(await this.open());
17956
+ function isCurrent(capturedPubkey, currentGeneration) {
17957
+ return generation === currentGeneration && normalizePubkey2(options.getActivePubkey() ?? "") === capturedPubkey;
17881
17958
  }
17882
- async writeVerifiedResolutionOnce(input) {
17883
- const cache2 = await this.open();
17884
- const now2 = input.now ?? this.now();
17885
- const index = await this.readIndex(cache2);
17886
- const blobHashes = [];
17887
- for (const pathEntry of input.manifest.paths) {
17888
- const bytes = input.files.get(pathEntry.path);
17889
- if (!bytes) continue;
17890
- blobHashes.push(pathEntry.sha256);
17891
- await cache2.put(this.blobUrl(pathEntry.sha256), new Response(responseBody(bytes)));
17892
- index.blobs[pathEntry.sha256] = {
17893
- size: byteLength2(bytes),
17894
- lastAccessed: now2,
17895
- refCount: index.blobs[pathEntry.sha256]?.refCount ?? 0
17896
- };
17897
- }
17898
- const key = aggregateKey(input.manifest.dTag, input.manifest.aggregateHash);
17899
- const record = {
17900
- schemaVersion: SCHEMA_VERSION,
17901
- dTag: input.manifest.dTag,
17902
- aggregateHash: input.manifest.aggregateHash,
17903
- manifest: {
17904
- kind: input.manifest.kind,
17905
- pubkey: input.manifest.pubkey,
17906
- dTag: input.manifest.dTag,
17907
- paths: input.manifest.paths.map((entry) => ({ path: entry.path, sha256: entry.sha256 })),
17908
- requires: [...input.manifest.requires],
17909
- ...input.manifest.title === void 0 ? {} : { title: input.manifest.title },
17910
- ...input.manifest.description === void 0 ? {} : { description: input.manifest.description }
17959
+ function decorate(router, canReadIdentity) {
17960
+ return {
17961
+ ...router.getEvent ? { getEvent: router.getEvent.bind(router) } : {},
17962
+ async query(filters, queryOptions) {
17963
+ const canAugmentAtStart = canReadIdentity?.() ?? true;
17964
+ const activePubkey = normalizePubkey2(options.getActivePubkey() ?? "");
17965
+ const snapshot = canAugmentAtStart && activePubkey ? snapshots.get(activePubkey) : void 0;
17966
+ const base = await router.query(filters, queryOptions);
17967
+ if (!canAugmentAtStart || !(canReadIdentity?.() ?? true)) return base;
17968
+ const cached = matchingCachedProfiles(snapshot?.profiles, filters);
17969
+ return mergeResult(base, cached, filters, queryOptions);
17911
17970
  },
17912
- indexHtml: input.indexHtml,
17913
- blobHashes,
17914
- writtenAt: now2
17915
- };
17916
- const aggregateBytes = new TextEncoder().encode(JSON.stringify(record));
17917
- await cache2.put(this.aggregateUrl(key), new Response(responseBody(aggregateBytes), {
17918
- headers: { "content-type": "application/json" }
17919
- }));
17920
- const coordKey = coordinateKey(input.manifest.kind, input.manifest.pubkey, input.manifest.dTag);
17921
- index.aggregates[key] = {
17922
- dTag: input.manifest.dTag,
17923
- aggregateHash: input.manifest.aggregateHash,
17924
- key,
17925
- blobHashes,
17926
- size: byteLength2(aggregateBytes),
17927
- lastAccessed: now2,
17928
- coordinateKey: coordKey
17929
- };
17930
- index.coordinates[coordKey] = {
17931
- key: coordKey,
17932
- kind: input.manifest.kind,
17933
- pubkey: input.manifest.pubkey,
17934
- dTag: input.manifest.dTag,
17935
- aggregateHash: input.manifest.aggregateHash,
17936
- lastResolvedAt: now2,
17937
- foregroundTtlMs: DEFAULT_FOREGROUND_TTL_MS,
17938
- backgroundTtlMs: DEFAULT_BACKGROUND_TTL_MS
17971
+ subscribe: router.subscribe.bind(router),
17972
+ publish: router.publish.bind(router),
17973
+ resolveRelays: router.resolveRelays.bind(router)
17939
17974
  };
17940
- this.rewriteRefCounts(index);
17941
- index.updatedAt = now2;
17942
- await this.writeIndex(cache2, index);
17943
- await this.prune(now2);
17944
- }
17945
- async open() {
17946
- this.cachePromise ??= this.cacheStorage.open(this.cacheName);
17947
- return this.cachePromise;
17948
- }
17949
- indexUrl() {
17950
- return new URL("__kehto_napplet_cache/index.json", this.baseUrl).toString();
17951
- }
17952
- blobUrl(hash) {
17953
- return new URL(`__kehto_napplet_cache/blob/${encodeKeyPart(hash)}`, this.baseUrl).toString();
17954
- }
17955
- aggregateUrl(key) {
17956
- return new URL(`__kehto_napplet_cache/aggregate/${encodeKeyPart(key)}.json`, this.baseUrl).toString();
17957
17975
  }
17958
- async readIndex(cache2) {
17959
- const response = await cache2.match(this.indexUrl());
17960
- if (!response) return emptyIndex(this.now());
17961
- try {
17962
- const index = await responseJson(response);
17963
- if (index.schemaVersion !== SCHEMA_VERSION) return emptyIndex(this.now());
17964
- return index;
17965
- } catch {
17966
- return emptyIndex(this.now());
17976
+ const unsubscribe = options.subscribeSignerChange?.(() => {
17977
+ void refreshActiveIdentity();
17978
+ });
17979
+ return {
17980
+ getFollows: loadFollows,
17981
+ refreshActiveIdentity,
17982
+ decorate,
17983
+ dispose: () => {
17984
+ activeRefreshController?.abort();
17985
+ unsubscribe?.();
17967
17986
  }
17968
- }
17969
- async writeIndex(cache2, index) {
17970
- await cache2.put(this.indexUrl(), new Response(JSON.stringify(index), {
17971
- headers: { "content-type": "application/json" }
17972
- }));
17973
- }
17974
- rewriteRefCounts(index) {
17975
- const counts = refCounts(index);
17976
- for (const [hash, blob] of Object.entries(index.blobs)) {
17977
- blob.refCount = counts[hash] ?? 0;
17987
+ };
17988
+ }
17989
+ function normalizePubkey2(value) {
17990
+ return typeof value === "string" && HEX_PUBKEY.test(value) ? value.toLowerCase() : null;
17991
+ }
17992
+ function isContactCandidate(candidate, capturedPubkey) {
17993
+ if (typeof candidate !== "object" || candidate === null) return false;
17994
+ const event = candidate;
17995
+ return event.kind === 3 && normalizePubkey2(event.pubkey) === capturedPubkey;
17996
+ }
17997
+ function selectReplacement(events) {
17998
+ return [...events].sort((left, right) => {
17999
+ const timestampOrder = right.created_at - left.created_at;
18000
+ if (timestampOrder !== 0) return timestampOrder;
18001
+ if (left.id === right.id) return 0;
18002
+ return left.id < right.id ? -1 : 1;
18003
+ })[0];
18004
+ }
18005
+ async function contactPubkeys(event, isStillCurrent) {
18006
+ if (!event || !Array.isArray(event.tags)) return [];
18007
+ const follows = /* @__PURE__ */ new Set();
18008
+ for (let index = 0; index < event.tags.length; index += 1) {
18009
+ if (isStillCurrent && !isStillCurrent()) return [];
18010
+ const tag = event.tags[index];
18011
+ if (Array.isArray(tag) && tag[0] === "p") {
18012
+ const pubkey2 = normalizePubkey2(tag[1]);
18013
+ if (pubkey2) follows.add(pubkey2);
18014
+ }
18015
+ if ((index + 1) % FOLLOW_PARSE_YIELD_EVERY === 0 && index + 1 < event.tags.length) {
18016
+ await yieldToEventLoop();
18017
+ if (isStillCurrent && !isStillCurrent()) return [];
17978
18018
  }
17979
18019
  }
17980
- async budgetBytes() {
17981
- const estimate = await this.estimateStorage();
17982
- if (!estimate?.quota) return this.unknownBudgetBytes;
17983
- return Math.min(this.softCeilingBytes, Math.floor(estimate.quota * 0.1));
17984
- }
17985
- async hardBudgetBytes() {
17986
- const estimate = await this.estimateStorage();
17987
- if (!estimate?.quota) return this.unknownBudgetBytes;
17988
- return Math.min(this.hardCeilingBytes, Math.floor(estimate.quota * 0.2));
18020
+ return [...follows];
18021
+ }
18022
+ function profileResult(result2, author) {
18023
+ let newest;
18024
+ for (const entry of result2.events) {
18025
+ if (entry.event.kind !== 0 || normalizePubkey2(entry.event.pubkey) !== author) continue;
18026
+ if (!newest || isNewerProfile(entry, newest)) newest = entry;
17989
18027
  }
17990
- async originPressureHigh() {
17991
- const estimate = await this.estimateStorage();
17992
- if (!estimate?.quota || estimate.usage === void 0) return false;
17993
- return estimate.usage / estimate.quota >= 0.8;
18028
+ return newest;
18029
+ }
18030
+ function isNewerProfile(candidate, existing) {
18031
+ if (candidate.event.created_at !== existing.event.created_at) {
18032
+ return candidate.event.created_at > existing.event.created_at;
17994
18033
  }
17995
- async estimateStorage() {
17996
- if (!this.storage?.estimate) return void 0;
17997
- try {
17998
- return this.storage.estimate();
17999
- } catch (cause) {
18000
- this.diagnostic({
18001
- type: "storage-estimate-unavailable",
18002
- message: "storage estimate failed; using unknown quota cache budget",
18003
- cause
18004
- });
18005
- return void 0;
18034
+ return candidate.event.id < existing.event.id;
18035
+ }
18036
+ function yieldToEventLoop() {
18037
+ return new Promise((resolve) => setTimeout(resolve, 0));
18038
+ }
18039
+ function matchingCachedProfiles(profiles, filters) {
18040
+ const readyProfiles = profiles ? [...profiles.values()] : [];
18041
+ if (filters.length === 0) return readyProfiles;
18042
+ const matched = /* @__PURE__ */ new Map();
18043
+ for (const filter of filters) {
18044
+ const limit = typeof filter.limit === "number" && filter.limit >= 0 ? filter.limit : void 0;
18045
+ let count = 0;
18046
+ for (const entry of readyProfiles) {
18047
+ if (!matchesAnyFilter2(entry.event, [filter])) continue;
18048
+ if (limit !== void 0 && count >= limit) continue;
18049
+ count += 1;
18050
+ if (!matched.has(entry.event.id)) matched.set(entry.event.id, entry);
18006
18051
  }
18007
18052
  }
18008
- diagnostic(diagnostic) {
18009
- this.onDiagnostic?.(diagnostic);
18053
+ return [...matched.values()];
18054
+ }
18055
+ function mergeResult(base, cached, filters, queryOptions) {
18056
+ const events = /* @__PURE__ */ new Map();
18057
+ for (const entry of base.events) events.set(entry.event.id, entry);
18058
+ for (const entry of cached) {
18059
+ if (!events.has(entry.event.id)) events.set(entry.event.id, entry);
18010
18060
  }
18011
- };
18012
- async function openNappletArtifactCache(options = {}) {
18013
- const cacheStorage = options.cacheStorage ?? globalThis.caches;
18014
- if (!cacheStorage) return void 0;
18015
- const storage = options.storage ?? globalThis.navigator?.storage;
18016
- if (options.requireStorageEstimate && !storage?.estimate) {
18017
- options.onDiagnostic?.({
18018
- type: "storage-estimate-unavailable",
18019
- message: "storage estimates are unavailable; using network-only loading"
18061
+ return {
18062
+ events: applyFinalLimits([...events.values()], filters, queryOptions),
18063
+ ...base.incomplete === void 0 ? {} : { incomplete: base.incomplete },
18064
+ ...base.error === void 0 ? {} : { error: base.error }
18065
+ };
18066
+ }
18067
+ function applyFinalLimits(entries, filters, queryOptions) {
18068
+ const aggregateLimit = typeof queryOptions?.limit === "number" && queryOptions.limit >= 0 ? queryOptions.limit : void 0;
18069
+ const aggregateCapped = aggregateLimit === void 0 ? entries : entries.slice(0, aggregateLimit);
18070
+ if (filters.length === 0) return aggregateCapped;
18071
+ const counts = filters.map(() => 0);
18072
+ return aggregateCapped.filter((entry) => {
18073
+ const matching = filters.flatMap((filter, index) => matchesAnyFilter2(entry.event, [filter]) ? [index] : []);
18074
+ const allowed2 = matching.some((index) => {
18075
+ const limit = filters[index]?.limit;
18076
+ return typeof limit !== "number" || limit < 0 || counts[index] < limit;
18020
18077
  });
18021
- return void 0;
18022
- }
18078
+ if (!allowed2) return false;
18079
+ for (const index of matching) counts[index] += 1;
18080
+ return true;
18081
+ });
18082
+ }
18083
+
18084
+ // src/browser-relay-policy.ts
18085
+ var PAJA_STORAGE_PROBE_KEY = "kehto:paja:storage-probe";
18086
+ function normalizeRelayUrl(value) {
18023
18087
  try {
18024
- const cache2 = new CacheStorageNappletArtifactCache({ ...options, cacheStorage, storage });
18025
- await cache2.snapshotIndex();
18026
- return cache2;
18027
- } catch (cause) {
18028
- options.onDiagnostic?.({
18029
- type: "cache-open-failed",
18030
- message: "Cache Storage napplet artifact cache could not be opened",
18031
- cause
18032
- });
18033
- return void 0;
18088
+ const url = new URL(value);
18089
+ if (url.protocol !== "wss:" && url.protocol !== "ws:" || url.username || url.password) return null;
18090
+ url.hash = "";
18091
+ return url.href;
18092
+ } catch {
18093
+ return null;
18034
18094
  }
18035
18095
  }
18036
- var NAPPLET_KIND_SNAPSHOT = 5129;
18037
- var NAPPLET_KIND_ROOT = 15129;
18038
- var NAPPLET_KIND_NAMED = 35129;
18039
- var NAPPLET_KINDS = [
18040
- NAPPLET_KIND_SNAPSHOT,
18041
- NAPPLET_KIND_ROOT,
18042
- NAPPLET_KIND_NAMED
18043
- ];
18044
- function isNappletManifestKind(kind) {
18045
- return NAPPLET_KINDS.includes(kind);
18046
- }
18047
- var NappletResolutionError = class extends Error {
18048
- code;
18049
- constructor(code, message) {
18050
- super(message);
18051
- this.name = "NappletResolutionError";
18052
- this.code = code;
18053
- }
18054
- };
18055
- function firstTagValue(tags, name) {
18056
- for (const tag of tags) {
18057
- if (tag[0] === name && typeof tag[1] === "string" && tag[1].length > 0) return tag[1];
18096
+ function isVerifiedNostrEvent(value) {
18097
+ if (typeof value !== "object" || value === null) return false;
18098
+ try {
18099
+ return verifyEvent(value);
18100
+ } catch {
18101
+ return false;
18058
18102
  }
18059
- return void 0;
18060
18103
  }
18061
- function allTagValues(tags, name) {
18062
- const out = [];
18063
- for (const tag of tags) {
18064
- if (tag[0] === name && typeof tag[1] === "string" && tag[1].length > 0) out.push(tag[1]);
18104
+ function isPajaRelayAllowed(value, getConfiguredRelays) {
18105
+ const normalized = normalizeRelayUrl(value);
18106
+ if (!normalized) return false;
18107
+ if (getConfiguredRelays().some((url2) => normalizeRelayUrl(url2) === normalized)) return true;
18108
+ const url = new URL(normalized);
18109
+ if (url.protocol !== "wss:") return false;
18110
+ const hostname = url.hostname.replace(/^\[|\]$/gu, "").toLowerCase();
18111
+ if (hostname === "localhost" || hostname.endsWith(".localhost") || hostname.endsWith(".local") || hostname.endsWith(".internal") || !hostname.includes(".")) return false;
18112
+ if (hostname.includes(":")) {
18113
+ return hostname !== "::" && hostname !== "::1" && !/^(?:fc|fd|fe[89ab])/iu.test(hostname);
18065
18114
  }
18066
- return out;
18115
+ const octets = hostname.split(".").map(Number);
18116
+ if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) return true;
18117
+ const [first, second] = octets;
18118
+ return first !== 0 && first !== 10 && first !== 127 && first < 224 && !(first === 100 && second >= 64 && second <= 127) && !(first === 169 && second === 254) && !(first === 172 && second >= 16 && second <= 31) && !(first === 192 && second === 168) && !(first === 198 && (second === 18 || second === 19));
18067
18119
  }
18068
- function archetypesFromTags(tags) {
18069
- const out = [];
18070
- for (const tag of tags) {
18071
- if (tag[0] !== "archetype") continue;
18072
- const slug = tag[1];
18073
- if (typeof slug !== "string" || !/^[a-z0-9][a-z0-9-]*$/.test(slug)) {
18074
- throw new NappletResolutionError(
18075
- "invalid-manifest",
18076
- "archetype slug must contain lowercase letters, numbers, and hyphens"
18077
- );
18078
- }
18079
- const convention = tag[2];
18080
- if (typeof convention !== "string" || convention.length === 0) {
18081
- throw new NappletResolutionError("invalid-manifest", "archetype convention is required");
18082
- }
18083
- if (/^NAP-\d+$/.test(convention)) {
18084
- throw new NappletResolutionError(
18085
- "invalid-manifest",
18086
- "numbered NAP identifier is not an archetype convention"
18087
- );
18088
- }
18089
- if (!/^napplet:[^/?#\s]+\/[^/?#\s]+$/.test(convention)) {
18090
- throw new NappletResolutionError(
18091
- "invalid-manifest",
18092
- "archetype convention must be a queryless napplet:<archetype>/<intent> identity"
18093
- );
18094
- }
18095
- if (tag.length !== 3) {
18096
- throw new NappletResolutionError(
18097
- "invalid-manifest",
18098
- "archetype tags must contain exactly slug and convention"
18099
- );
18120
+ function createPajaRelayConfig(getSimulation) {
18121
+ const tierNames = ["discovery", "super", "outbox"];
18122
+ const additions = /* @__PURE__ */ new Map();
18123
+ const removals = /* @__PURE__ */ new Map();
18124
+ const current = { discovery: [], super: [], outbox: [] };
18125
+ const allRelays = [];
18126
+ function isTier(value) {
18127
+ return tierNames.includes(value);
18128
+ }
18129
+ function refresh() {
18130
+ for (const tier of tierNames) {
18131
+ const seen = /* @__PURE__ */ new Set();
18132
+ const values = [];
18133
+ const removed = removals.get(tier);
18134
+ for (const url of [...getPajaRelayUrls(getSimulation()), ...additions.get(tier)?.values() ?? []]) {
18135
+ const normalized = normalizeRelayUrl(url);
18136
+ if (!normalized || seen.has(normalized) || removed?.has(normalized)) continue;
18137
+ seen.add(normalized);
18138
+ values.push(url);
18139
+ }
18140
+ current[tier].splice(0, current[tier].length, ...values);
18100
18141
  }
18101
- out.push({ slug, convention });
18142
+ const combined = [...new Set(tierNames.flatMap((tier) => current[tier]))];
18143
+ allRelays.splice(0, allRelays.length, ...combined);
18102
18144
  }
18103
- return out;
18145
+ const runtime = {
18146
+ allRelays,
18147
+ outboxRelays: current.outbox,
18148
+ addRelay(tier, url) {
18149
+ const normalized = normalizeRelayUrl(url);
18150
+ if (!isTier(tier) || !normalized) return;
18151
+ const entries = additions.get(tier) ?? /* @__PURE__ */ new Map();
18152
+ entries.set(normalized, url);
18153
+ additions.set(tier, entries);
18154
+ removals.get(tier)?.delete(normalized);
18155
+ refresh();
18156
+ },
18157
+ removeRelay(tier, url) {
18158
+ const normalized = normalizeRelayUrl(url);
18159
+ if (!isTier(tier) || !normalized) return;
18160
+ additions.get(tier)?.delete(normalized);
18161
+ const entries = removals.get(tier) ?? /* @__PURE__ */ new Set();
18162
+ entries.add(normalized);
18163
+ removals.set(tier, entries);
18164
+ refresh();
18165
+ },
18166
+ getRelayConfig() {
18167
+ refresh();
18168
+ return {
18169
+ discovery: [...current.discovery],
18170
+ super: [...current.super],
18171
+ outbox: [...current.outbox]
18172
+ };
18173
+ },
18174
+ getNip66Suggestions: () => [],
18175
+ getRelayUrls(tiers = tierNames) {
18176
+ refresh();
18177
+ return [...new Set(tiers.flatMap((tier) => current[tier]))];
18178
+ }
18179
+ };
18180
+ refresh();
18181
+ return runtime;
18104
18182
  }
18105
- function parseNappletManifest(event) {
18106
- if (!isNappletManifestKind(event.kind)) {
18107
- throw new NappletResolutionError("invalid-manifest", `not a NIP-5D napplet kind: ${event.kind}`);
18108
- }
18109
- const paths = pathEntriesFromTags(event.tags);
18110
- if (paths.length === 0) {
18111
- throw new NappletResolutionError("invalid-manifest", "manifest has no path tags");
18112
- }
18113
- const aggregateHash = aggregateTagValue(event.tags);
18114
- if (!aggregateHash) {
18115
- throw new NappletResolutionError("invalid-manifest", "manifest has no aggregate x tag");
18116
- }
18117
- const dTag = firstTagValue(event.tags, "d");
18118
- if (event.kind !== NAPPLET_KIND_NAMED && dTag !== void 0) {
18119
- throw new NappletResolutionError("invalid-manifest", "only named manifests may carry a d tag");
18183
+ function createPajaRelayHooks(pool, getSimulation, relayConfig) {
18184
+ const cleanups = /* @__PURE__ */ new Map();
18185
+ const scoped = /* @__PURE__ */ new Map();
18186
+ function closeScopedRelay(windowId) {
18187
+ scoped.get(windowId)?.unsubscribe();
18188
+ scoped.delete(windowId);
18120
18189
  }
18121
18190
  return {
18122
- kind: event.kind,
18123
- pubkey: event.pubkey,
18124
- dTag: dTag ?? "",
18125
- paths,
18126
- aggregateHash,
18127
- servers: allTagValues(event.tags, "server"),
18128
- requires: allTagValues(event.tags, "requires"),
18129
- archetypes: archetypesFromTags(event.tags),
18130
- title: firstTagValue(event.tags, "title"),
18131
- description: firstTagValue(event.tags, "description"),
18132
- source: firstTagValue(event.tags, "source")
18191
+ getRelayPool: () => pool,
18192
+ trackSubscription(subKey, cleanup) {
18193
+ cleanups.set(subKey, cleanup);
18194
+ },
18195
+ untrackSubscription(subKey) {
18196
+ cleanups.get(subKey)?.();
18197
+ cleanups.delete(subKey);
18198
+ },
18199
+ openScopedRelay(windowId, relayUrl2, subId, filters, sourceWindow) {
18200
+ closeScopedRelay(windowId);
18201
+ const configured = new Map(relayConfig.getRelayUrls().flatMap((url) => {
18202
+ const normalized = normalizeRelayUrl(url);
18203
+ return normalized ? [[normalized, url]] : [];
18204
+ }));
18205
+ const requested = normalizeRelayUrl(relayUrl2);
18206
+ const allowedUrl = requested && isPajaRelayAllowed(relayUrl2, () => relayConfig.getRelayUrls()) ? configured.get(requested) ?? requested : void 0;
18207
+ if (getSimulation().relay.mode !== "live" || !allowedUrl) {
18208
+ sourceWindow.postMessage({ type: "relay.closed", subId, reason: "scoped relay unavailable" }, "*");
18209
+ return;
18210
+ }
18211
+ const subscription = pool.subscription([allowedUrl], filters).subscribe((item) => {
18212
+ if (item === "EOSE") {
18213
+ sourceWindow.postMessage({ type: "relay.eose", subId }, "*");
18214
+ return;
18215
+ }
18216
+ if (!isVerifiedNostrEvent(item)) return;
18217
+ sourceWindow.postMessage({
18218
+ type: "relay.event",
18219
+ subId,
18220
+ result: { event: item, sidecar: { relayHints: [allowedUrl] } }
18221
+ }, "*");
18222
+ });
18223
+ scoped.set(windowId, { relayUrl: allowedUrl, unsubscribe: () => subscription.unsubscribe() });
18224
+ },
18225
+ closeScopedRelay,
18226
+ publishToScopedRelay: async (windowId, event) => {
18227
+ const active = scoped.get(windowId);
18228
+ if (getSimulation().relay.mode !== "live" || !active || !verifyEvent(event)) return false;
18229
+ try {
18230
+ await pool.publish([active.relayUrl], event);
18231
+ return true;
18232
+ } catch {
18233
+ return false;
18234
+ }
18235
+ },
18236
+ selectRelayTier: () => relayConfig.getRelayUrls(["discovery", "super"])
18133
18237
  };
18134
18238
  }
18135
- function verifyManifestSignature(event) {
18239
+ function hasWritableLocalStorage() {
18240
+ if (typeof localStorage === "undefined") return false;
18241
+ let previous = null;
18136
18242
  try {
18137
- return verifyEvent(event);
18243
+ previous = localStorage.getItem(PAJA_STORAGE_PROBE_KEY);
18244
+ localStorage.setItem(PAJA_STORAGE_PROBE_KEY, "1");
18245
+ const available = localStorage.getItem(PAJA_STORAGE_PROBE_KEY) === "1";
18246
+ if (previous === null) localStorage.removeItem(PAJA_STORAGE_PROBE_KEY);
18247
+ else localStorage.setItem(PAJA_STORAGE_PROBE_KEY, previous);
18248
+ return available;
18138
18249
  } catch {
18250
+ try {
18251
+ if (previous === null) localStorage.removeItem(PAJA_STORAGE_PROBE_KEY);
18252
+ else localStorage.setItem(PAJA_STORAGE_PROBE_KEY, previous);
18253
+ } catch {
18254
+ }
18139
18255
  return false;
18140
18256
  }
18141
18257
  }
18142
- function verifyBlobHash(bytes, sha256Hex) {
18143
- return bytesToHex2(sha256(bytes)) === sha256Hex;
18144
- }
18145
- function stripTrailingSlash(url) {
18146
- return url.endsWith("/") ? url.slice(0, -1) : url;
18147
- }
18148
- async function fetchBlob(servers, sha256Hex, fetchBytes) {
18149
- for (const server of servers) {
18150
- const url = `${stripTrailingSlash(server)}/${sha256Hex}`;
18258
+
18259
+ // src/browser-common.ts
18260
+ var HEX_642 = /^[0-9a-f]{64}$/i;
18261
+ var SHORTCODE = /^:[a-zA-Z0-9_+-]+:$/;
18262
+ function relayUrls(values) {
18263
+ const urls = /* @__PURE__ */ new Set();
18264
+ for (const value of values) {
18151
18265
  try {
18152
- const bytes = await fetchBytes(url);
18153
- if (verifyBlobHash(bytes, sha256Hex)) return bytes;
18266
+ const url = new URL(value);
18267
+ if (url.protocol === "wss:" || url.protocol === "ws:") urls.add(url.href);
18154
18268
  } catch {
18155
18269
  }
18156
18270
  }
18157
- throw new NappletResolutionError("blob-unavailable", `no server served blob ${sha256Hex}`);
18158
- }
18159
- var INDEX_PATHS = ["/index.html", "index.html", "/"];
18160
- function defaultDecode(bytes) {
18161
- return new TextDecoder().decode(bytes);
18271
+ return [...urls];
18162
18272
  }
18163
- async function resolveNapplet(options) {
18164
- const { event, fetchBlob: fetchBlobBytes, textDecode = defaultDecode, cache: cache2 } = options;
18165
- if (!verifyManifestSignature(event)) {
18166
- throw new NappletResolutionError("invalid-signature", "manifest signature is invalid");
18167
- }
18168
- const manifest = parseNappletManifest(event);
18169
- const recomputed = computeAggregateHash(manifest.paths);
18170
- if (recomputed !== manifest.aggregateHash) {
18171
- throw new NappletResolutionError(
18172
- "aggregate-mismatch",
18173
- `recomputed aggregate ${recomputed} != manifest ${manifest.aggregateHash}`
18174
- );
18175
- }
18176
- const files = /* @__PURE__ */ new Map();
18177
- for (const entry of manifest.paths) {
18178
- let bytes = await cache2?.readBlob(entry.sha256);
18179
- if (bytes && !verifyBlobHash(bytes, entry.sha256)) {
18180
- await cache2?.deleteBlob(entry.sha256);
18181
- bytes = void 0;
18273
+ function profileTarget(target, defaults) {
18274
+ if (HEX_642.test(target)) return { pubkey: target.toLowerCase(), relays: relayUrls(defaults) };
18275
+ try {
18276
+ const decoded = decode(target);
18277
+ if (decoded.type === "npub") {
18278
+ return { pubkey: decoded.data.toLowerCase(), relays: relayUrls(defaults) };
18182
18279
  }
18183
- bytes ??= await fetchBlobBytes(entry.sha256, manifest.servers);
18184
- if (!verifyBlobHash(bytes, entry.sha256)) {
18185
- throw new NappletResolutionError(
18186
- "blob-hash-mismatch",
18187
- `blob for ${entry.path} does not match hash ${entry.sha256}`
18188
- );
18280
+ if (decoded.type === "nprofile") {
18281
+ return {
18282
+ pubkey: decoded.data.pubkey.toLowerCase(),
18283
+ relays: relayUrls([
18284
+ ...(decoded.data.relays ?? []).filter((relay) => isPajaRelayAllowed(relay, () => defaults)),
18285
+ ...defaults
18286
+ ])
18287
+ };
18189
18288
  }
18190
- files.set(entry.path, bytes);
18289
+ } catch {
18290
+ return null;
18191
18291
  }
18192
- const indexEntry = manifest.paths.find((e) => INDEX_PATHS.includes(e.path));
18193
- if (!indexEntry) {
18194
- throw new NappletResolutionError("missing-index", "manifest has no /index.html entry");
18292
+ return null;
18293
+ }
18294
+ function npub(value) {
18295
+ try {
18296
+ const decoded = decode(value);
18297
+ return decoded.type === "npub" ? decoded.data.toLowerCase() : null;
18298
+ } catch {
18299
+ return null;
18195
18300
  }
18196
- const indexHtml = textDecode(files.get(indexEntry.path));
18197
- await cache2?.writeVerifiedResolution({ event, manifest, files, indexHtml });
18198
- return {
18199
- dTag: manifest.dTag,
18200
- aggregateHash: manifest.aggregateHash,
18201
- files,
18202
- indexHtml,
18203
- manifest
18204
- };
18205
18301
  }
18206
-
18207
- // src/browser-resource.ts
18208
- var PAJA_RESOURCE_MAX_BYTES = 10 * 1024 * 1024;
18209
- var PAJA_RESOURCE_MAX_URLS = 100;
18210
- var PAJA_RESOURCE_MAX_SERVERS = 8;
18211
- var UTF8_DECODER = new TextDecoder("utf-8", { fatal: true });
18212
- var BLOSSOM_RESOURCE_PATTERN = /^blossom:sha256:([0-9a-f]{64})$/i;
18213
- function createPajaResourceFetch(options = {}) {
18214
- return async (value, init) => {
18215
- if (init.signal.aborted) throw new DOMException("Resource request cancelled", "AbortError");
18216
- const url = new URL(value);
18217
- if (init.method && init.method.toUpperCase() !== "GET") {
18218
- throw new ResourceServiceError("invalid-request", "NAP-RESOURCE is read-only");
18219
- }
18220
- if (url.protocol === "blossom:") {
18221
- return fetchBlossomResource(value, init.signal, init.servers ?? [], options);
18222
- }
18223
- if (url.protocol === "http:" || url.protocol === "https:") {
18224
- return fetchNetworkResource(value, init.signal, options.fetch ?? globalThis.fetch);
18225
- }
18226
- if (url.protocol !== "data:") {
18227
- throw new ResourceServiceError("unsupported-scheme", `Paja does not enable ${url.protocol}`);
18228
- }
18229
- if (value.length > encodedDataUrlLimit(PAJA_RESOURCE_MAX_BYTES)) {
18230
- throw new ResourceServiceError("too-large", `resource exceeds ${PAJA_RESOURCE_MAX_BYTES} bytes`);
18231
- }
18232
- const decoded = await fetch(value, { signal: init.signal });
18233
- const bytes = new Uint8Array(await decoded.arrayBuffer());
18234
- if (bytes.byteLength > PAJA_RESOURCE_MAX_BYTES) {
18235
- throw new ResourceServiceError("too-large", `resource exceeds ${PAJA_RESOURCE_MAX_BYTES} bytes`);
18236
- }
18237
- const mime = sniffSafeResourceMime(bytes);
18238
- if (!mime) {
18239
- throw new ResourceServiceError("decode-failed", "resource bytes are not an enabled safe media type");
18240
- }
18241
- return new Response(arrayBufferFor(bytes), { headers: { "content-type": mime } });
18242
- };
18302
+ function pubkey(value) {
18303
+ if (HEX_642.test(value)) return value.toLowerCase();
18304
+ return npub(value);
18243
18305
  }
18244
- function pajaResourceInfo() {
18245
- const schemes = [
18246
- { scheme: "data", enabled: true },
18247
- { scheme: "https", enabled: true },
18248
- { scheme: "http", enabled: true },
18249
- { scheme: "blossom", enabled: true }
18250
- ];
18251
- return {
18252
- schemes,
18253
- maxBytes: PAJA_RESOURCE_MAX_BYTES,
18254
- maxUrls: PAJA_RESOURCE_MAX_URLS,
18255
- maxServers: PAJA_RESOURCE_MAX_SERVERS
18256
- };
18306
+ function newestVerified(events, predicate) {
18307
+ return events.filter((event) => predicate(event) && verifyEvent(event)).sort((left, right) => right.created_at - left.created_at || left.id.localeCompare(right.id))[0] ?? null;
18257
18308
  }
18258
- async function fetchNetworkResource(value, signal, fetcher) {
18259
- let response;
18309
+ function parseProfile(event) {
18260
18310
  try {
18261
- response = await fetcher(value, {
18262
- method: "GET",
18263
- signal,
18264
- credentials: "omit",
18265
- referrerPolicy: "no-referrer"
18266
- });
18267
- } catch (error) {
18268
- if (signal.aborted || isAbortError(error)) throw error;
18269
- throw new ResourceServiceError(
18270
- "network-error",
18271
- error instanceof Error ? error.message : String(error)
18272
- );
18273
- }
18274
- if (response.status === 404 || response.status === 410) {
18275
- throw new ResourceServiceError("not-found", "HTTP resource was not found");
18276
- }
18277
- if (!response.ok) {
18278
- throw new ResourceServiceError("network-error", `HTTP resource returned ${response.status}`);
18279
- }
18280
- const bytes = await readCappedResponse(response, signal);
18281
- const mime = sniffSafeResourceMime(bytes);
18282
- if (!mime) {
18283
- throw new ResourceServiceError("decode-failed", "resource bytes are not an enabled safe media type");
18311
+ const parsed = JSON.parse(event.content);
18312
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
18313
+ const profile = { ...parsed };
18314
+ if (typeof profile.display_name === "string" && typeof profile.displayName !== "string") {
18315
+ profile.displayName = profile.display_name;
18316
+ }
18317
+ return profile;
18318
+ } catch {
18319
+ return null;
18284
18320
  }
18285
- return new Response(arrayBufferFor(bytes), { headers: { "content-type": mime } });
18286
18321
  }
18287
- async function fetchBlossomResource(value, signal, requestServers, options) {
18288
- const match = BLOSSOM_RESOURCE_PATTERN.exec(value);
18289
- if (!match?.[1]) {
18290
- throw new ResourceServiceError("invalid-request", "expected blossom:sha256:<64 hex characters>");
18322
+ function contactPubkeys2(event) {
18323
+ const follows = /* @__PURE__ */ new Set();
18324
+ for (const tag of event?.tags ?? []) {
18325
+ if (tag[0] === "p" && typeof tag[1] === "string" && HEX_642.test(tag[1])) {
18326
+ follows.add(tag[1].toLowerCase());
18327
+ }
18291
18328
  }
18292
- const expectedHash = match[1].toLowerCase();
18293
- const servers = resolveBlossomServers(
18294
- requestServers,
18295
- options.getBlossomServers?.() ?? []
18296
- );
18297
- if (servers.length === 0) {
18298
- throw new ResourceServiceError("blocked-by-policy", "Paja has no accepted Blossom server");
18329
+ return [...follows];
18330
+ }
18331
+ function actionError(error) {
18332
+ const message = error instanceof Error ? error.message : String(error);
18333
+ if (message.includes("denied")) return { ok: false, error: "user-denied" };
18334
+ if (message.includes("publish")) return { ok: false, error: "publish-failed" };
18335
+ return { ok: false, error: message };
18336
+ }
18337
+ function isSingleEmoji(value) {
18338
+ const graphemes = [...new Intl.Segmenter(void 0, { granularity: "grapheme" }).segment(value)];
18339
+ return graphemes.length === 1 && /[\p{Extended_Pictographic}\p{Regional_Indicator}]/u.test(value);
18340
+ }
18341
+ function reactionTags(target, reaction, customEmojiHref) {
18342
+ if (reaction !== "+" && reaction !== "-" && !isSingleEmoji(reaction) && !SHORTCODE.test(reaction)) return null;
18343
+ if (customEmojiHref && !SHORTCODE.test(reaction)) return null;
18344
+ if (SHORTCODE.test(reaction) && !customEmojiHref) return null;
18345
+ const tags = [["e", target.id], ["p", target.pubkey], ["k", String(target.kind)]];
18346
+ if (customEmojiHref) {
18347
+ let url;
18348
+ try {
18349
+ url = new URL(customEmojiHref);
18350
+ } catch {
18351
+ return null;
18352
+ }
18353
+ if (url.protocol !== "https:" && url.protocol !== "http:") return null;
18354
+ tags.push(["emoji", reaction.slice(1, -1), url.href]);
18299
18355
  }
18300
- const fetcher = options.fetch ?? globalThis.fetch;
18301
- let foundHashMismatch = false;
18302
- let foundNotFound = false;
18303
- let foundInconclusive = false;
18304
- let lastNetworkMessage = "all accepted Blossom servers failed";
18305
- for (const server of servers) {
18306
- if (signal.aborted) throw new DOMException("Resource request cancelled", "AbortError");
18307
- const resourceUrl = `${server}/${expectedHash}`;
18308
- let response;
18356
+ return tags;
18357
+ }
18358
+ function createPajaCommonBackend(options) {
18359
+ const query = (filters, relays = options.getRelays()) => options.relay.query(relays, filters, PAJA_LIVE_QUERY_WAIT_MS);
18360
+ const identity = async () => {
18361
+ const active = options.getSigner();
18362
+ if (!active?.getPublicKey) throw new Error("not-signed-in");
18363
+ const activePubkey = (await active.getPublicKey()).toLowerCase();
18364
+ if (!HEX_642.test(activePubkey)) throw new Error("not-signed-in");
18365
+ return { signer: active, pubkey: activePubkey };
18366
+ };
18367
+ const signer = async () => {
18368
+ const active = await identity();
18369
+ if (!active.signer.signEvent) throw new Error("not-signed-in");
18370
+ return active;
18371
+ };
18372
+ const currentContacts = async (author) => {
18373
+ const events = await query([{ kinds: [3], authors: [author], limit: 16 }]);
18374
+ return newestVerified(events, (event) => event.kind === 3 && event.pubkey.toLowerCase() === author);
18375
+ };
18376
+ const publish = async (active, author, template) => {
18377
+ try {
18378
+ const event = await active.signEvent(template);
18379
+ if (event.pubkey.toLowerCase() !== author || !verifyEvent(event)) return { ok: false, error: "invalid-signature" };
18380
+ await options.relay.publish(options.getRelays(), event);
18381
+ return { ok: true, eventId: event.id, event };
18382
+ } catch (error) {
18383
+ return actionError(error);
18384
+ }
18385
+ };
18386
+ const mutateFollows = async (values, add) => {
18387
+ const targets = values.map(pubkey);
18388
+ if (targets.some((target) => target === null)) return { ok: false, error: "invalid-pubkey" };
18309
18389
  try {
18310
- response = await fetcher(resourceUrl, {
18311
- method: "GET",
18312
- signal,
18313
- redirect: "error",
18314
- cache: "no-store",
18315
- credentials: "omit",
18316
- referrerPolicy: "no-referrer"
18390
+ const active = await signer();
18391
+ const current = await currentContacts(active.pubkey);
18392
+ const targetSet = new Set(targets);
18393
+ const existing = new Set(contactPubkeys2(current));
18394
+ const changed = add ? [...targetSet].some((target) => !existing.has(target)) : [...targetSet].some((target) => existing.has(target));
18395
+ if (!changed) {
18396
+ return current ? { ok: true, eventId: current.id, event: current } : { ok: true };
18397
+ }
18398
+ const tags = (current?.tags ?? []).filter((tag) => {
18399
+ if (tag[0] !== "p" || typeof tag[1] !== "string") return true;
18400
+ return add || !targetSet.has(tag[1].toLowerCase());
18401
+ });
18402
+ if (add) {
18403
+ for (const target of targetSet) {
18404
+ if (!existing.has(target)) tags.push(["p", target]);
18405
+ }
18406
+ }
18407
+ return publish(active.signer, active.pubkey, {
18408
+ kind: 3,
18409
+ created_at: Math.floor(Date.now() / 1e3),
18410
+ tags,
18411
+ content: current?.content ?? ""
18317
18412
  });
18318
18413
  } catch (error) {
18319
- if (signal.aborted || isAbortError(error)) throw error;
18320
- foundInconclusive = true;
18321
- lastNetworkMessage = error instanceof Error ? error.message : String(error);
18322
- continue;
18323
- }
18324
- if (response.status === 404 || response.status === 410) {
18325
- foundNotFound = true;
18326
- continue;
18327
- }
18328
- if (!response.ok) {
18329
- foundInconclusive = true;
18330
- lastNetworkMessage = `Blossom server returned HTTP ${response.status}`;
18331
- continue;
18332
- }
18333
- const bytes = await readCappedResponse(response, signal);
18334
- if (!verifyBlobHash(bytes, expectedHash)) {
18335
- foundHashMismatch = true;
18336
- continue;
18414
+ return actionError(error);
18337
18415
  }
18338
- const mime = sniffSafeResourceMime(bytes);
18339
- if (!mime) {
18340
- throw new ResourceServiceError("decode-failed", "resource bytes are not an enabled safe media type");
18416
+ };
18417
+ return {
18418
+ async getProfile(target) {
18419
+ const resolved = profileTarget(target, options.getRelays());
18420
+ if (!resolved) return { ok: false, pubkey: "", error: "invalid-profile-target" };
18421
+ try {
18422
+ const events = await query([{ kinds: [0], authors: [resolved.pubkey], limit: 16 }], resolved.relays);
18423
+ const event = newestVerified(events, (candidate) => candidate.kind === 0 && candidate.pubkey.toLowerCase() === resolved.pubkey);
18424
+ if (!event) return { ok: true, pubkey: resolved.pubkey, profile: null };
18425
+ return {
18426
+ ok: true,
18427
+ pubkey: resolved.pubkey,
18428
+ profile: parseProfile(event),
18429
+ result: { event, sidecar: { relayHints: resolved.relays } }
18430
+ };
18431
+ } catch {
18432
+ return { ok: false, pubkey: resolved.pubkey, error: "relay-timeout" };
18433
+ }
18434
+ },
18435
+ async follows() {
18436
+ try {
18437
+ const active = await identity();
18438
+ return { ok: true, pubkeys: contactPubkeys2(await currentContacts(active.pubkey)) };
18439
+ } catch (error) {
18440
+ const failure3 = actionError(error);
18441
+ return { ok: false, pubkeys: [], error: failure3.error };
18442
+ }
18443
+ },
18444
+ follow: (pubkeys) => mutateFollows(pubkeys, true),
18445
+ unfollow: (pubkeys) => mutateFollows(pubkeys, false),
18446
+ async react(targetEventId, reaction, customEmojiHref) {
18447
+ if (!HEX_642.test(targetEventId)) return { ok: false, error: "invalid-target" };
18448
+ try {
18449
+ const active = await signer();
18450
+ const events = await query([{ ids: [targetEventId], limit: 8 }]);
18451
+ const target = newestVerified(events, (event) => event.id === targetEventId.toLowerCase());
18452
+ if (!target) return { ok: false, error: "invalid-target" };
18453
+ const tags = reactionTags(target, reaction, customEmojiHref);
18454
+ if (!tags) return { ok: false, error: "invalid-reaction" };
18455
+ return publish(active.signer, active.pubkey, {
18456
+ kind: 7,
18457
+ created_at: Math.floor(Date.now() / 1e3),
18458
+ tags,
18459
+ content: reaction
18460
+ });
18461
+ } catch (error) {
18462
+ return actionError(error);
18463
+ }
18464
+ },
18465
+ async report(target, reason, text) {
18466
+ try {
18467
+ const active = await signer();
18468
+ if (target.type === "pubkey") {
18469
+ const reportedPubkey = pubkey(target.pubkey);
18470
+ if (!reportedPubkey) return { ok: false, error: "invalid-target" };
18471
+ return publish(active.signer, active.pubkey, {
18472
+ kind: 1984,
18473
+ created_at: Math.floor(Date.now() / 1e3),
18474
+ tags: [["p", reportedPubkey, target.relay ?? "", reason]],
18475
+ content: text
18476
+ });
18477
+ }
18478
+ if (!HEX_642.test(target.id)) return { ok: false, error: "invalid-target" };
18479
+ const explicitAuthor = target.pubkey ? pubkey(target.pubkey) : void 0;
18480
+ if (target.pubkey && !explicitAuthor) return { ok: false, error: "invalid-target" };
18481
+ let author = explicitAuthor ?? null;
18482
+ if (!author) {
18483
+ const events = await query([{ ids: [target.id], limit: 8 }]);
18484
+ author = newestVerified(events, (event) => event.id === target.id.toLowerCase())?.pubkey ?? null;
18485
+ }
18486
+ if (!author) return { ok: false, error: "author-unresolved" };
18487
+ return publish(active.signer, active.pubkey, {
18488
+ kind: 1984,
18489
+ created_at: Math.floor(Date.now() / 1e3),
18490
+ tags: [
18491
+ ["e", target.id.toLowerCase(), target.relay ?? "", reason],
18492
+ ["p", author.toLowerCase(), "", reason]
18493
+ ],
18494
+ content: text
18495
+ });
18496
+ } catch (error) {
18497
+ return actionError(error);
18498
+ }
18341
18499
  }
18342
- return new Response(arrayBufferFor(bytes), { headers: { "content-type": mime } });
18343
- }
18344
- if (foundHashMismatch) {
18345
- throw new ResourceServiceError("decode-failed", "Blossom response did not match the requested SHA-256");
18346
- }
18347
- if (foundInconclusive) {
18348
- throw new ResourceServiceError("network-error", lastNetworkMessage);
18349
- }
18350
- if (foundNotFound) {
18351
- throw new ResourceServiceError("not-found", "Blossom resource was not found");
18352
- }
18353
- throw new ResourceServiceError("network-error", lastNetworkMessage);
18500
+ };
18354
18501
  }
18355
- function resolveBlossomServers(requestServers, configuredServers) {
18356
- const servers = [];
18357
- for (const value of requestServers) {
18358
- const server = normalizePublicBlossomHint(value);
18359
- if (server && !servers.includes(server)) servers.push(server);
18360
- if (servers.length === PAJA_RESOURCE_MAX_SERVERS) return servers;
18361
- }
18362
- for (const server of usableBlossomServers(configuredServers)) {
18363
- if (!servers.includes(server)) servers.push(server);
18364
- if (servers.length === PAJA_RESOURCE_MAX_SERVERS) break;
18502
+
18503
+ // src/browser-lists.ts
18504
+ var HEX_643 = /^[0-9a-f]{64}$/i;
18505
+ var ADDRESS = /^\d+:[0-9a-f]{64}:.+$/i;
18506
+ var SUPPORTED_LISTS = [
18507
+ {
18508
+ kind: 1e4,
18509
+ type: "mute-list",
18510
+ addressable: false,
18511
+ supportedItemTypes: ["pubkey", "event", "hashtag", "word"],
18512
+ privateItems: false,
18513
+ tagByItemType: { pubkey: "p", event: "e", hashtag: "t", word: "word" }
18514
+ },
18515
+ {
18516
+ kind: 10002,
18517
+ type: "relay-list-metadata",
18518
+ addressable: false,
18519
+ supportedItemTypes: ["relay"],
18520
+ privateItems: false,
18521
+ tagByItemType: { relay: "r" }
18522
+ },
18523
+ {
18524
+ kind: 10003,
18525
+ type: "bookmarks",
18526
+ addressable: false,
18527
+ supportedItemTypes: ["event", "address"],
18528
+ privateItems: false,
18529
+ tagByItemType: { event: "e", address: "a" }
18530
+ },
18531
+ {
18532
+ kind: 3e4,
18533
+ type: "follow-sets",
18534
+ addressable: true,
18535
+ supportedItemTypes: ["pubkey"],
18536
+ privateItems: false,
18537
+ tagByItemType: { pubkey: "p" }
18365
18538
  }
18366
- return servers;
18539
+ ];
18540
+ function publicSupport() {
18541
+ return SUPPORTED_LISTS.map(({ tagByItemType: _tagByItemType, ...support }) => ({
18542
+ ...support,
18543
+ supportedItemTypes: support.supportedItemTypes ? [...support.supportedItemTypes] : void 0
18544
+ }));
18367
18545
  }
18368
- function normalizePublicBlossomHint(value) {
18369
- if (typeof value !== "string" || value.trim().length === 0) return null;
18546
+ function failure2(error, reason) {
18547
+ return { ok: false, error, reason, supported: publicSupport() };
18548
+ }
18549
+ function resolveList(ref) {
18550
+ const input = ref;
18551
+ const hasKind = typeof input.kind === "number";
18552
+ const hasType = typeof input.type === "string" && input.type.length > 0;
18553
+ if (hasKind === hasType) return failure2("invalid-list-ref", "exactly one list kind or type is required");
18554
+ const candidates = hasKind ? SUPPORTED_LISTS.filter((support2) => support2.kind === input.kind) : SUPPORTED_LISTS.filter((support2) => support2.type === input.type);
18555
+ if (candidates.length === 0) return failure2("unsupported-list", "list kind or type is not supported");
18556
+ if (candidates.length > 1) return failure2("ambiguous-list", "list type maps to multiple supported kinds");
18557
+ const support = candidates[0];
18558
+ const identifier = typeof input.identifier === "string" && input.identifier.length > 0 ? input.identifier : void 0;
18559
+ if (support.addressable && !identifier) return failure2("missing-identifier", "addressable lists require an identifier");
18560
+ if (!support.addressable && identifier) return failure2("invalid-list-ref", "replaceable list does not accept an identifier");
18561
+ return { support, ...identifier ? { identifier } : {} };
18562
+ }
18563
+ function relayUrl(value) {
18370
18564
  try {
18371
- const url = new URL(value.trim());
18372
- if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash || url.pathname !== "/" || !isPublicHostname(url.hostname)) return null;
18373
- return url.origin;
18565
+ const parsed = new URL(value);
18566
+ return parsed.protocol === "ws:" || parsed.protocol === "wss:" ? parsed.href : null;
18374
18567
  } catch {
18375
18568
  return null;
18376
18569
  }
18377
18570
  }
18378
- function isPublicHostname(value) {
18379
- const hostname = value.replace(/^\[|\]$/gu, "").toLowerCase();
18380
- if (hostname === "localhost" || hostname.endsWith(".localhost") || hostname.endsWith(".local") || hostname.endsWith(".internal") || !hostname.includes(".")) return false;
18381
- if (hostname.includes(":")) {
18382
- return hostname !== "::" && hostname !== "::1" && !hostname.startsWith("::ffff:") && !/^(?:fc|fd|fe[89ab]|ff)/iu.test(hostname) && !hostname.startsWith("2001:db8:");
18383
- }
18384
- const octets = hostname.split(".").map(Number);
18385
- if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) return true;
18386
- const [first, second] = octets;
18387
- return first !== 0 && first !== 10 && first !== 127 && first < 224 && !(first === 100 && second >= 64 && second <= 127) && !(first === 169 && second === 254) && !(first === 172 && second >= 16 && second <= 31) && !(first === 192 && second === 168) && !(first === 198 && (second === 18 || second === 19));
18388
- }
18389
- function usableBlossomServers(values) {
18390
- const servers = [];
18391
- for (const value of values) {
18392
- try {
18393
- const [server] = normalizeUploadServers([value]);
18394
- if (server && !servers.includes(server)) servers.push(server);
18395
- } catch {
18396
- }
18397
- }
18398
- return servers;
18399
- }
18400
- async function readCappedResponse(response, signal) {
18401
- const declaredLength = Number(response.headers.get("content-length"));
18402
- if (Number.isFinite(declaredLength) && declaredLength > PAJA_RESOURCE_MAX_BYTES) {
18403
- throw resourceTooLarge();
18571
+ function itemTag(support, item) {
18572
+ if (item.visibility === "private") return failure2("private-items-unsupported", "private list items require NIP-44 support");
18573
+ const tagName = support.tagByItemType[item.itemType];
18574
+ if (!tagName) return failure2("unsupported-item", `${item.itemType} is not supported by ${support.type}`);
18575
+ const value = item.value.trim();
18576
+ if (!value) return failure2("invalid-item", "list item value is empty");
18577
+ if ((item.itemType === "pubkey" || item.itemType === "event") && !HEX_643.test(value)) {
18578
+ return failure2("invalid-item", `${item.itemType} values must be 32-byte hex`);
18404
18579
  }
18405
- if (!response.body) {
18406
- const bytes2 = new Uint8Array(await response.arrayBuffer());
18407
- if (bytes2.byteLength > PAJA_RESOURCE_MAX_BYTES) throw resourceTooLarge();
18408
- return bytes2;
18580
+ if (item.itemType === "address" && !ADDRESS.test(value)) {
18581
+ return failure2("invalid-item", "address values must use kind:pubkey:identifier");
18409
18582
  }
18410
- const reader = response.body.getReader();
18411
- const chunks = [];
18412
- let total = 0;
18413
- try {
18414
- while (true) {
18415
- if (signal.aborted) throw new DOMException("Resource request cancelled", "AbortError");
18416
- const { done, value } = await reader.read();
18417
- if (done) break;
18418
- total += value.byteLength;
18419
- if (total > PAJA_RESOURCE_MAX_BYTES) {
18420
- await reader.cancel();
18421
- throw resourceTooLarge();
18422
- }
18423
- chunks.push(value);
18583
+ if (support.kind === 10002) {
18584
+ const url = relayUrl(value);
18585
+ if (!url) return failure2("invalid-item", "relay list items require ws or wss URLs");
18586
+ const marker = item.marker ?? "read-write";
18587
+ if (marker !== "read" && marker !== "write" && marker !== "read-write") {
18588
+ return failure2("invalid-item", "relay marker must be read, write, or read-write");
18424
18589
  }
18425
- } finally {
18426
- reader.releaseLock();
18427
- }
18428
- const bytes = new Uint8Array(total);
18429
- let offset = 0;
18430
- for (const chunk of chunks) {
18431
- bytes.set(chunk, offset);
18432
- offset += chunk.byteLength;
18590
+ return marker === "read-write" ? ["r", url] : ["r", url, marker];
18433
18591
  }
18434
- return bytes;
18592
+ const tag = [tagName, value];
18593
+ if (item.relay) tag.push(item.relay);
18594
+ if (item.label) tag.push(item.label);
18595
+ return tag;
18435
18596
  }
18436
- function resourceTooLarge() {
18437
- return new ResourceServiceError("too-large", `resource exceeds ${PAJA_RESOURCE_MAX_BYTES} bytes`);
18597
+ function isFailure(value) {
18598
+ return !Array.isArray(value);
18438
18599
  }
18439
- function isAbortError(error) {
18440
- return error instanceof Error && (error.name === "AbortError" || error.name === "DOMException");
18600
+ function sameItem(tag, expected) {
18601
+ if (tag[0] !== expected[0] || tag[1] !== expected[1]) return false;
18602
+ if (expected.length > 2 && tag[2] !== expected[2]) return false;
18603
+ if (expected.length > 3 && tag[3] !== expected[3]) return false;
18604
+ return true;
18441
18605
  }
18442
- function arrayBufferFor(bytes) {
18443
- return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
18606
+ function relayCoverage(tag) {
18607
+ if (tag[2] === "read") return /* @__PURE__ */ new Set(["read"]);
18608
+ if (tag[2] === "write") return /* @__PURE__ */ new Set(["write"]);
18609
+ return /* @__PURE__ */ new Set(["read", "write"]);
18444
18610
  }
18445
- function encodedDataUrlLimit(maxBytes) {
18446
- return Math.ceil(maxBytes * 4 / 3) + 1024;
18611
+ function relayTag(url, coverage) {
18612
+ if (coverage.size === 0) return null;
18613
+ if (coverage.size === 2) return ["r", url];
18614
+ return ["r", url, coverage.has("read") ? "read" : "write"];
18447
18615
  }
18448
- function startsWith(bytes, signature, offset = 0) {
18449
- return signature.every((value, index) => bytes[offset + index] === value);
18616
+ function sameRelay(tag, url) {
18617
+ return tag[0] === "r" && typeof tag[1] === "string" && relayUrl(tag[1]) === url;
18450
18618
  }
18451
- function ascii(bytes, start, end) {
18452
- return String.fromCharCode(...bytes.subarray(start, end));
18619
+ function addRelayItem(tags, expected) {
18620
+ const url = expected[1];
18621
+ const matching = tags.filter((tag) => sameRelay(tag, url));
18622
+ const coverage = /* @__PURE__ */ new Set();
18623
+ for (const tag of matching) for (const direction of relayCoverage(tag)) coverage.add(direction);
18624
+ const requested = relayCoverage(expected);
18625
+ const before = coverage.size;
18626
+ for (const direction of requested) coverage.add(direction);
18627
+ if (coverage.size === before) return { tags, changed: false };
18628
+ const retained = tags.filter((tag) => !sameRelay(tag, url));
18629
+ retained.push(relayTag(url, coverage));
18630
+ return { tags: retained, changed: true };
18453
18631
  }
18454
- function sniffSafeResourceMime(bytes) {
18455
- if (startsWith(bytes, [137, 80, 78, 71, 13, 10, 26, 10])) return "image/png";
18456
- if (startsWith(bytes, [255, 216, 255])) return "image/jpeg";
18457
- if (ascii(bytes, 0, 6) === "GIF87a" || ascii(bytes, 0, 6) === "GIF89a") return "image/gif";
18458
- if (ascii(bytes, 0, 4) === "RIFF" && ascii(bytes, 8, 12) === "WEBP") return "image/webp";
18459
- if (ascii(bytes, 0, 4) === "RIFF" && ascii(bytes, 8, 12) === "WAVE") return "audio/wav";
18460
- if (ascii(bytes, 0, 4) === "OggS") return "audio/ogg";
18461
- if (ascii(bytes, 0, 3) === "ID3" || startsWith(bytes, [255, 251])) return "audio/mpeg";
18462
- if (startsWith(bytes, [26, 69, 223, 163])) return "video/webm";
18463
- if (ascii(bytes, 4, 8) === "ftyp") return "video/mp4";
18464
- if (ascii(bytes, 0, 4) === "wOFF") return "font/woff";
18465
- if (ascii(bytes, 0, 4) === "wOF2") return "font/woff2";
18466
- return sniffSafeTextMime(bytes);
18632
+ function removeRelayItem(tags, expected) {
18633
+ const url = expected[1];
18634
+ const matching = tags.filter((tag) => sameRelay(tag, url));
18635
+ if (matching.length === 0) return { tags, changed: false };
18636
+ const retained = tags.filter((tag) => !sameRelay(tag, url));
18637
+ if (expected.length === 2) return { tags: retained, changed: true };
18638
+ const coverage = /* @__PURE__ */ new Set();
18639
+ for (const tag of matching) for (const direction of relayCoverage(tag)) coverage.add(direction);
18640
+ coverage.delete(expected[2]);
18641
+ const rewritten = relayTag(url, coverage);
18642
+ if (rewritten) retained.push(rewritten);
18643
+ return { tags: retained, changed: true };
18467
18644
  }
18468
- function sniffSafeTextMime(bytes) {
18469
- let text;
18470
- try {
18471
- text = UTF8_DECODER.decode(bytes);
18472
- } catch {
18473
- return null;
18474
- }
18475
- if (/\u0000/u.test(text)) return null;
18476
- const normalized = text.trimStart().toLowerCase();
18477
- if (normalized.startsWith("<svg") || normalized.startsWith("<?xml") || normalized.startsWith("<!doctype html") || normalized.startsWith("<html") || normalized.startsWith("<script")) return null;
18478
- if (normalized.startsWith("{") || normalized.startsWith("[")) {
18645
+ function metadataTags(resolved, options) {
18646
+ const tags = [];
18647
+ if (resolved.identifier) tags.push(["d", resolved.identifier]);
18648
+ if (options?.title) tags.push(["title", options.title]);
18649
+ if (options?.description) tags.push(["description", options.description]);
18650
+ if (options?.image) tags.push(["image", options.image]);
18651
+ return tags;
18652
+ }
18653
+ function listFilter(resolved, author) {
18654
+ return {
18655
+ kinds: [resolved.support.kind],
18656
+ authors: [author],
18657
+ limit: 16,
18658
+ ...resolved.identifier ? { ["#d"]: [resolved.identifier] } : {}
18659
+ };
18660
+ }
18661
+ function newestList(events, resolved, author) {
18662
+ return events.filter((event) => event.kind === resolved.support.kind && event.pubkey.toLowerCase() === author && (!resolved.identifier || event.tags.some((tag) => tag[0] === "d" && tag[1] === resolved.identifier)) && verifyEvent(event)).sort((left, right) => right.created_at - left.created_at || left.id.localeCompare(right.id))[0] ?? null;
18663
+ }
18664
+ function createPajaListsBackend(options) {
18665
+ const activeSigner = async () => {
18666
+ const signer = options.getSigner();
18667
+ if (!signer?.getPublicKey || !signer.signEvent) throw new Error("not-signed-in");
18668
+ const pubkey2 = (await signer.getPublicKey()).toLowerCase();
18669
+ if (!HEX_643.test(pubkey2)) throw new Error("not-signed-in");
18670
+ return { signer, pubkey: pubkey2 };
18671
+ };
18672
+ const mutation = async (operation, ref, items, mutationOptions) => {
18673
+ const resolved = resolveList(ref);
18674
+ if ("ok" in resolved) return resolved;
18675
+ if (items.length === 0) return { ok: true, [operation === "add" ? "added" : "removed"]: 0, skipped: 0 };
18676
+ const itemTags = [];
18677
+ for (const item of items) {
18678
+ const tag = itemTag(resolved.support, item);
18679
+ if (isFailure(tag)) return tag;
18680
+ itemTags.push(tag);
18681
+ }
18682
+ let active;
18479
18683
  try {
18480
- JSON.parse(text);
18481
- return "application/json";
18684
+ active = await activeSigner();
18482
18685
  } catch {
18483
- return "text/plain";
18686
+ return failure2("not-signed-in", "list mutations require an active signer");
18484
18687
  }
18485
- }
18486
- return "text/plain";
18688
+ let current;
18689
+ try {
18690
+ const events = await options.relay.query(
18691
+ options.getRelays(),
18692
+ [listFilter(resolved, active.pubkey)],
18693
+ PAJA_LIVE_QUERY_WAIT_MS
18694
+ );
18695
+ current = newestList(events, resolved, active.pubkey);
18696
+ } catch {
18697
+ return failure2("list-unavailable", "current list could not be loaded");
18698
+ }
18699
+ if (!current && !(operation === "add" && mutationOptions?.create)) {
18700
+ return failure2("list-not-found", "list does not exist and creation was not requested");
18701
+ }
18702
+ if (operation === "remove" && current?.content && items.some((item) => item.visibility !== "public")) {
18703
+ return failure2("private-items-unsupported", "cannot safely remove private items without NIP-44 support");
18704
+ }
18705
+ let tags = current ? current.tags.map((tag) => [...tag]) : metadataTags(resolved, mutationOptions);
18706
+ let changed = 0;
18707
+ for (const expected of itemTags) {
18708
+ if (resolved.support.kind === 10002) {
18709
+ const result2 = operation === "add" ? addRelayItem(tags, expected) : removeRelayItem(tags, expected);
18710
+ tags = result2.tags;
18711
+ if (result2.changed) changed += 1;
18712
+ continue;
18713
+ }
18714
+ if (operation === "add") {
18715
+ if (!tags.some((tag) => sameItem(tag, expected))) {
18716
+ tags.push(expected);
18717
+ changed += 1;
18718
+ }
18719
+ } else {
18720
+ const before = tags.length;
18721
+ tags = tags.filter((tag) => !sameItem(tag, expected));
18722
+ if (tags.length < before) changed += 1;
18723
+ }
18724
+ }
18725
+ const skipped = items.length - changed;
18726
+ if (changed === 0) {
18727
+ return {
18728
+ ok: true,
18729
+ ...current ? { eventId: current.id, event: { ...current } } : {},
18730
+ [operation === "add" ? "added" : "removed"]: 0,
18731
+ skipped
18732
+ };
18733
+ }
18734
+ try {
18735
+ const template = {
18736
+ kind: resolved.support.kind,
18737
+ created_at: Math.floor(Date.now() / 1e3),
18738
+ tags,
18739
+ content: current?.content ?? ""
18740
+ };
18741
+ const event = await active.signer.signEvent(template);
18742
+ if (event.pubkey.toLowerCase() !== active.pubkey || !verifyEvent(event)) {
18743
+ return failure2("publish-failed", "signer returned an invalid list event");
18744
+ }
18745
+ await options.relay.publish(options.getRelays(), event);
18746
+ return {
18747
+ ok: true,
18748
+ eventId: event.id,
18749
+ event: { ...event },
18750
+ [operation === "add" ? "added" : "removed"]: changed,
18751
+ skipped
18752
+ };
18753
+ } catch (error) {
18754
+ const message = error instanceof Error ? error.message : String(error);
18755
+ return failure2(message.includes("denied") ? "user-denied" : "publish-failed", message);
18756
+ }
18757
+ };
18758
+ return {
18759
+ supported: publicSupport,
18760
+ add: (list, items, mutationOptions) => mutation("add", list, items, mutationOptions),
18761
+ remove: (list, items, mutationOptions) => mutation("remove", list, items, mutationOptions)
18762
+ };
18487
18763
  }
18488
18764
 
18489
18765
  // src/browser-webrtc.ts
@@ -18520,7 +18796,7 @@ var BrowserWebrtcController = class {
18520
18796
  };
18521
18797
  refreshAvailability() {
18522
18798
  const signer = this.options.getSigner();
18523
- const nextPubkey = isSignalingSigner(signer) ? normalizePubkey2(this.options.getPubkey()) : null;
18799
+ const nextPubkey = isSignalingSigner(signer) ? normalizePubkey3(this.options.getPubkey()) : null;
18524
18800
  if (this.activePubkey !== nextPubkey) {
18525
18801
  this.dispose();
18526
18802
  this.activePubkey = nextPubkey;
@@ -18540,8 +18816,8 @@ var BrowserWebrtcController = class {
18540
18816
  throw new Error("session limit reached");
18541
18817
  }
18542
18818
  const signer = this.requireSigner();
18543
- const localPubkey = normalizePubkey2(await signer.getPublicKey());
18544
- if (!localPubkey || localPubkey !== normalizePubkey2(this.options.getPubkey())) throw new Error("signaling unavailable");
18819
+ const localPubkey = normalizePubkey3(await signer.getPublicKey());
18820
+ if (!localPubkey || localPubkey !== normalizePubkey3(this.options.getPubkey())) throw new Error("signaling unavailable");
18545
18821
  const identity = this.options.getIdentity(context.windowId);
18546
18822
  const allowed2 = await this.options.confirm({
18547
18823
  action: "webrtc",
@@ -18554,7 +18830,7 @@ var BrowserWebrtcController = class {
18554
18830
  const id = this.crypto.randomUUID();
18555
18831
  const channel = request.channel ?? "default";
18556
18832
  const roomHash = request.scope.type === "room" ? await hashRoom(this.crypto, request.scope.room) : void 0;
18557
- const allowedPeers = request.scope.type === "direct" ? /* @__PURE__ */ new Set([normalizePubkey2(request.scope.pubkey)]) : request.scope.peers && request.scope.peers.length > 0 ? new Set(request.scope.peers.map((peer) => normalizePubkey2(peer))) : null;
18833
+ const allowedPeers = request.scope.type === "direct" ? /* @__PURE__ */ new Set([normalizePubkey3(request.scope.pubkey)]) : request.scope.peers && request.scope.peers.length > 0 ? new Set(request.scope.peers.map((peer) => normalizePubkey3(peer))) : null;
18558
18834
  const session = {
18559
18835
  id,
18560
18836
  windowId: context.windowId,
@@ -18731,7 +19007,7 @@ var BrowserWebrtcController = class {
18731
19007
  async publishPresence(session, type, recipient) {
18732
19008
  const tags = [["type", type]];
18733
19009
  if (recipient) tags.push(["p", recipient]);
18734
- else if (session.request.scope.type === "direct") tags.push(["p", normalizePubkey2(session.request.scope.pubkey)]);
19010
+ else if (session.request.scope.type === "direct") tags.push(["p", normalizePubkey3(session.request.scope.pubkey)]);
18735
19011
  else if (session.allowedPeers) {
18736
19012
  for (const peer of session.allowedPeers) tags.push(["p", peer]);
18737
19013
  }
@@ -18788,7 +19064,7 @@ var BrowserWebrtcController = class {
18788
19064
  }
18789
19065
  requireSessionSigner(session) {
18790
19066
  const signer = this.requireSigner();
18791
- if (normalizePubkey2(this.options.getPubkey()) !== session.localPubkey) throw new Error("signaling unavailable");
19067
+ if (normalizePubkey3(this.options.getPubkey()) !== session.localPubkey) throw new Error("signaling unavailable");
18792
19068
  return signer;
18793
19069
  }
18794
19070
  removePeer(session, pubkey2, notify) {
@@ -18834,12 +19110,12 @@ function validateOpenRequest(request) {
18834
19110
  throw new Error("unsupported scope");
18835
19111
  }
18836
19112
  if (request.scope.type === "direct") {
18837
- if (!normalizePubkey2(request.scope.pubkey)) throw new Error("unsupported scope");
19113
+ if (!normalizePubkey3(request.scope.pubkey)) throw new Error("unsupported scope");
18838
19114
  } else if (request.scope.type === "room") {
18839
19115
  if (typeof request.scope.room !== "string" || request.scope.room.length < 8 || request.scope.room.length > 128) {
18840
19116
  throw new Error("unsupported scope");
18841
19117
  }
18842
- if (request.scope.peers && (request.scope.peers.length > PAJA_WEBRTC_MAX_PEERS || request.scope.peers.some((peer) => !normalizePubkey2(peer)))) throw new Error("unsupported scope");
19118
+ if (request.scope.peers && (request.scope.peers.length > PAJA_WEBRTC_MAX_PEERS || request.scope.peers.some((peer) => !normalizePubkey3(peer)))) throw new Error("unsupported scope");
18843
19119
  } else {
18844
19120
  throw new Error("unsupported scope");
18845
19121
  }
@@ -18853,17 +19129,17 @@ function signalFilters(session) {
18853
19129
  return session.roomHash ? [{ ...base, "#r": [session.roomHash] }] : [{ ...base, "#p": [session.localPubkey] }];
18854
19130
  }
18855
19131
  function scopeAllowsPeer(session, pubkey2) {
18856
- return normalizePubkey2(pubkey2) !== null && pubkey2 !== session.localPubkey && (session.allowedPeers === null || session.allowedPeers.has(pubkey2));
19132
+ return normalizePubkey3(pubkey2) !== null && pubkey2 !== session.localPubkey && (session.allowedPeers === null || session.allowedPeers.has(pubkey2));
18857
19133
  }
18858
19134
  function isSignalPayload(value, session) {
18859
- if (!isRecord5(value) || value.version !== 1 || typeof value.signalId !== "string") return false;
18860
- if (value.channel !== session.channel || value.protocol !== session.protocol || !isRecord5(value.description)) return false;
19135
+ if (!isRecord6(value) || value.version !== 1 || typeof value.signalId !== "string") return false;
19136
+ if (value.channel !== session.channel || value.protocol !== session.protocol || !isRecord6(value.description)) return false;
18861
19137
  return (value.description.type === "offer" || value.description.type === "answer") && typeof value.description.sdp === "string";
18862
19138
  }
18863
19139
  function isSignalingSigner(signer) {
18864
19140
  return typeof signer?.getPublicKey === "function" && typeof signer.signEvent === "function" && typeof signer.nip44?.encrypt === "function" && typeof signer.nip44.decrypt === "function";
18865
19141
  }
18866
- function normalizePubkey2(value) {
19142
+ function normalizePubkey3(value) {
18867
19143
  return typeof value === "string" && /^[0-9a-f]{64}$/iu.test(value) ? value.toLowerCase() : null;
18868
19144
  }
18869
19145
  function describeScope(request) {
@@ -18890,7 +19166,7 @@ function tagValue2(tags, name) {
18890
19166
  function tagValues(tags, name) {
18891
19167
  return tags.filter((tag) => tag[0] === name && typeof tag[1] === "string").map((tag) => tag[1]);
18892
19168
  }
18893
- function isRecord5(value) {
19169
+ function isRecord6(value) {
18894
19170
  return typeof value === "object" && value !== null && !Array.isArray(value);
18895
19171
  }
18896
19172
  function defaultPeerConnectionFactory() {
@@ -19685,7 +19961,7 @@ function createRuntimeSigner(getSimulation, confirmRequest, signerProvider, sour
19685
19961
  }
19686
19962
  return signer;
19687
19963
  }
19688
- function createDevServices(backend, getSimulation, relayConfig, onThemeService, onThemeBroadcast, confirmRequest, getBlossomServers, uploadRuntime, signerProvider, intentHost, getIdentity, userActivation, notifyOptions, configOptions) {
19964
+ function createDevServices(backend, getSimulation, relayConfig, onThemeService, onThemeBroadcast, confirmRequest, getConfiguredBlossomServers, uploadRuntime, signerProvider, intentHost, getIdentity, userActivation, notifyOptions, configOptions) {
19689
19965
  const theme = createThemeService({
19690
19966
  initialTheme: createDevTheme(getSimulation().theme.mode, getSimulation().theme.values),
19691
19967
  onBroadcast: onThemeBroadcast
@@ -19696,6 +19972,11 @@ function createDevServices(backend, getSimulation, relayConfig, onThemeService,
19696
19972
  const getWriteRelays = () => relayConfig.getRelayUrls(["outbox"]);
19697
19973
  const getAllRelays = () => relayConfig.getRelayUrls();
19698
19974
  const baseOutboxRouter = createOutboxRouter(backend, getSimulation, relayConfig, confirmRequest, signerProvider);
19975
+ const blossomEventResolver = createPajaBlossomEventResolver({
19976
+ baseRouter: baseOutboxRouter,
19977
+ getDefaultAuthors: () => [getRuntimePubkey(getSimulation, signerProvider)],
19978
+ getConfiguredServers: getConfiguredBlossomServers
19979
+ });
19699
19980
  const socialCache = createPajaSocialCache({
19700
19981
  baseRouter: baseOutboxRouter,
19701
19982
  loadContactList: createPajaContactListLoader(backend, getSimulation, signerProvider, getReadRelays),
@@ -19714,11 +19995,20 @@ function createDevServices(backend, getSimulation, relayConfig, onThemeService,
19714
19995
  getSigner: () => createRuntimeSigner(getSimulation, confirmRequest, signerProvider)
19715
19996
  });
19716
19997
  void socialCache.refreshActiveIdentity();
19998
+ const resourceService = createResourceService({
19999
+ fetch: createPajaResourceFetch({
20000
+ getBlossomServers: ({ url, windowId }) => blossomEventResolver.getServers(url, windowId)
20001
+ }),
20002
+ resourceInfo: () => pajaResourceInfo()
20003
+ });
19717
20004
  const services = {
19718
- resource: createResourceService({
19719
- fetch: createPajaResourceFetch({ getBlossomServers }),
19720
- resourceInfo: () => pajaResourceInfo()
19721
- })
20005
+ resource: {
20006
+ ...resourceService,
20007
+ onWindowDestroyed(windowId) {
20008
+ resourceService.onWindowDestroyed?.(windowId);
20009
+ blossomEventResolver.clearWindow(windowId);
20010
+ }
20011
+ }
19722
20012
  };
19723
20013
  if (getSimulation().capabilities.domains.keys && typeof document !== "undefined") {
19724
20014
  services.keys = createKeysService({ listenerTarget: document });
@@ -19742,9 +20032,13 @@ function createDevServices(backend, getSimulation, relayConfig, onThemeService,
19742
20032
  });
19743
20033
  services.outbox = createOutboxService({
19744
20034
  router: baseOutboxRouter,
19745
- getQueryRouter: (windowId, context) => socialCache.decorate(
19746
- baseOutboxRouter,
19747
- () => context?.hasCapability(windowId, "identity:read") ?? false
20035
+ getReadRouter: (windowId) => blossomEventResolver.decorate(baseOutboxRouter, windowId),
20036
+ getQueryRouter: (windowId, context) => blossomEventResolver.decorate(
20037
+ socialCache.decorate(
20038
+ baseOutboxRouter,
20039
+ () => context?.hasCapability(windowId, "identity:read") ?? false
20040
+ ),
20041
+ windowId
19748
20042
  )
19749
20043
  });
19750
20044
  }
@@ -19914,7 +20208,7 @@ function createPajaAdapter(config, getSimulation, onThemeService, onThemeBroadca
19914
20208
  getNappletIdentity: resolveIdentity,
19915
20209
  subscribeSignerChange: signerProvider?.subscribe?.bind(signerProvider)
19916
20210
  }) : void 0;
19917
- const getBlossomServers = () => [
20211
+ const getConfiguredBlossomServers = () => [
19918
20212
  ...config.target?.pointer?.blossomServers ?? [],
19919
20213
  ...uploadRuntime?.getServers() ?? getSimulation().upload.servers
19920
20214
  ];
@@ -19927,7 +20221,7 @@ function createPajaAdapter(config, getSimulation, onThemeService, onThemeBroadca
19927
20221
  onThemeService,
19928
20222
  onThemeBroadcast,
19929
20223
  confirmRequest,
19930
- getBlossomServers,
20224
+ getConfiguredBlossomServers,
19931
20225
  uploadRuntime,
19932
20226
  signerProvider,
19933
20227
  intentHost,
@@ -20456,14 +20750,14 @@ function createPajaPostMessageProxy(realWin, state, windowId) {
20456
20750
  return proxy;
20457
20751
  }
20458
20752
  function redactPajaMessageForLog(message) {
20459
- if (!isRecord6(message) || message.type !== "config.values") return message;
20753
+ if (!isRecord7(message) || message.type !== "config.values") return message;
20460
20754
  return {
20461
20755
  type: "config.values",
20462
20756
  ...typeof message.id === "string" ? { id: message.id } : {},
20463
20757
  values: "[redacted by host]"
20464
20758
  };
20465
20759
  }
20466
- function isRecord6(value) {
20760
+ function isRecord7(value) {
20467
20761
  return typeof value === "object" && value !== null && !Array.isArray(value);
20468
20762
  }
20469
20763
  function installPajaOriginRegistryProxy(originRegistry2, stateRef) {
@@ -22234,7 +22528,7 @@ function createPajaConfigController(options) {
22234
22528
  const raw = storage.getItem(storageKey(options.getIdentity(windowId)));
22235
22529
  if (!raw) return cloneValues(options.getInitialValues?.(windowId) ?? {});
22236
22530
  const value = JSON.parse(raw);
22237
- return isRecord7(value) ? value : {};
22531
+ return isRecord8(value) ? value : {};
22238
22532
  } catch {
22239
22533
  return {};
22240
22534
  }
@@ -22297,9 +22591,9 @@ function cloneValues(values) {
22297
22591
  }
22298
22592
  }
22299
22593
  function renderObjectFields(document2, parent, schema, values, path, bindings, selectedSection) {
22300
- const properties = isRecord7(schema.properties) ? schema.properties : {};
22594
+ const properties = isRecord8(schema.properties) ? schema.properties : {};
22301
22595
  const required = new Set(Array.isArray(schema.required) ? schema.required.filter((key) => typeof key === "string") : []);
22302
- const ordered = Object.entries(properties).filter((entry) => isRecord7(entry[1])).filter(([, child2]) => !selectedSection || child2["x-napplet-section"] === selectedSection || child2.type === "object").sort(([leftKey, left], [rightKey, right]) => compareSchemaFields(leftKey, left, rightKey, right));
22596
+ const ordered = Object.entries(properties).filter((entry) => isRecord8(entry[1])).filter(([, child2]) => !selectedSection || child2["x-napplet-section"] === selectedSection || child2.type === "object").sort(([leftKey, left], [rightKey, right]) => compareSchemaFields(leftKey, left, rightKey, right));
22303
22597
  for (const [key, rawChild] of ordered) {
22304
22598
  const child2 = rawChild;
22305
22599
  const childPath = [...path, key];
@@ -22397,7 +22691,7 @@ function assignPath(target, path, value) {
22397
22691
  let cursor = target;
22398
22692
  for (const segment of path.slice(0, -1)) {
22399
22693
  const child2 = cursor[segment];
22400
- if (!isRecord7(child2)) cursor[segment] = {};
22694
+ if (!isRecord8(child2)) cursor[segment] = {};
22401
22695
  cursor = cursor[segment];
22402
22696
  }
22403
22697
  const final = path.at(-1);
@@ -22406,7 +22700,7 @@ function assignPath(target, path, value) {
22406
22700
  function readPath(values, path) {
22407
22701
  let cursor = values;
22408
22702
  for (const segment of path) {
22409
- if (!isRecord7(cursor)) return void 0;
22703
+ if (!isRecord8(cursor)) return void 0;
22410
22704
  cursor = cursor[segment];
22411
22705
  }
22412
22706
  return cursor;
@@ -22448,7 +22742,7 @@ function readGlobalStorage() {
22448
22742
  return null;
22449
22743
  }
22450
22744
  }
22451
- function isRecord7(value) {
22745
+ function isRecord8(value) {
22452
22746
  return typeof value === "object" && value !== null && !Array.isArray(value);
22453
22747
  }
22454
22748