@ghostlytools/sdk 1.2.3 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/app.js +15 -4
  2. package/dist/app.js.map +1 -1
  3. package/dist/core.js +2 -2
  4. package/dist/{fakes-CBIuqo5e.js → fakes-BlpK1WuW.js} +2 -2
  5. package/dist/{fakes-CBIuqo5e.js.map → fakes-BlpK1WuW.js.map} +1 -1
  6. package/dist/fakes.js +1 -1
  7. package/dist/index.js +2 -2
  8. package/dist/{keet-identity-key-BylxCPl4.js → keet-identity-key-GE5nr3zt.js} +2 -2
  9. package/dist/{keet-identity-key-BylxCPl4.js.map → keet-identity-key-GE5nr3zt.js.map} +1 -1
  10. package/dist/{src-DCeLPsi-.js → src-JQitqFJD.js} +1038 -137
  11. package/dist/src-JQitqFJD.js.map +1 -0
  12. package/dist/testing.js +3 -3
  13. package/dist/types/core/src/appBundle.d.ts +28 -0
  14. package/dist/types/core/src/chatFiles.d.ts +41 -1
  15. package/dist/types/core/src/datalink.d.ts +13 -7
  16. package/dist/types/core/src/dhtDelivery.d.ts +9 -0
  17. package/dist/types/core/src/engineErrors.d.ts +1 -0
  18. package/dist/types/core/src/frames.d.ts +5 -0
  19. package/dist/types/core/src/ghostlink.d.ts +83 -8
  20. package/dist/types/core/src/groupCommunity.d.ts +37 -1
  21. package/dist/types/core/src/groupFiles.d.ts +6 -2
  22. package/dist/types/core/src/groupSession.d.ts +57 -6
  23. package/dist/types/core/src/groupSignals.d.ts +2 -0
  24. package/dist/types/core/src/link.d.ts +15 -0
  25. package/dist/types/core/src/miniApp.d.ts +15 -4
  26. package/dist/types/core/src/pairedCapabilities.d.ts +6 -1
  27. package/dist/types/core/src/pkarr.d.ts +6 -0
  28. package/dist/types/core/src/relay.d.ts +60 -4
  29. package/dist/types/core/src/transport.d.ts +12 -0
  30. package/dist/{verify-DBGw6wYt.js → verify-afQj9kHW.js} +2 -2
  31. package/dist/{verify-DBGw6wYt.js.map → verify-afQj9kHW.js.map} +1 -1
  32. package/package.json +1 -1
  33. package/dist/src-DCeLPsi-.js.map +0 -1
@@ -140,11 +140,17 @@ export interface GroupEditFrame {
140
140
  c: string;
141
141
  sig: string;
142
142
  }
143
+ /**
144
+ * `left`: on a `remove` commit made on the member's own leave (its `group-leave`, its signed `group-bye`, or its leave
145
+ * on the admin's chat), the committer's signature over `leftSigned` (WISP 902 § Leaving): only the admin knows the
146
+ * removal was asked for, and a hub cannot add the mark to one it was not. Apps from before leave it out and drop it.
147
+ */
143
148
  export interface GroupCommitFrame {
144
149
  t: "group-commit";
145
150
  g: string;
146
151
  commit: GroupCommit;
147
152
  secret?: SealedSecret;
153
+ left?: string;
148
154
  }
149
155
  /**
150
156
  * `mt`: which metadata statement I hold (`groupMetaTag`); apps without metadata leave it out. `miss`: sequence numbers
@@ -242,7 +248,11 @@ export interface GroupState {
242
248
  seqEpoch: number;
243
249
  /** My own frames, newest last, for members who missed them. */
244
250
  sent: GroupMessageFrame[];
245
- /** Other members' frames, in the order they arrived, for members who missed them. Absent in states from before revision 0.9. */
251
+ /**
252
+ * Other members' frames, in the order they arrived, for members who missed them. Absent in states from before revision
253
+ * 0.9. With an app that keeps each frame with its message (`GroupSession`'s `onRows`), only the ones from before it
254
+ * did, until newer ones take their place.
255
+ */
246
256
  relay?: GroupMessageFrame[];
247
257
  /** Other members' edits, the latest per message, for members who missed them. Absent in states from before edits were handed on. */
248
258
  relayEdits?: GroupEditFrame[];
@@ -265,6 +275,8 @@ export interface GroupState {
265
275
  * (`resealBehind`): I may have been behind on the chain without knowing. Absent in older states.
266
276
  */
267
277
  alone?: string[];
278
+ /** Epoch → the admin's mark (`GroupCommitFrame.left`) on the commit of that epoch that took out a member who left. Absent in older states. */
279
+ leftMarks?: Record<string, string>;
268
280
  }
269
281
  /**
270
282
  * `completes`: this message was delivered before from a copy another member handed on without its author's whole
@@ -295,6 +307,12 @@ export interface GroupSessionHooks {
295
307
  send(to: string, frame: GroupEdgeFrame): boolean | void;
296
308
  /** Store before it resolves: replay state advances only afterwards. */
297
309
  message(message: GroupIncomingMessage): Promise<void> | void;
310
+ /**
311
+ * A frame kept to hand on that came with no message of its own: message `id`, stored before, said again by its author
312
+ * under a later epoch (WISP 902 § Catch-up, "Frames said again"). An app that keeps the frames with its messages puts
313
+ * this one in the place of that message's.
314
+ */
315
+ kept?(id: string, frame: GroupMessageFrame): Promise<void> | void;
298
316
  /** An edit of a member's message, authenticated as its author (WISP 902 § Edits). Apps without edits leave it out. */
299
317
  edit?(edit: GroupIncomingEdit): Promise<void> | void;
300
318
  /** Roster, epoch or status changed. */
@@ -352,7 +370,6 @@ export interface GroupPinFrame extends WirePin {
352
370
  k: string;
353
371
  sig: string;
354
372
  }
355
- /** What a frame weighs in a log, roughly: its boxes plus the fixed fields around them. */
356
373
  /** What a kept frame counts for against `GROUP_LIMITS.relayBytes`. */
357
374
  export declare const frameBytes: (f: GroupMessageFrame) => number;
358
375
  /**
@@ -383,8 +400,15 @@ export declare class GroupSession {
383
400
  private pendingMeta;
384
401
  /** While `handle` runs: the frames it took that a hub passes on (`handle`'s result). */
385
402
  private passOn;
403
+ /** The frames kept to hand on that the app holds with its messages, oldest first; undefined when the state holds them all. */
404
+ private onRows;
386
405
  /** Set while a save of what received messages changed is due (`persistSoon`). */
387
406
  private saveTimer;
407
+ /**
408
+ * The frames of members who left that each member was handed (`frameKey`), so an app that does not take them (from
409
+ * before revision 2026-10-13, and never marks them seen) is not handed them again at every sync. In memory only.
410
+ */
411
+ private leaversHanded;
388
412
  /** Syncs answered per member, a few a minute (`GROUP_LIMITS.syncAnswers`). In memory only. */
389
413
  private syncsAnswered;
390
414
  /** Catch-up answers still going out, a slice at a time (`handOut`). */
@@ -397,7 +421,12 @@ export declare class GroupSession {
397
421
  private provisional;
398
422
  /** When my chain last moved (a commit made or applied), by `hooks.clock`: frames are said again once it has settled. */
399
423
  private chainMovedAt;
400
- constructor(state: GroupState, hooks: GroupSessionHooks);
424
+ /**
425
+ * `onRows`: the frames the app holds with the messages it stored (`GroupIncomingMessage.frame`), oldest first. Given
426
+ * (empty at first), the app is where frames are kept: the saved state carries none of them, and a message received
427
+ * no longer writes them all again. Absent: they are kept in the state, as before.
428
+ */
429
+ constructor(state: GroupState, hooks: GroupSessionHooks, onRows?: GroupMessageFrame[]);
401
430
  private clock;
402
431
  /** A new group: its genesis commit, signed by the creator, who is its admin. */
403
432
  static create(name: string, now?: number): GroupState;
@@ -487,17 +516,31 @@ export declare class GroupSession {
487
516
  * contact link) after telling the existing members over their edges.
488
517
  */
489
518
  admit(memberKey: string, now?: number): Promise<(GroupChainFrame | GroupWelcomeFrame)[]>;
490
- remove(memberKey: string, now?: number): Promise<void>;
519
+ /**
520
+ * A welcome for a member already in the roster that never got the first one (its chat closed while it was let in):
521
+ * nothing is committed. It carries the secrets of the epochs it was in, from its admission on, sealed to its key.
522
+ */
523
+ rewelcome(memberKey: string): Promise<(GroupChainFrame | GroupWelcomeFrame)[]>;
524
+ /** `left`: the member asked to leave (on the admin's chat), and the commit says so (`GroupCommitFrame.left`). */
525
+ remove(memberKey: string, now?: number, { left }?: {
526
+ left?: boolean | undefined;
527
+ }): Promise<void>;
491
528
  transferAdmin(memberKey: string, now?: number): Promise<void>;
492
529
  /** A fresh secret without a membership change: whoever holds the old one and is not a member learns nothing new. */
493
530
  rotate(now?: number): Promise<void>;
494
531
  private commit;
495
- /** Someone out of the roster is not handed on any more, whatever they sent while in it (WISP 902 § Catch-up). */
532
+ /**
533
+ * Someone removed is not handed on any more, whatever they sent while in the roster; one who left still is, for the
534
+ * epochs before its leave (WISP 902 § Catch-up).
535
+ */
496
536
  private pruneRelay;
497
537
  /** Another member's edit, kept to hand on: the latest per message; the oldest go once the log is full. False: one as new was kept. */
498
538
  private keepEdit;
499
539
  /** A frame of another member, kept to hand on; the oldest go once the log is full. */
500
540
  private keep;
541
+ /** The frames kept to hand on, oldest first: the state's, then the ones the app holds with its messages. */
542
+ private kept;
543
+ private trimRelay;
501
544
  private pruneSecrets;
502
545
  /** Leaves: my secrets go now; the admin removes me from the roster when it hears. */
503
546
  leave(): Promise<void>;
@@ -636,7 +679,8 @@ export declare class GroupSession {
636
679
  private commitUnlessTurnUnconfirmed;
637
680
  /**
638
681
  * A message, from its author's edge or handed on by another member. Handed on, it is taken only while both are in
639
- * the roster (someone removed is neither heard from nor handed on, #300), and its boxes only with the author's `xs`.
682
+ * the roster (someone removed is neither heard from nor handed on, #300), or from a member in it when its author left
683
+ * after it (`handsOn`), and its boxes only with the author's `xs`.
640
684
  */
641
685
  private receiveMessage;
642
686
  /**
@@ -662,6 +706,13 @@ export declare class GroupSession {
662
706
  private ask;
663
707
  private replayWaiting;
664
708
  private receiveCommit;
709
+ /**
710
+ * Whether a frame of `author` under `epoch` is taken from another member, kept and handed on: while its author is in
711
+ * the roster, or when it left (its removal marked `left`, and it is not back in) and the frame is from before that.
712
+ */
713
+ private handsOn;
714
+ /** Keeps the admin's mark on a commit that took out a member who left (`GroupCommitFrame.left`) when it holds; true when new. */
715
+ private takeLeftMark;
665
716
  private apply;
666
717
  /** A sealed secret for an epoch of my chain: kept only when it confirms against that epoch's commit. */
667
718
  private takeSecret;
@@ -98,6 +98,8 @@ export declare class CarriedTransport implements PkarrTransport {
98
98
  /** My last packet while the edge is down: what a member that just became reachable is handed. */
99
99
  private mine;
100
100
  private lastTimestamp;
101
+ /** The date each packet `stamp` signed carries: the relays' transport takes it rather than check the signature again. */
102
+ private readonly dated;
101
103
  /** My newest packet, wherever it went: what the edge hands the member over itself once it is ready (`linkReady`). */
102
104
  private newest;
103
105
  /** The newest packet of the member's that came through a carrier, and the timestamp of the one a read last returned. */
@@ -67,6 +67,15 @@ export declare const STALLED_LOOK_MS = 15000;
67
67
  export declare const DEPARTED_READ_MS = 30000;
68
68
  /** A chat whose contact was never seen (an invite just sent) keeps looking at the active pace this long. */
69
69
  export declare const AWAITING_PEER_MS: number;
70
+ /**
71
+ * An invite this side made that nobody used, once no longer awaited (`AWAITING_PEER_MS`), is read less often the older
72
+ * it is: a fifth of its age between reads, up to this. Read at the background pace instead, 15 unused invites (their
73
+ * keys and their mailboxes) asked the relays for 60 reads a minute for as long as the app ran: the relays' minute went
74
+ * to invites nobody may ever open, and a join on one was noticed 90 s later (bug hunt 1013-1642, 2026-10-13).
75
+ */
76
+ export declare const UNUSED_INVITE_WAIT_MAX_MS: number;
77
+ /** The wait between reads of an unused invite of age `age` (`UNUSED_INVITE_WAIT_MAX_MS`), never shorter than the pace's `interval`. */
78
+ export declare function unusedInviteWait(age: number, interval: number): number;
70
79
  /**
71
80
  * A group link's peer whose packet advertises and carries no `_tr` on every read for this long publishes none: what it
72
81
  * said before is forgotten (WISP 902 § Transports). Not at the first such packet: an app with no WebRTC (a Linux
@@ -169,6 +178,8 @@ export interface LinkSessionOptions {
169
178
  * sent at once) went out for a minute (2026-10-08).
170
179
  */
171
180
  awaitingSince?: number;
181
+ /** Whether this is an invite this side made that nobody used yet: once no longer awaited, read less often (`unusedInviteWait`). */
182
+ invite?: () => boolean;
172
183
  }
173
184
  /** With `firstPublish: "after-first-poll"`, the first packet goes out by then whatever happened. */
174
185
  export declare const FIRST_PUBLISH_MAX_MS = 2000;
@@ -213,6 +224,8 @@ export declare class LinkSession {
213
224
  private readonly startedAt;
214
225
  /** From when a peer never seen is awaited (`AWAITING_PEER_MS`): never later than this start, whatever the clock said when the chat was made. */
215
226
  private readonly awaitingSince;
227
+ /** This side's invite, nobody used yet (`LinkSessionOptions.invite`). */
228
+ private readonly invite;
216
229
  private readonly intervals;
217
230
  private fastPollUntil;
218
231
  /** An offer to a saved contact is out: from then on its fast window looks less often (`OFFER_FAST_MS`); 0 for none. */
@@ -337,6 +350,8 @@ export declare class LinkSession {
337
350
  * the one that comes back.
338
351
  */
339
352
  private watching;
353
+ /** A contact never seen, whose invite was sent lately (`AWAITING_PEER_MS`): its join is due. */
354
+ private awaitingPeer;
340
355
  /** How urgently this link looks right now. */
341
356
  private pace;
342
357
  private scheduleHeartbeat;
@@ -75,15 +75,16 @@ export interface MiniAppRequest {
75
75
  * - `bad-path`: a `file` path that is not a string of 1 to 1024 characters.
76
76
  * - `bad-request`: a request that is not `{id, type, args}` with JSON arguments.
77
77
  * - `failed`: anything else; the client's own words never reach the app.
78
- * - `full`: a storage write would take the scope past 5 MiB (each key counts 128 bytes beside its own and its value's),
79
- * so the app can make room.
78
+ * - `full`: a storage write would take the scope past 5 MiB (each key counts 128 bytes, its own bytes eight times and
79
+ * its value's), so the app can make room.
80
80
  * - `no-file`: the bundle has no such file.
81
81
  * - `not-allowed`: `chat.send` without the `chat` permission, or with the app opened alone.
82
82
  * - `not-open`: `chat.send` before this side's chat has the app open.
83
83
  * - `offline`: `chat.send` while the chat's session is not live. Nothing is kept to send later.
84
84
  * - `peer-closed`: `chat.send` while the contact has not opened the app (or its client does not offer `apps/1`).
85
85
  * - `stopped`: a store removed or the publisher revoked the version running.
86
- * - `too-fast`: past 50 requests a second, or past 48 `chat.send` frames a second.
86
+ * - `too-fast`: past 50 requests a second, past 48 `chat.send` frames a second, or a `chat.send` while the chat's
87
+ * connection is still sending earlier ones (back off and send again).
87
88
  * - `too-large`: a request, a stored value or a `chat.send` value past its bound (`MINI_APP_LIMITS`).
88
89
  * - `unknown-type`: a request `type` the broker does not answer.
89
90
  *
@@ -128,13 +129,23 @@ export declare const MINI_APP_LIMITS: {
128
129
  readonly requestBytes: number;
129
130
  /** Requests per second, per app. */
130
131
  readonly requestsPerSecond: 50;
132
+ /**
133
+ * Bytes of `file` answers per second, per app: a whole bundle's worth. A read that starts under it is answered whole;
134
+ * past it `file` is refused with `too-fast` until the second has gone.
135
+ */
136
+ readonly fileBytesPerSecond: number;
131
137
  /** A storage key, UTF-8. */
132
138
  readonly storageKeyBytes: 256;
133
139
  /** One stored JSON value, serialized. */
134
140
  readonly storageValueBytes: number;
135
141
  /** Counted for each stored key beside its own bytes and its value's: what keeping the key costs the device. */
136
142
  readonly storageRowBytes: 128;
137
- /** Everything an app keeps in one scope (per app and per chat, or alone): each key, its value and `storageRowBytes`. */
143
+ /** How many times a stored key's bytes count: the device keeps each key several times, mostly as UTF-16. */
144
+ readonly storageKeyTimes: 8;
145
+ /**
146
+ * Everything an app keeps in one scope (per app and per chat, or alone): for each key `storageRowBytes`, the key's
147
+ * bytes `storageKeyTimes` over and its value's.
148
+ */
138
149
  readonly storageScopeBytes: number;
139
150
  /** One `chat.send` value, serialized: the `paired-app` data cap (decision D5 of the plan). */
140
151
  readonly chatDataBytes: number;
@@ -20,6 +20,11 @@ export declare const SERVICES_CAPABILITY = "services/1";
20
20
  * confirmed byte, checked by digest (`pf-offer` … frames, `chatFiles.ts`). Without it, files/2 and 100 MiB.
21
21
  */
22
22
  export declare const FILES_CAPABILITY = "files/3";
23
+ /**
24
+ * A file's bytes as binary messages (WISP 501 § files/4): beside `files/3`, on a session whose channel carries binary
25
+ * messages, a chunk travels as it is (`encodeFileData`, `chatFiles.ts`) and not as base64url text in a `pf-data` frame.
26
+ */
27
+ export declare const FILES_BINARY_CAPABILITY = "files/4";
23
28
  /** The typing indicator: `paired-typing` frames on this session, 1:1 chats only (WISP 401 § Typing, `pairedTyping.ts`). */
24
29
  export declare const TYPING_CAPABILITY = "typing/1";
25
30
  /** Reactions to messages: `paired-reaction` frames on this session, 1:1 chats only (WISP 401 § Reactions, `reactions.ts`). */
@@ -58,7 +63,7 @@ export declare const APPS_CAPABILITY = "apps/1";
58
63
  * What only a device link offers (WISP 06, `deviceLink.ts`): the frames between a person's own devices. They are in
59
64
  * the type so a device link can announce them, and not in `KNOWN_SESSION_CAPABILITIES`: no chat knows them.
60
65
  */
61
- export type SessionCapability = DeviceCapability | typeof CALLS_CAPABILITY | typeof SERVICES_CAPABILITY | typeof FILES_CAPABILITY | typeof TYPING_CAPABILITY | typeof REACTIONS_CAPABILITY | typeof EDIT_CAPABILITY | typeof WAKE_SESSION_CAPABILITY | typeof PIN_CAPABILITY | typeof STATUS_CARD_CAPABILITY | typeof BUTTONS_CAPABILITY | typeof UPGRADE_CAPABILITY | typeof APPS_CAPABILITY;
66
+ export type SessionCapability = DeviceCapability | typeof CALLS_CAPABILITY | typeof SERVICES_CAPABILITY | typeof FILES_CAPABILITY | typeof FILES_BINARY_CAPABILITY | typeof TYPING_CAPABILITY | typeof REACTIONS_CAPABILITY | typeof EDIT_CAPABILITY | typeof WAKE_SESSION_CAPABILITY | typeof PIN_CAPABILITY | typeof STATUS_CARD_CAPABILITY | typeof BUTTONS_CAPABILITY | typeof UPGRADE_CAPABILITY | typeof APPS_CAPABILITY;
62
67
  /** Every capability this app knows on a session: what `receive` reports changes of. */
63
68
  export declare const KNOWN_SESSION_CAPABILITIES: readonly SessionCapability[];
64
69
  export declare const SESSION_CAPABILITIES_FRAME = "paired-capabilities";
@@ -38,6 +38,12 @@ export declare function openRelayPayload(pubKeyZ32: string, payload: Uint8Array)
38
38
  };
39
39
  /** Verifies and decodes a relay payload. Throws if the signature does not match. */
40
40
  export declare function parseRelayPayload(pubKeyZ32: string, payload: Uint8Array): SignedPacket;
41
+ /**
42
+ * Decodes a payload whose signature this process made or already checked (one it is putting), without checking it
43
+ * again: an Ed25519 verify costs about 1 ms, and a CLI daemon at its relay budget checked its own packets ~500 times a
44
+ * minute. Never for bytes read from elsewhere: `parseRelayPayload` is.
45
+ */
46
+ export declare function readOwnRelayPayload(pubKeyZ32: string, payload: Uint8Array): SignedPacket;
41
47
  /** How far ahead of this clock a packet's time may be and still count as now: clocks drift, not by this much. */
42
48
  export declare const PKARR_FUTURE_SKEW_MS: number;
43
49
  /**
@@ -40,8 +40,8 @@ export declare const BACKGROUND_REQUESTS_PER_MINUTE = 20;
40
40
  export declare const WRITE_FIRST_MS = 5000;
41
41
  /**
42
42
  * Once a 1:1 chat needs the relays (the budget refused one of its requests there, or it read urgently anywhere: it polls
43
- * fast for a signal due any moment), group requests leave it the last this many of each minute, for a minute. Groups
44
- * that spend the whole budget spend it over the minute, so the chat then takes the next request that frees, within
43
+ * fast for a signal due any moment), group requests and background ones leave it the last this many of each minute (more
44
+ * for several chats, `CHAT_RESERVE_PER_CHAT`), for a minute. Groups that spend the whole budget spend it over the minute, so the chat then takes the next request that frees, within
45
45
  * seconds, and has room for what follows (the receipt). Waiting for a refusal was too late when a contact went away
46
46
  * from a chat and from groups at once: the chat and the groups' edges all watched fast for it, the edges spent both
47
47
  * relays' minute in 40 s, and the chat read the contact's offer half a minute late (2026-09-27). A chat with nothing
@@ -51,6 +51,18 @@ export declare const WRITE_FIRST_MS = 5000;
51
51
  * live in 18 s held a group's edge that had just missed its read for 48 s more (bug hunt r6a, 2026-09-29).
52
52
  */
53
53
  export declare const CHAT_RESERVE = 10;
54
+ /**
55
+ * …and more while several chats need the relays at once: this many requests each (a read, an offer or answer, the read
56
+ * for the answer to it), up to `CHAT_RESERVE_MOST_SHARE` of the minute. Background requests leave it too, not the
57
+ * groups' alone: the looks of chats whose contacts are not there, and their presence (upkeep, `LinkSession`). An app
58
+ * opened while 30 of its 50 chats' contacts were online spent both relays' minute in its first second, on the presence
59
+ * of the chats whose contacts were long gone, its groups' records and every chat's first read: 12 of the 30 offers and
60
+ * answers went out, no read for an answer could, and 0 of the 30 chats were live 60 s after the start (bug hunt,
61
+ * 2026-10-13).
62
+ */
63
+ export declare const CHAT_RESERVE_PER_CHAT = 3;
64
+ /** The most of a relay's minute the chats' reserve takes, however many chats need it: the rest stays for everything else. */
65
+ export declare const CHAT_RESERVE_MOST_SHARE: number;
54
66
  /**
55
67
  * A 1:1 chat's signaling (a new offer or answer, and its reads for the answer to its offer, `signal`) may go over a
56
68
  * relay's minute by this fraction of it: 6 on a relay of 30, 12 on one of 60, 1 on relay.pkarr.org's 5 (it allows 10),
@@ -225,6 +237,8 @@ export declare class RelayTransport implements PkarrTransport {
225
237
  * it is under the watch share (`WATCH_SHARE`) and while the groups' reads are rationed (`GROUP_RATION_WINDOW_MS`).
226
238
  */
227
239
  private readonly readTurns;
240
+ /** Per key read in turn (`isTurnRead`), when a read of it last went out and when it last asked (`READ_TURN_MS`). */
241
+ private readonly keyTurns;
228
242
  /** Groups' reads (not background ones) on each relay in the last `GROUP_RATION_WINDOW_MS`. */
229
243
  private readonly spentGroupReads;
230
244
  /** When a group's read last found each relay's minute full: its reads there are rationed for `GROUP_RATION_MS`. */
@@ -244,6 +258,11 @@ export declare class RelayTransport implements PkarrTransport {
244
258
  /** Per relay and key, the newest packet that relay held back for its budget while another relay took it (`catchUpLater`). */
245
259
  private readonly catchUp;
246
260
  private catchUpTimer;
261
+ /**
262
+ * Per key whose reads the budget held back since its last read went out: when a request frees for it
263
+ * (`readHeldBackFor`), how many times in a row, and since when (`READ_STARVED_MS`).
264
+ */
265
+ private readonly heldBack;
247
266
  /** When the relays last answered a read of each key, for `FRESH_READ_MS`. */
248
267
  private readonly readAt;
249
268
  private readonly freshReadMs;
@@ -289,18 +308,38 @@ export declare class RelayTransport implements PkarrTransport {
289
308
  nextTimestamp(pubKeyZ32: string): bigint;
290
309
  /**
291
310
  * Signs the records, dated by `nextTimestamp`, and hands the payload to `put` (the relays; the CLI adds the DHT).
311
+ * When every relay's budget (or rate limit) holds this asker back, it throws that wait before signing anything
312
+ * (`publishWait`): a daemon at its budget signed about 500 packets a minute that never went out. `elsewhere`: `put`
313
+ * also takes the packet where no budget holds it back (the CLI's DHT), so it is signed whatever the relays say.
292
314
  * `put` calls `conflict` for a relay that answered 409: it holds a packet under this key dated at or after this one,
293
315
  * which this client has not read (an inviter's warm packet under the key it gave its contact, from a clock ahead of
294
316
  * this one). That packet is read from that relay, and the records go again dated just past it, once. Without this
295
317
  * the packet was refused until this device's clock passed the other one's, however long that took, and on a relay
296
318
  * that did take it, readers still preferred the later-dated empty packet of another relay.
297
319
  */
298
- publishDated(identity: Identity, records: GhostRecord[], put: (pubKeyZ32: string, payload: Uint8Array, timestamp: bigint, conflict: (relay: string) => void) => Promise<void>, options?: PkarrRequestOptions, again?: boolean): Promise<void>;
320
+ publishDated(identity: Identity, records: GhostRecord[], put: (pubKeyZ32: string, payload: Uint8Array, timestamp: bigint, conflict: (relay: string) => void) => Promise<void>, options?: PkarrRequestOptions, again?: boolean, elsewhere?: boolean): Promise<void>;
321
+ /**
322
+ * How long until some relay takes a publish of this asker, and why each holds it back; null when one would now. Walks the relays as `put` does,
323
+ * without asking any: a relay the budget holds back gets its refused `take` (the asker's write then waits first in
324
+ * line, as when `put` is refused), one rate limiting or throttling this address is a wait, one left alone for failing
325
+ * is none. Null too when a relay fails another way (its network cooling down): the publish then goes, and fails, as
326
+ * before, and when no relay is held back at all.
327
+ */
328
+ private publishWait;
299
329
  /** One relay's packet for a key, read now: its time, kept for `nextTimestamp`. Null when it has none or does not answer. */
300
330
  private heldAt;
301
331
  /** A packet under this key was read (on a relay, or by the CLI on the DHT): its time, for `nextTimestamp`. */
302
332
  sawTimestamp(pubKeyZ32: string, timestamp: bigint): void;
303
- /** Puts a payload signed elsewhere (a did:dht document), byte for byte, on every relay. `conflict`: as `publishDated` gives it. */
333
+ /**
334
+ * Puts a payload `publishDated` just signed, dated `timestamp`, on every relay. Its signature is not checked: it was
335
+ * made here (`publishPayload` checks one signed elsewhere, to read its sequence number). `conflict`: as `publishDated`
336
+ * gives it.
337
+ */
338
+ putSigned(pubKeyZ32: string, payload: Uint8Array, timestamp: bigint, options?: PkarrRequestOptions, conflict?: (relay: string) => void): Promise<void>;
339
+ /**
340
+ * Puts a payload signed elsewhere (a did:dht document), byte for byte, on every relay; one signed here says its date
341
+ * (`signedAt`) and is not checked again. `conflict`: as `publishDated` gives it.
342
+ */
304
343
  publishPayload(pubKeyZ32: string, payload: Uint8Array, options?: PkarrRequestOptions, conflict?: (relay: string) => void): Promise<void>;
305
344
  /**
306
345
  * Puts the packet on every relay and settles as soon as one of them took it. A relay that is slow to
@@ -343,6 +382,8 @@ export declare class RelayTransport implements PkarrTransport {
343
382
  */
344
383
  private hedgeRoom;
345
384
  readAnsweredAt(pubKeyZ32: string): number | undefined;
385
+ readHeldBackFor(pubKeyZ32: string): number | undefined;
386
+ private heldBackUntil;
346
387
  /** The relays answered a read of this key now; answers older than `FRESH_READ_MS` are dropped as the list grows. */
347
388
  private answeredRead;
348
389
  /** The relay that answered a key's read, for its next one; the keys read longest ago go past `READ_TURNS_KEPT`. */
@@ -381,6 +422,19 @@ export declare class RelayTransport implements PkarrTransport {
381
422
  * would keep a turn it cannot take.
382
423
  */
383
424
  private readsAhead;
425
+ /** A read of `key` that takes turns asks: it waits for its turn from now on, unless it is taken (`turnAhead`). */
426
+ private turnAsked;
427
+ /**
428
+ * Whether a key read in turn longer ago than `key`, still asking, would take this relay's next request: one read in the
429
+ * background for a background read, and a chat's that is starved (`READ_STARVED_MS`) for any. One asks again after
430
+ * the budget held it back (a link's poll does, a one-off look does not), and keeps asking within `READ_TURN_MS` of its
431
+ * last ask, or of when it was told the budget frees a request for it (`readHeldBackFor`).
432
+ * One the budget holds back on its own account (a group's read, for the chats' reserve) keeps no turn: a group key
433
+ * waiting for the chats held every chat's read back (CLI lab, 2026-10-13).
434
+ */
435
+ private turnAhead;
436
+ /** A 1:1 chat's read of `key` the budget has held back for `READ_STARVED_MS` without a break. */
437
+ private starved;
384
438
  /** This contact's departed reads past the limit in the last minute (`DEPARTED_READS`). */
385
439
  private departedReads;
386
440
  /** One more, the contacts with none in the last minute dropped. */
@@ -390,6 +444,8 @@ export declare class RelayTransport implements PkarrTransport {
390
444
  private chatReservedFor;
391
445
  /** Requests allowed to this relay a minute: this client's budget, or the relay's own share (`RELAY_REQUESTS_PER_MINUTE`). */
392
446
  private limitOf;
447
+ /** What the chats that need the relays keep on this relay (`CHAT_RESERVE_PER_CHAT`), never less than `reserveOf`. */
448
+ private chatReserveOf;
393
449
  /** What groups leave a chat on this relay: `CHAT_RESERVE`, or a third of a smaller budget. */
394
450
  private reserveOf;
395
451
  private isCoolingDown;
@@ -31,6 +31,8 @@ export type DiscoveryChange = "tripped" | "recovered";
31
31
  * fast for a while, on the hub left and on its members alike: on CLI daemons the hub left got 2 of 24 beacon writes
32
32
  * through in 90 s (its entry went stale, and members it should have carried became hubs), and the members' requests
33
33
  * in its lobby went out 40 s after they asked (2026-10-03).
34
+ * A hub's reads say `door` only while someone is coming in (`Communities.doorBusy`): otherwise they give way like any
35
+ * background read, and an app that was a hub of several communities left its edges' signaling the share (2026-10-13).
34
36
  *
35
37
  * `signal`: a link's WebRTC signaling, what its contact waits for: the write of a new offer or answer, or a read for
36
38
  * the answer while this side's offer is out, or the reads of a DHT-only contact's mailbox once it shows it is leaving,
@@ -53,6 +55,11 @@ export interface PkarrRequestOptions {
53
55
  * restarts publishes its offer then. A few may go over the relay's minute (`DEPARTED_READS` in relay.ts).
54
56
  */
55
57
  departed?: boolean;
58
+ /**
59
+ * `publishPayload` only: the payload was signed in this process, dated so (a group edge's, `CarriedTransport`). Its
60
+ * signature is not checked again on the way to the relays, as `RelayTransport.putSigned`'s is not.
61
+ */
62
+ signedAt?: bigint;
56
63
  }
57
64
  /**
58
65
  * `transport` with `extra` added to every request's options: a group's edges say `group` so. The optional methods
@@ -119,6 +126,11 @@ export interface PkarrTransport {
119
126
  * where the transport cannot say; such a caller then takes no read for one.
120
127
  */
121
128
  readAnsweredAt?(pubKeyZ32: string): number | undefined;
129
+ /**
130
+ * How long the budget still holds back a read of this key, when its last read was held back and answered from a kept
131
+ * copy (`readAnsweredAt` did not move): when to read again. Undefined once a read went out, or where it cannot say.
132
+ */
133
+ readHeldBackFor?(pubKeyZ32: string): number | undefined;
122
134
  /**
123
135
  * Called with each time a server gave (`ServerTime`), where the transport can read one: what `ClockWatch` holds this
124
136
  * device's clock against. Returns the unsubscribe.
@@ -1,4 +1,4 @@
1
- import { Ql as boundVerifiedIdentity } from "./src-DCeLPsi-.js";
1
+ import { cu as boundVerifiedIdentity } from "./src-JQitqFJD.js";
2
2
  //#region ../browser/src/proofs/verify.ts
3
3
  var DAY = 86400;
4
4
  /**
@@ -103,4 +103,4 @@ function boundedIdentityFetch(options = { online: () => true }) {
103
103
  //#endregion
104
104
  export { verifyIdentity as i, boundedIdentityFetch as n, descriptorProblems as r, availableSigners as t };
105
105
 
106
- //# sourceMappingURL=verify-DBGw6wYt.js.map
106
+ //# sourceMappingURL=verify-afQj9kHW.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"verify-DBGw6wYt.js","names":[],"sources":["../../browser/src/proofs/verify.ts"],"sourcesContent":["import { boundVerifiedIdentity, IDENTITY_MAX_EVIDENCE, IDENTITY_MAX_VALIDITY, type IdentityStatement, type VerifiedIdentity } from \"@ghostly/core\";\nimport type { IdentityFetch, IdentityProofProvider, IdentitySigner, VerifyContext } from \"./contract\";\n\nconst DAY = 86_400;\n\n/**\n * The checks every proof goes through, whatever its provider: known provider, validity within the\n * provider's limit, bounded evidence, strict parsing, the provider's own check, and the category rule\n * (a self-custodied proof proves exactly the subject it names; an attested one says who attests it).\n * The engine verifies a contact's proof, and the person's own proof before saving it, only through this.\n */\nexport async function verifyIdentity(providers: readonly IdentityProofProvider[], statement: IdentityStatement, evidence: unknown, ctx: VerifyContext): Promise<VerifiedIdentity> {\n const { binding } = statement;\n const provider = providers.find(p => p.id === binding.provider);\n if (!provider) throw new Error(\"This app cannot verify this kind of identity\");\n if (binding.expiresAt - binding.issuedAt > Math.min(provider.validity.maxDays * DAY, IDENTITY_MAX_VALIDITY)) throw new Error(\"The proof lasts longer than this kind of identity allows\");\n if (JSON.stringify(evidence ?? null).length > IDENTITY_MAX_EVIDENCE) throw new Error(\"Evidence too large\");\n const parsed = provider.parseEvidence(evidence);\n const verified = boundVerifiedIdentity(await provider.verify(statement, parsed, ctx));\n if (provider.category === \"self-custodied\" && verified.subject !== binding.subject) throw new Error(\"The evidence is for another identity\");\n if (provider.category === \"provider-attested\" && !verified.attester) throw new Error(\"The evidence does not say who attests it\");\n return verified;\n}\n\n/** Problems with a provider's descriptor, empty when it is well-formed. The registry and the contract suite use it. */\nexport function descriptorProblems(p: IdentityProofProvider): string[] {\n const problems: string[] = [];\n if (!/^[a-z][a-z0-9-]{0,31}$/.test(p.id)) problems.push(\"id must match ^[a-z][a-z0-9-]{0,31}$\");\n if (!p.label?.trim()) problems.push(\"label is empty\");\n if (!p.description?.trim()) problems.push(\"description is empty\");\n if (!p.privacy?.trim()) problems.push(\"privacy is empty: say what verify contacts\");\n if (p.category !== \"self-custodied\" && p.category !== \"provider-attested\") problems.push(\"category is unknown\");\n if (!p.platforms.length) problems.push(\"no platforms\");\n const { defaultDays, maxDays } = p.validity;\n if (!(Number.isInteger(defaultDays) && Number.isInteger(maxDays) && defaultDays >= 1 && defaultDays <= maxDays && maxDays * DAY <= IDENTITY_MAX_VALIDITY)) problems.push(\"validity must be whole days, 1 ≤ default ≤ max ≤ 400\");\n if (p.recheck && !(Number.isInteger(p.recheck.afterSeconds) && p.recheck.afterSeconds >= 60)) problems.push(\"recheck.afterSeconds must be at least 60\");\n if (!p.signers.length) problems.push(\"no signers\");\n const ids = p.signers.map(s => s.id);\n if (new Set(ids).size !== ids.length) problems.push(\"signer ids are not unique\");\n for (const s of p.signers as readonly IdentitySigner<unknown>[]) {\n if (![\"in-app\", \"external-tool\", \"redirect\", \"publish\"].includes(s.kind)) problems.push(`signer ${s.id} has an unknown kind`);\n if (s.kind === \"in-app\" && typeof s.run !== \"function\") problems.push(`signer ${s.id} has no run()`);\n if (s.kind === \"external-tool\" && (typeof s.instructions !== \"function\" || typeof s.parse !== \"function\")) problems.push(`signer ${s.id} needs instructions() and parse()`);\n if (s.kind === \"redirect\" && typeof s.start !== \"function\") problems.push(`signer ${s.id} has no start()`);\n if (s.kind === \"publish\" && (typeof s.instructions !== \"function\" || typeof s.evidence !== \"function\")) problems.push(`signer ${s.id} needs instructions() and evidence()`);\n }\n return problems;\n}\n\n/** Signers of a provider that run on this platform and are available in this window. */\nexport function availableSigners<E>(p: IdentityProofProvider<E>, platform: IdentityProofProvider[\"platforms\"][number]): IdentitySigner<E>[] {\n return p.signers.filter(s => (s.platforms ?? p.platforms).includes(platform) && (s.available?.() ?? true));\n}\n\n/**\n * The engine's `ctx.fetch`: HTTPS GET only, no credentials or referrer, a time-out, a size cap,\n * redirects refused unless asked for.\n * `online` false refuses everything (the person turned the network off).\n */\nexport function boundedIdentityFetch(options: { online: () => boolean; timeoutMs?: number; fetcher?: typeof fetch } = { online: () => true }): IdentityFetch {\n return async (url, { headers, maxBytes = 64 * 1024, signal, redirect = \"error\" } = {}) => {\n if (!options.online()) throw new Error(\"Offline: this identity cannot be checked now\");\n const target = new URL(url);\n if (target.protocol !== \"https:\" || target.username || target.password) throw new Error(\"Identity checks use HTTPS only\");\n const timeout = AbortSignal.timeout(options.timeoutMs ?? 10_000);\n const response = await (options.fetcher ?? fetch)(target.href, {\n headers, signal: signal ? AbortSignal.any([signal, timeout]) : timeout,\n credentials: \"omit\", referrerPolicy: \"no-referrer\", cache: \"no-store\", redirect,\n });\n if (Number(response.headers.get(\"content-length\")) > maxBytes) throw new Error(\"Identity check response too large\");\n const reader = response.body?.getReader();\n const parts: Uint8Array[] = [];\n let length = 0;\n if (reader) {\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n length += value.length;\n if (length > maxBytes) throw new Error(\"Identity check response too large\");\n parts.push(value);\n }\n } finally { await reader.cancel().catch(() => {}); }\n }\n const bytes = new Uint8Array(length);\n let offset = 0;\n for (const part of parts) { bytes.set(part, offset); offset += part.length; }\n return { status: response.status, contentType: response.headers.get(\"content-type\") ?? \"\", text: new TextDecoder().decode(bytes), bytes };\n };\n}\n"],"mappings":";;AAGA,IAAM,MAAM;;;;;;;AAQZ,eAAsB,eAAe,WAA6C,WAA8B,UAAmB,KAA+C;CAChL,MAAM,EAAE,YAAY;CACpB,MAAM,WAAW,UAAU,MAAK,MAAK,EAAE,OAAO,QAAQ,QAAQ;CAC9D,IAAI,CAAC,UAAU,MAAM,IAAI,MAAM,8CAA8C;CAC7E,IAAI,QAAQ,YAAY,QAAQ,WAAW,KAAK,IAAI,SAAS,SAAS,UAAU,KAAA,MAA0B,GAAG,MAAM,IAAI,MAAM,0DAA0D;CACvL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QAAQ,WAAW,MAAA,CAAO,OAAO,MAAM;GAC7D;GAAS,QAAQ,SAAS,YAAY,IAAI,CAAC,QAAQ,OAAO,CAAC,IAAI;GAC/D,aAAa;GAAQ,gBAAgB;GAAe,OAAO;GAAY;EACzE,CAAC;EACD,IAAI,OAAO,SAAS,QAAQ,IAAI,gBAAgB,CAAC,IAAI,UAAU,MAAM,IAAI,MAAM,mCAAmC;EAClH,MAAM,SAAS,SAAS,MAAM,UAAU;EACxC,MAAM,QAAsB,CAAC;EAC7B,IAAI,SAAS;EACb,IAAI,QACF,IAAI;GACF,SAAS;IACP,MAAM,EAAE,MAAM,UAAU,MAAM,OAAO,KAAK;IAC1C,IAAI,MAAM;IACV,UAAU,MAAM;IAChB,IAAI,SAAS,UAAU,MAAM,IAAI,MAAM,mCAAmC;IAC1E,MAAM,KAAK,KAAK;GAClB;EACF,UAAU;GAAE,MAAM,OAAO,OAAO,CAAC,CAAC,YAAY,CAAC,CAAC;EAAG;EAErD,MAAM,QAAQ,IAAI,WAAW,MAAM;EACnC,IAAI,SAAS;EACb,KAAK,MAAM,QAAQ,OAAO;GAAE,MAAM,IAAI,MAAM,MAAM;GAAG,UAAU,KAAK;EAAQ;EAC5E,OAAO;GAAE,QAAQ,SAAS;GAAQ,aAAa,SAAS,QAAQ,IAAI,cAAc,KAAK;GAAI,MAAM,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK;GAAG;EAAM;CAC1I;AACF"}
1
+ {"version":3,"file":"verify-afQj9kHW.js","names":[],"sources":["../../browser/src/proofs/verify.ts"],"sourcesContent":["import { boundVerifiedIdentity, IDENTITY_MAX_EVIDENCE, IDENTITY_MAX_VALIDITY, type IdentityStatement, type VerifiedIdentity } from \"@ghostly/core\";\nimport type { IdentityFetch, IdentityProofProvider, IdentitySigner, VerifyContext } from \"./contract\";\n\nconst DAY = 86_400;\n\n/**\n * The checks every proof goes through, whatever its provider: known provider, validity within the\n * provider's limit, bounded evidence, strict parsing, the provider's own check, and the category rule\n * (a self-custodied proof proves exactly the subject it names; an attested one says who attests it).\n * The engine verifies a contact's proof, and the person's own proof before saving it, only through this.\n */\nexport async function verifyIdentity(providers: readonly IdentityProofProvider[], statement: IdentityStatement, evidence: unknown, ctx: VerifyContext): Promise<VerifiedIdentity> {\n const { binding } = statement;\n const provider = providers.find(p => p.id === binding.provider);\n if (!provider) throw new Error(\"This app cannot verify this kind of identity\");\n if (binding.expiresAt - binding.issuedAt > Math.min(provider.validity.maxDays * DAY, IDENTITY_MAX_VALIDITY)) throw new Error(\"The proof lasts longer than this kind of identity allows\");\n if (JSON.stringify(evidence ?? null).length > IDENTITY_MAX_EVIDENCE) throw new Error(\"Evidence too large\");\n const parsed = provider.parseEvidence(evidence);\n const verified = boundVerifiedIdentity(await provider.verify(statement, parsed, ctx));\n if (provider.category === \"self-custodied\" && verified.subject !== binding.subject) throw new Error(\"The evidence is for another identity\");\n if (provider.category === \"provider-attested\" && !verified.attester) throw new Error(\"The evidence does not say who attests it\");\n return verified;\n}\n\n/** Problems with a provider's descriptor, empty when it is well-formed. The registry and the contract suite use it. */\nexport function descriptorProblems(p: IdentityProofProvider): string[] {\n const problems: string[] = [];\n if (!/^[a-z][a-z0-9-]{0,31}$/.test(p.id)) problems.push(\"id must match ^[a-z][a-z0-9-]{0,31}$\");\n if (!p.label?.trim()) problems.push(\"label is empty\");\n if (!p.description?.trim()) problems.push(\"description is empty\");\n if (!p.privacy?.trim()) problems.push(\"privacy is empty: say what verify contacts\");\n if (p.category !== \"self-custodied\" && p.category !== \"provider-attested\") problems.push(\"category is unknown\");\n if (!p.platforms.length) problems.push(\"no platforms\");\n const { defaultDays, maxDays } = p.validity;\n if (!(Number.isInteger(defaultDays) && Number.isInteger(maxDays) && defaultDays >= 1 && defaultDays <= maxDays && maxDays * DAY <= IDENTITY_MAX_VALIDITY)) problems.push(\"validity must be whole days, 1 ≤ default ≤ max ≤ 400\");\n if (p.recheck && !(Number.isInteger(p.recheck.afterSeconds) && p.recheck.afterSeconds >= 60)) problems.push(\"recheck.afterSeconds must be at least 60\");\n if (!p.signers.length) problems.push(\"no signers\");\n const ids = p.signers.map(s => s.id);\n if (new Set(ids).size !== ids.length) problems.push(\"signer ids are not unique\");\n for (const s of p.signers as readonly IdentitySigner<unknown>[]) {\n if (![\"in-app\", \"external-tool\", \"redirect\", \"publish\"].includes(s.kind)) problems.push(`signer ${s.id} has an unknown kind`);\n if (s.kind === \"in-app\" && typeof s.run !== \"function\") problems.push(`signer ${s.id} has no run()`);\n if (s.kind === \"external-tool\" && (typeof s.instructions !== \"function\" || typeof s.parse !== \"function\")) problems.push(`signer ${s.id} needs instructions() and parse()`);\n if (s.kind === \"redirect\" && typeof s.start !== \"function\") problems.push(`signer ${s.id} has no start()`);\n if (s.kind === \"publish\" && (typeof s.instructions !== \"function\" || typeof s.evidence !== \"function\")) problems.push(`signer ${s.id} needs instructions() and evidence()`);\n }\n return problems;\n}\n\n/** Signers of a provider that run on this platform and are available in this window. */\nexport function availableSigners<E>(p: IdentityProofProvider<E>, platform: IdentityProofProvider[\"platforms\"][number]): IdentitySigner<E>[] {\n return p.signers.filter(s => (s.platforms ?? p.platforms).includes(platform) && (s.available?.() ?? true));\n}\n\n/**\n * The engine's `ctx.fetch`: HTTPS GET only, no credentials or referrer, a time-out, a size cap,\n * redirects refused unless asked for.\n * `online` false refuses everything (the person turned the network off).\n */\nexport function boundedIdentityFetch(options: { online: () => boolean; timeoutMs?: number; fetcher?: typeof fetch } = { online: () => true }): IdentityFetch {\n return async (url, { headers, maxBytes = 64 * 1024, signal, redirect = \"error\" } = {}) => {\n if (!options.online()) throw new Error(\"Offline: this identity cannot be checked now\");\n const target = new URL(url);\n if (target.protocol !== \"https:\" || target.username || target.password) throw new Error(\"Identity checks use HTTPS only\");\n const timeout = AbortSignal.timeout(options.timeoutMs ?? 10_000);\n const response = await (options.fetcher ?? fetch)(target.href, {\n headers, signal: signal ? AbortSignal.any([signal, timeout]) : timeout,\n credentials: \"omit\", referrerPolicy: \"no-referrer\", cache: \"no-store\", redirect,\n });\n if (Number(response.headers.get(\"content-length\")) > maxBytes) throw new Error(\"Identity check response too large\");\n const reader = response.body?.getReader();\n const parts: Uint8Array[] = [];\n let length = 0;\n if (reader) {\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n length += value.length;\n if (length > maxBytes) throw new Error(\"Identity check response too large\");\n parts.push(value);\n }\n } finally { await reader.cancel().catch(() => {}); }\n }\n const bytes = new Uint8Array(length);\n let offset = 0;\n for (const part of parts) { bytes.set(part, offset); offset += part.length; }\n return { status: response.status, contentType: response.headers.get(\"content-type\") ?? \"\", text: new TextDecoder().decode(bytes), bytes };\n };\n}\n"],"mappings":";;AAGA,IAAM,MAAM;;;;;;;AAQZ,eAAsB,eAAe,WAA6C,WAA8B,UAAmB,KAA+C;CAChL,MAAM,EAAE,YAAY;CACpB,MAAM,WAAW,UAAU,MAAK,MAAK,EAAE,OAAO,QAAQ,QAAQ;CAC9D,IAAI,CAAC,UAAU,MAAM,IAAI,MAAM,8CAA8C;CAC7E,IAAI,QAAQ,YAAY,QAAQ,WAAW,KAAK,IAAI,SAAS,SAAS,UAAU,KAAA,MAA0B,GAAG,MAAM,IAAI,MAAM,0DAA0D;CACvL,IAAI,KAAK,UAAU,YAAY,IAAI,CAAC,CAAC,SAAA,OAAgC,MAAM,IAAI,MAAM,oBAAoB;CACzG,MAAM,SAAS,SAAS,cAAc,QAAQ;CAC9C,MAAM,WAAW,sBAAsB,MAAM,SAAS,OAAO,WAAW,QAAQ,GAAG,CAAC;CACpF,IAAI,SAAS,aAAa,oBAAoB,SAAS,YAAY,QAAQ,SAAS,MAAM,IAAI,MAAM,sCAAsC;CAC1I,IAAI,SAAS,aAAa,uBAAuB,CAAC,SAAS,UAAU,MAAM,IAAI,MAAM,0CAA0C;CAC/H,OAAO;AACT;;AAGA,SAAgB,mBAAmB,GAAoC;CACrE,MAAM,WAAqB,CAAC;CAC5B,IAAI,CAAC,yBAAyB,KAAK,EAAE,EAAE,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U,MAAM,IAAI,MAAM,mCAAmC;IAC1E,MAAM,KAAK,KAAK;GAClB;EACF,UAAU;GAAE,MAAM,OAAO,OAAO,CAAC,CAAC,YAAY,CAAC,CAAC;EAAG;EAErD,MAAM,QAAQ,IAAI,WAAW,MAAM;EACnC,IAAI,SAAS;EACb,KAAK,MAAM,QAAQ,OAAO;GAAE,MAAM,IAAI,MAAM,MAAM;GAAG,UAAU,KAAK;EAAQ;EAC5E,OAAO;GAAE,QAAQ,SAAS;GAAQ,aAAa,SAAS,QAAQ,IAAI,cAAc,KAAK;GAAI,MAAM,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK;GAAG;EAAM;CAC1I;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ghostlytools/sdk",
3
- "version": "1.2.3",
3
+ "version": "1.3.0",
4
4
  "type": "module",
5
5
  "description": "Build a wallet source, an identity proof, a mini-app or a client for Ghostly without reading its internals: the adapter contracts, their fakes and contract test suites, the plugin registry, and the mini-app API types (Apps run in Ghostly 1.2 and later).",
6
6
  "license": "MIT",