@solarpunkltd/swarm-id 0.8.0 → 0.8.2

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.
package/dist/schemas.d.ts CHANGED
@@ -59,6 +59,8 @@ export declare const ChatBindingSchema: z.ZodObject<{
59
59
  message: z.ZodString;
60
60
  signature: z.ZodString;
61
61
  }, z.core.$strip>;
62
+ /** The stamp choice of an app the person set to use no stamp at all */
63
+ export declare const NO_POSTAGE_STAMP = "none";
62
64
  /**
63
65
  * Connected App Schema V1.
64
66
  *
@@ -73,8 +75,9 @@ export declare const ConnectedAppSchemaV1: z.ZodObject<{
73
75
  appDescription: z.ZodOptional<z.ZodString>;
74
76
  connectedUntil: z.ZodOptional<z.ZodNumber>;
75
77
  appSecret: z.ZodOptional<z.ZodString>;
76
- postageStampBatchID: z.ZodOptional<z.ZodPipe<z.ZodString, z.ZodTransform<BeeBatchId, string>>>;
78
+ postageStampBatchID: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"none">, z.ZodPipe<z.ZodString, z.ZodTransform<BeeBatchId, string>>]>>;
77
79
  postageStampBatchIDAt: z.ZodOptional<z.ZodNumber>;
80
+ stampPending: z.ZodOptional<z.ZodLiteral<true>>;
78
81
  revokedAt: z.ZodOptional<z.ZodNumber>;
79
82
  disconnectedAt: z.ZodOptional<z.ZodNumber>;
80
83
  chatBinding: z.ZodOptional<z.ZodObject<{
@@ -202,8 +205,9 @@ export declare const SyncedAccountSchemaV1: z.ZodObject<{
202
205
  appDescription: z.ZodOptional<z.ZodString>;
203
206
  connectedUntil: z.ZodOptional<z.ZodNumber>;
204
207
  appSecret: z.ZodOptional<z.ZodString>;
205
- postageStampBatchID: z.ZodOptional<z.ZodPipe<z.ZodString, z.ZodTransform<BeeBatchId, string>>>;
208
+ postageStampBatchID: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"none">, z.ZodPipe<z.ZodString, z.ZodTransform<BeeBatchId, string>>]>>;
206
209
  postageStampBatchIDAt: z.ZodOptional<z.ZodNumber>;
210
+ stampPending: z.ZodOptional<z.ZodLiteral<true>>;
207
211
  revokedAt: z.ZodOptional<z.ZodNumber>;
208
212
  disconnectedAt: z.ZodOptional<z.ZodNumber>;
209
213
  chatBinding: z.ZodOptional<z.ZodObject<{
@@ -268,8 +272,9 @@ declare const SignedInAccountSchemaV1: z.ZodObject<{
268
272
  appDescription: z.ZodOptional<z.ZodString>;
269
273
  connectedUntil: z.ZodOptional<z.ZodNumber>;
270
274
  appSecret: z.ZodOptional<z.ZodString>;
271
- postageStampBatchID: z.ZodOptional<z.ZodPipe<z.ZodString, z.ZodTransform<BeeBatchId, string>>>;
275
+ postageStampBatchID: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"none">, z.ZodPipe<z.ZodString, z.ZodTransform<BeeBatchId, string>>]>>;
272
276
  postageStampBatchIDAt: z.ZodOptional<z.ZodNumber>;
277
+ stampPending: z.ZodOptional<z.ZodLiteral<true>>;
273
278
  revokedAt: z.ZodOptional<z.ZodNumber>;
274
279
  disconnectedAt: z.ZodOptional<z.ZodNumber>;
275
280
  chatBinding: z.ZodOptional<z.ZodObject<{
@@ -392,8 +397,9 @@ export declare const LocalAccountSchemaV1: z.ZodUnion<readonly [z.ZodObject<{
392
397
  appDescription: z.ZodOptional<z.ZodString>;
393
398
  connectedUntil: z.ZodOptional<z.ZodNumber>;
394
399
  appSecret: z.ZodOptional<z.ZodString>;
395
- postageStampBatchID: z.ZodOptional<z.ZodPipe<z.ZodString, z.ZodTransform<BeeBatchId, string>>>;
400
+ postageStampBatchID: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"none">, z.ZodPipe<z.ZodString, z.ZodTransform<BeeBatchId, string>>]>>;
396
401
  postageStampBatchIDAt: z.ZodOptional<z.ZodNumber>;
402
+ stampPending: z.ZodOptional<z.ZodLiteral<true>>;
397
403
  revokedAt: z.ZodOptional<z.ZodNumber>;
398
404
  disconnectedAt: z.ZodOptional<z.ZodNumber>;
399
405
  chatBinding: z.ZodOptional<z.ZodObject<{
@@ -528,8 +534,9 @@ export declare const AccountStateSnapshotSchemaV1: z.ZodObject<{
528
534
  appDescription: z.ZodOptional<z.ZodString>;
529
535
  connectedUntil: z.ZodOptional<z.ZodNumber>;
530
536
  appSecret: z.ZodOptional<z.ZodString>;
531
- postageStampBatchID: z.ZodOptional<z.ZodPipe<z.ZodString, z.ZodTransform<BeeBatchId, string>>>;
537
+ postageStampBatchID: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"none">, z.ZodPipe<z.ZodString, z.ZodTransform<BeeBatchId, string>>]>>;
532
538
  postageStampBatchIDAt: z.ZodOptional<z.ZodNumber>;
539
+ stampPending: z.ZodOptional<z.ZodLiteral<true>>;
533
540
  revokedAt: z.ZodOptional<z.ZodNumber>;
534
541
  disconnectedAt: z.ZodOptional<z.ZodNumber>;
535
542
  chatBinding: z.ZodOptional<z.ZodObject<{
@@ -632,6 +639,12 @@ export declare const NetworkSettingsSchemaV1: z.ZodObject<{
632
639
  gnosisRpcUrl: z.ZodString;
633
640
  }, z.core.$strip>;
634
641
  export type NetworkSettings = z.infer<typeof NetworkSettingsSchemaV1>;
642
+ /**
643
+ * A Bee address a site gives the frame for its own session (`beeApiUrl` on
644
+ * `parentIdentify` and `setBeeApiUrl`). Never stored: it lives in the frame
645
+ * that site embeds, and only while it is open.
646
+ */
647
+ export declare const BeeApiUrlSchema: z.ZodString;
635
648
  /**
636
649
  * Bucket update entry for cross-tab synchronization
637
650
  */
@@ -48,6 +48,7 @@ export declare class SwarmIdClient {
48
48
  private buttonConfig?;
49
49
  private containerId?;
50
50
  private subsidisedGatewayUrl?;
51
+ private beeApiUrl?;
51
52
  private ready;
52
53
  /**
53
54
  * Whether the proxy iframe can read the trusted domain's first-party store,
@@ -95,8 +96,10 @@ export declare class SwarmIdClient {
95
96
  * @param options.buttonConfig.fontSize - CSS font-size for the button; the default floating iframe is a fixed 300x50 px and hides its overflow, so a size that does not fit is clipped — pass `containerId` to own the box (optional)
96
97
  * @param options.buttonConfig.fontWeight - CSS font-weight for the button, as a keyword or a number (optional)
97
98
  * @param options.containerId - ID of container element to place iframe in (optional)
99
+ * @param options.subsidisedGatewayUrl - A gateway that stamps uploads for a person with no drive of their own (optional)
100
+ * @param options.beeApiUrl - The Bee node this site's content reads and stamped uploads go through, in place of the person's own setting. Their account and device coordination stay on their own node. Change it later with {@link setBeeApiUrl} (optional)
98
101
  * @throws {Error} If constructed where there is no `window` (a server render)
99
- * @throws {SwarmIdError} `invalid-request` if the provided app metadata is invalid
102
+ * @throws {SwarmIdError} `invalid-request` if the provided app metadata is invalid, or `beeApiUrl` is not an http(s) URL without credentials, query or fragment
100
103
  */
101
104
  constructor(options: ClientOptions);
102
105
  /**
@@ -194,6 +197,7 @@ export declare class SwarmIdClient {
194
197
  * @returns A promise resolving to the authentication status object
195
198
  * @returns return.authenticated - Whether the user is currently authenticated
196
199
  * @returns return.origin - The origin that authenticated (if authenticated)
200
+ * @returns return.beeApiUrl - The Bee node this site gave, if it gave one. The person's own node is never reported
197
201
  * @throws {Error} If the client is not initialized
198
202
  * @throws {Error} If the request times out
199
203
  *
@@ -206,6 +210,31 @@ export declare class SwarmIdClient {
206
210
  * ```
207
211
  */
208
212
  checkAuthStatus(): Promise<AuthStatus>;
213
+ /**
214
+ * Changes the Bee node this site's content reads and stamped uploads go
215
+ * through, without a reload, for example when the viewer picks another source. It
216
+ * replaces the `beeApiUrl` given at construction, and takes over from the
217
+ * person's own Bee setting on this site if none was given. Every other site,
218
+ * and Swarm ID itself, keep the person's setting. The checks and writes
219
+ * that coordinate the person's account and devices always use their own
220
+ * node. Nothing is stored: the next page load starts from the
221
+ * constructor's `beeApiUrl` again.
222
+ *
223
+ * Works signed in or not. A subsidised gateway the person's own custom node
224
+ * had switched off comes back once the site names its node.
225
+ *
226
+ * @param url - An http(s) URL, optionally with a path, without credentials, query or fragment
227
+ * @throws {SwarmIdError} `invalid-request` if `url` is not such a URL, and nothing is sent
228
+ * @throws {SwarmIdError} `invalid-state` if the client is not initialized
229
+ * @throws {SwarmIdError} `timeout` if the request times out
230
+ *
231
+ * @example
232
+ * ```typescript
233
+ * await client.setBeeApiUrl('https://bee.example.com/')
234
+ * console.log(client.connectionInfo.beeApiUrl)
235
+ * ```
236
+ */
237
+ setBeeApiUrl(url: string): Promise<void>;
209
238
  /**
210
239
  * Gets the current postage batch for the authenticated identity.
211
240
  *
@@ -48,6 +48,14 @@ export declare class SwarmIdProxy {
48
48
  private stampWorkerPool;
49
49
  private storagePartitioned;
50
50
  private pendingChallenge;
51
+ /**
52
+ * The challenge of the connect window whose handover this session came
53
+ * from. That window asks for the site's stamp after it handed over, and a
54
+ * stamp picked there reaches this frame as a second handover under the same
55
+ * challenge (`isStampHandover`). Cleared when another window opens or the
56
+ * session ends, so only the newest window can do it.
57
+ */
58
+ private handedOverChallenge;
51
59
  /**
52
60
  * Hydrated account view for the storage-partitioning fallback: the synced
53
61
  * projection handed over by the connect popup (`AuthData.account`), held in
@@ -100,7 +108,22 @@ export declare class SwarmIdProxy {
100
108
  */
101
109
  private lastRestampMs;
102
110
  private utilizationStore;
103
- private beeApiUrl;
111
+ /** The Bee node the person set in Swarm ID's network settings. */
112
+ private ownBeeApiUrl;
113
+ /**
114
+ * The Bee node the embedding site named for its own session, from
115
+ * `parentIdentify` or `setBeeApiUrl`. In memory only: a frame
116
+ * serves the one parent origin it was identified by, so this is that
117
+ * site's alone, and nothing writes it to storage, the account or a sync
118
+ * feed. The site sends it again on every load.
119
+ */
120
+ private siteBeeApiUrl;
121
+ /**
122
+ * The subsidised gateway the site asked for, kept apart from
123
+ * `subsidisedGatewayUrl`, which the person's own custom node can switch
124
+ * off, so the gateway can come back once the site names its own node.
125
+ */
126
+ private siteSubsidisedGatewayUrl;
104
127
  private gnosisRpcUrl;
105
128
  private postageStampContractAddress;
106
129
  private signalingUrl;
@@ -109,11 +132,10 @@ export declare class SwarmIdProxy {
109
132
  private popupMode;
110
133
  private appMetadata;
111
134
  /**
112
- * The last Bee client built, with the URL it was asked for. Keyed on that
113
- * input URL, not on the client's own `url`, which bee-js keeps without the
114
- * trailing slash.
135
+ * Bee clients by the URL they were asked for. Keyed on that input URL, not
136
+ * on the client's own `url`, which bee-js keeps without the trailing slash.
115
137
  */
116
- private beeClient;
138
+ private beeClients;
117
139
  private unsubscribeStorageListeners;
118
140
  private storageWorkQueue;
119
141
  private lastConnectionInfo;
@@ -135,6 +157,21 @@ export declare class SwarmIdProxy {
135
157
  private stamperInitGeneration;
136
158
  /** Why the session refuses to stamp with the resolved drive, if it does. */
137
159
  private get stampRefusal();
160
+ /**
161
+ * The node the site's own content goes through: the site's address when it
162
+ * named one, the person's setting otherwise. Content only, the reads and
163
+ * stamped uploads the site asks for. Nothing that decides whether this
164
+ * session may write, or that coordinates the person's devices, reads it
165
+ * (`accountBee`), because a site could answer those from a node of its own.
166
+ */
167
+ private get beeApiUrl();
168
+ /**
169
+ * Switch off the site's subsidised gateway when the node in effect is the
170
+ * person's own custom one, so their uploads go to the node they chose. A
171
+ * node the site named is not the person's choice, and the site asked for
172
+ * both, so it keeps the gateway.
173
+ */
174
+ private dropGatewayForOwnCustomNode;
138
175
  /**
139
176
  * The client for the node the current mode writes to: the dApp's gateway
140
177
  * while the session is subsidised, the configured node otherwise. Reads have
@@ -149,14 +186,24 @@ export declare class SwarmIdProxy {
149
186
  */
150
187
  private get bee();
151
188
  /**
152
- * The client for the configured node, whatever the mode. The coordinator
153
- * writes there, and only there: it runs in user-stamp mode alone, and a
154
- * refused drive (expired, unusable) keeps one while `bee` points at the
155
- * gateway. What it writes — the roster, this device's state — is read back
156
- * through this client too.
189
+ * The client for the site's content node, whatever the mode: where the
190
+ * site's stamped uploads go in user-stamp mode, which `bee` also reads from
191
+ * then.
157
192
  */
158
193
  private get nodeBee();
159
- /** A client for `url`, rebuilt only when the URL differs from the last. */
194
+ /**
195
+ * The client for the person's own node, whatever the site named. The
196
+ * coordinator's lock, lease and state chunks, the device roster and the
197
+ * restored session's revocation check go through it: they decide what this
198
+ * session may do with the person's account and stamp, so the embedding
199
+ * site must not be able to answer them.
200
+ */
201
+ private get accountBee();
202
+ /**
203
+ * A client for `url`, kept per URL so the content, account and gateway
204
+ * clients do not rebuild each other. Bounded, because a site can name a
205
+ * new address at any time.
206
+ */
160
207
  private beeClientFor;
161
208
  /**
162
209
  * The write path (lock + partition lease + stamp flush) for the current
@@ -295,6 +342,18 @@ export declare class SwarmIdProxy {
295
342
  * Used as storage partitioning fallback when storage events don't fire due to partitioning.
296
343
  */
297
344
  private handlePopupMessage;
345
+ /**
346
+ * A second handover from the window this session was handed over by,
347
+ * carrying the stamp the person picked there after the first one. Accepted
348
+ * only for that window's challenge, this parent and this session's secret,
349
+ * so it can move the open session to the stamp the person picked and to
350
+ * nothing else: not another account, not another site, not a session that
351
+ * has ended. Which stamp it is was decided in that window, from the
352
+ * account's own record.
353
+ */
354
+ private isStampHandover;
355
+ /** Authenticate in storage-partitioned mode from a checked handover */
356
+ private adoptHandover;
298
357
  /**
299
358
  * End the connect attempt a refused handover belonged to.
300
359
  *
@@ -916,6 +975,15 @@ export declare class SwarmIdProxy {
916
975
  * it the app secret itself never leaves the frame.
917
976
  */
918
977
  private handleGetChatKey;
978
+ /**
979
+ * The site names a new Bee node for its session, as the source its viewer
980
+ * picked changes. Needs no sign-in: it says where this site's reads go,
981
+ * which is the site's to decide whether or not anyone is connected.
982
+ *
983
+ * The site naming its node also brings back a subsidised gateway the
984
+ * person's own custom node had switched off (`dropGatewayForOwnCustomNode`).
985
+ */
986
+ private handleSetBeeApiUrl;
919
987
  /**
920
988
  * Stamp a chunk with the account's own stamp and hand the stamp back, for
921
989
  * the app to send through its own Swarm access. The stamp takes the same
@@ -1,2 +1,2 @@
1
- import{A as t,S as n,I as r,P as o,a,u as d,T as c,b as u,g as h,E as y,c as w,w as R,d as g,h as I,M as q,N as x,R as z}from"./chunks/chat-binding-DlH_ZkTn.js";export{C as CHAT_BINDING_TITLE,D as DEFAULT_BEE_NODE_URL,k as acceptedChatBinding,l as buildChatBindingMessage,f as formatTTL,e as generatedAvatarSvg,m as isCleanSiteOrigin,i as jsonRpcBatch,j as jsonRpcCall,p as parseChatBindingMessage,s as saveMantarayTreeRecursively,v as verifyChatBinding}from"./chunks/chat-binding-DlH_ZkTn.js";function F(e){const t=e.webkitRelativePath;return t?t.replace(/^[^/]*\//,""):e.name}function b(e,t,i){return R(e,t,i).catch(e=>{throw e instanceof g?new n("init-failed",e.message,{cause:e}):e})}class T{constructor(e){if(this.ready=!1,this.pendingRequests=new Map,this.progressListeners=new Map,this.requestIdCounter=0,"undefined"==typeof window)throw new Error("@solarpunkltd/swarm-id runs in the browser only: construct SwarmIdClient in code that runs there (an effect, onMount, or behind `typeof window !== 'undefined'`), not in a server render");this.iframeOrigin=e.iframeOrigin,this.iframePath=e.iframePath||"/proxy",this.timeout=e.timeout??3e4,this.initializationTimeout=e.initializationTimeout??3e4,this.onConnectionChange=e.onConnectionChange,this.popupMode=e.popupMode||"window",this.metadata=e.metadata,this.buttonConfig=e.buttonConfig,this.containerId=e.containerId,this.subsidisedGatewayUrl=e.subsidisedGatewayUrl;try{t.parse(this.metadata)}catch(e){throw new n("invalid-request",`Invalid app metadata: ${e}`,{cause:e})}this.setupMessageListener()}async initialize(){if(this.iframe)throw new n("invalid-state","SwarmIdClient already initialized");let e;if(this.firstConnectionInfoPromise=b(new Promise((e,t)=>{this.firstConnectionInfoResolve=e,this.firstConnectionInfoReject=t}),this.initializationTimeout,`Proxy initialization timeout - proxy did not send initial connectionInfoChanged within ${this.initializationTimeout}ms`),this.firstConnectionInfoPromise.catch(()=>{}),this.proxyInitializedPromise=b(new Promise((e,t)=>{this.proxyInitializedResolve=e,this.proxyInitializedReject=t}),this.initializationTimeout,`Proxy initialization timeout - proxy did not signal readiness within ${this.initializationTimeout}ms`),this.proxyInitializedPromise.catch(()=>{}),this.readyPromise=b(new Promise((e,t)=>{this.readyResolve=e,this.readyReject=t}),this.initializationTimeout,`Proxy initialization timeout - proxy did not respond within ${this.initializationTimeout}ms`),this.readyPromise.catch(()=>{}),this.iframe=document.createElement("iframe"),this.iframe.src=`${this.iframeOrigin}${this.iframePath}`,this.iframe.style.border="none",this.iframe.style.backgroundColor="transparent",this.iframe.style.borderRadius=this.buttonConfig?.borderRadius||"0",this.containerId){if(e=document.getElementById(this.containerId)||void 0,!e)throw new n("invalid-request",`Container element with ID "${this.containerId}" not found`);this.iframe.style.width="100%",this.iframe.style.height="100%",this.iframe.style.display="block"}else this.iframe.style.display="none",this.iframe.style.position="fixed",this.iframe.style.bottom="20px",this.iframe.style.right="20px",this.iframe.style.width="300px",this.iframe.style.height="50px",this.iframe.style.zIndex="999999";await new Promise((t,i)=>{this.iframeLoadReject=i,this.iframe.onload=()=>t(),this.iframe.onerror=()=>i(new n("init-failed","Failed to load Swarm ID iframe")),e?e.appendChild(this.iframe):document.body.appendChild(this.iframe)}),this.iframeLoadReject=void 0,await this.proxyInitializedPromise,this.sendMessage({type:"parentIdentify",requestId:this.generateRequestId(),popupMode:this.popupMode,metadata:this.metadata,buttonConfig:this.buttonConfig,subsidisedGatewayUrl:this.subsidisedGatewayUrl}),await this.readyPromise,await this.firstConnectionInfoPromise}setupMessageListener(){this.messageListener=e=>{if(!this.iframe||e.source!==this.iframe.contentWindow)return;if("proxyInitialized"===e.data?.type)return void(this.proxyInitializedResolve&&(this.proxyInitializedResolve(),this.proxyInitializedResolve=void 0));const t=new URL(this.iframeOrigin).origin;if(e.origin!==t)return void console.warn("[SwarmIdClient] Rejected message from unauthorized origin:",e.origin);let i;try{i=r.parse(e.data)}catch(t){return void console.warn("[SwarmIdClient] Invalid message format:",e.data,t)}this.handleIframeMessage(i)},window.addEventListener("message",this.messageListener)}handleIframeMessage(e){switch(e.type){case"proxyReady":this.ready=!0,this.storageShared=e.storageShared,this.readyResolve&&this.readyResolve(),this.iframe&&(this.iframe.style.display="block");break;case"authStatusResponse":if(this.iframe&&(this.iframe.style.display="block"),"requestId"in e){const t=this.pendingRequests.get(e.requestId);t&&(clearTimeout(t.timeoutId),this.pendingRequests.delete(e.requestId),t.resolve(e))}break;case"authSuccess":this.iframe&&(this.iframe.style.display="block");break;case"connectionInfoChanged":{const t={canUpload:e.canUpload,storagePartitioned:e.storagePartitioned,uploadMode:e.uploadMode,uploadUnavailableReason:e.uploadUnavailableReason,identity:e.identity,appKey:e.appKey,partition:e.partition,chatBinding:e.chatBinding};this.lastConnectionInfo=t,this.firstConnectionInfoResolve&&(this.firstConnectionInfoResolve(),this.firstConnectionInfoResolve=void 0),this.onConnectionChange&&this.onConnectionChange(t);break}case"initError":console.error("[SwarmIdClient] Proxy initialization error:",e.error),this.readyReject&&this.readyReject(new n("init-failed",e.error));break;case"disconnectResponse":if("requestId"in e){const t=this.pendingRequests.get(e.requestId);t&&(clearTimeout(t.timeoutId),this.pendingRequests.delete(e.requestId),t.resolve(e))}break;case"error":{const t=this.pendingRequests.get(e.requestId);t&&(clearTimeout(t.timeoutId),this.pendingRequests.delete(e.requestId),t.reject(n.fromWire(e)));break}case"uploadProgress":this.progressListeners.get(e.requestId)?.({total:e.total,processed:e.processed});break;default:if("requestId"in e){const t=this.pendingRequests.get(e.requestId);t&&(clearTimeout(t.timeoutId),this.pendingRequests.delete(e.requestId),t.resolve(e))}}}sendMessage(e){if(!this.iframe||!this.iframe.contentWindow)throw new n("invalid-state","Iframe not initialized");try{o.parse(e)}catch(e){throw new n("invalid-request",`Invalid message format: ${e}`,{cause:e})}this.iframe.contentWindow.postMessage(e,this.iframeOrigin)}async sendRequest(e){const t=this.roundTripTimeout(e.requestOptions?.timeout);return new Promise((i,s)=>{const r=setTimeout(()=>{this.pendingRequests.delete(e.requestId),s(new n("timeout",`Request timeout after ${t}ms`))},t);this.pendingRequests.set(e.requestId,{resolve:i,reject:s,timeoutId:r}),this.sendMessage(e)})}roundTripTimeout(e){return void 0===e||e<=0?this.timeout:Math.min(e,2147483647)}generateRequestId(){return`req-${++this.requestIdCounter}-${Date.now()}`}normalizeSocIdentifier(e){return e instanceof a?e.toHex():e instanceof Uint8Array?d(e):e}normalizeSocKey(e){return e instanceof Uint8Array?d(e):e}normalizeFeedTopic(e){return e instanceof c?d(e.toUint8Array()):e instanceof a?e.toHex():e instanceof Uint8Array?d(e):e}normalizeReference(e){return e instanceof Uint8Array?d(e):e}normalizeFeedTimestamp(e){return"bigint"==typeof e?e.toString():"number"==typeof e?BigInt(Math.floor(e)).toString():e}normalizeFeedIndex(e){return"bigint"==typeof e?e.toString():"number"==typeof e?BigInt(Math.floor(e)).toString():e}normalizePayload(e){return e instanceof Uint8Array?e:(new TextEncoder).encode(e)}socChunkFromResponse(e){return{data:e.data,identifier:e.identifier,signature:e.signature,span:e.span,payload:e.payload,address:e.address,owner:e.owner}}ensureReady(){if(!this.ready)throw new n("invalid-state","SwarmIdClient not initialized. Call initialize() first.")}getAuthIframe(){if(this.ensureReady(),!this.iframe)throw new n("invalid-state","Iframe not initialized");return this.iframe}async checkAuthStatus(){this.ensureReady();const e=this.generateRequestId(),t=await this.sendRequest({type:"checkAuth",requestId:e});return{authenticated:t.authenticated,origin:t.origin,beeApiUrl:t.beeApiUrl}}async getPostageBatch(){this.ensureReady();const e=this.generateRequestId();return(await this.sendRequest({type:"getPostageBatch",requestId:e})).postageBatch}async disconnect(){this.ensureReady();const e=this.generateRequestId();if(!(await this.sendRequest({type:"disconnect",requestId:e})).success)throw new n("internal","Failed to disconnect")}async connect(e={}){if(this.ensureReady(),!0===this.storageShared){if(!this.openAuthWindow(e))throw new n("popup-blocked","Failed to open authentication popup");return}const t=this.generateRequestId();if(!(await this.sendRequest({type:"connect",requestId:t,popupMode:e.popupMode})).success&&!this.openAuthWindow(e))throw new n("popup-blocked","Failed to open authentication popup")}openAuthWindow(e){const t=this.iframePath.replace(/\/proxy$/,""),i=u(this.iframeOrigin+t,window.location.origin,this.metadata),n="popup"===(e.popupMode??this.popupMode)?window.open(i,"_blank","width=500,height=600"):window.open(i,"_blank");return Boolean(n)}get connectionInfo(){if(this.ensureReady(),!this.lastConnectionInfo)throw new n("invalid-state","SwarmIdClient connectionInfo not yet available.");return this.lastConnectionInfo}async getAvatar(e={}){const{identity:t}=this.connectionInfo;if(t)return void 0!==e.size&&"generated"===t.avatar.source?h(t.id,e.size):t.avatar}async isBeeConnected(){try{this.ensureReady();const e=this.generateRequestId();return(await this.sendRequest({type:"isConnected",requestId:e})).connected}catch{return!1}}async getNodeInfo(){this.ensureReady();const e=this.generateRequestId(),t=await this.sendRequest({type:"getNodeInfo",requestId:e});return{beeMode:t.beeMode,chequebookEnabled:t.chequebookEnabled,swapEnabled:t.swapEnabled}}async uploadData(e,t,i){this.ensureReady();const n=this.generateRequestId(),{onProgress:s,useWebSocket:r,useWorkers:o,workerCount:a,concurrency:d,...c}=t??{},u=this.listenForProgress(n,s);try{const t=await this.sendRequest({type:"uploadData",requestId:n,data:new Uint8Array(e),options:c,requestOptions:i,enableProgress:!!s,useWebSocket:r,useWorkers:o,workerCount:a,concurrency:d});return{reference:t.reference,tagUid:t.tagUid}}finally{u()}}async downloadData(e,t,i){this.ensureReady();const n=this.generateRequestId();return(await this.sendRequest({type:"downloadData",requestId:n,reference:e,options:t,requestOptions:i})).data}async deriveAppSecret(e){this.ensureReady();const t=this.generateRequestId();return(await this.sendRequest({type:"deriveAppSecret",requestId:t,label:e})).secret}async getChatKey(){this.ensureReady();const e=this.generateRequestId();return(await this.sendRequest({type:"getChatKey",requestId:e})).chatKey}async stampChunk(e){this.ensureReady();const t=this.generateRequestId(),i="soc"===e.kind?{...e,identifier:this.normalizeSocIdentifier(e.identifier),signer:"app"===e.signer?e.signer:{...e.signer,privateKey:this.normalizeSocKey(e.signer.privateKey)}}:e,n=await this.sendRequest({type:"stampChunk",requestId:t,chunk:i});return{address:n.address,stamp:n.stamp,...void 0!==n.owner&&{owner:n.owner},...void 0!==n.signature&&{signature:n.signature}}}async uploadFile(e,t,i,n){this.ensureReady();const s=this.generateRequestId(),{onProgress:r,useWebSocket:o,useWorkers:a,workerCount:d,concurrency:c,...u}=i??{};let h,p=t;if(e instanceof File){const t=await e.arrayBuffer();h=new Uint8Array(t),p=p||e.name}else h=new Uint8Array(e.buffer.slice(0),e.byteOffset,e.byteLength);const y=this.listenForProgress(s,r);try{const e=await this.sendRequest({type:"uploadFile",requestId:s,data:h,name:p,options:u,requestOptions:n,enableProgress:!!r,useWebSocket:o,useWorkers:a,workerCount:d,concurrency:c});return{reference:e.reference,tagUid:e.tagUid}}finally{y()}}async downloadFile(e,t,i,n){this.ensureReady();const s=this.generateRequestId(),r=await this.sendRequest({type:"downloadFile",requestId:s,reference:e,path:t,options:i,requestOptions:n});return{name:r.name,data:new Uint8Array(r.data)}}async uploadFiles(e,t,i){this.ensureReady();const n=this.generateRequestId(),{onProgress:s,useWorkers:r,workerCount:o,...a}=t??{},d=await Promise.all(Array.from(e,async e=>{const{path:t,file:i}=e instanceof File?{path:F(e),file:e}:e;return{path:t,data:new Uint8Array(await i.arrayBuffer()),contentType:i.type||void 0}})),c=this.listenForProgress(n,s);try{const e=await this.sendRequest({type:"uploadFiles",requestId:n,files:d,options:a,requestOptions:i,enableProgress:!!s,useWorkers:r,workerCount:o});return{reference:e.reference,tagUid:e.tagUid}}finally{c()}}async listFiles(e,t){this.ensureReady();const i=this.generateRequestId();return(await this.sendRequest({type:"listFiles",requestId:i,reference:e,requestOptions:t})).entries}listenForProgress(e,t){return t?(this.progressListeners.set(e,t),()=>{this.progressListeners.delete(e)}):()=>{}}async uploadChunk(e,t,i){this.ensureReady();const n=this.generateRequestId(),{onProgress:s,...r}=t??{};return{reference:(await this.sendRequest({type:"uploadChunk",requestId:n,data:e,options:r,requestOptions:i})).reference}}async downloadChunk(e,t,i){this.ensureReady();const n=this.generateRequestId(),s=await this.sendRequest({type:"downloadChunk",requestId:n,reference:e,options:t,requestOptions:i});return new Uint8Array(s.data)}makeSOCReader(e,t){this.ensureReady();const i=new y(e).toHex(),n=async(e,n)=>{const s=this.generateRequestId(),r=await this.sendRequest({type:"socDownload",requestId:s,owner:i,identifier:this.normalizeSocIdentifier(e),encryptionKey:this.normalizeSocKey(n),requestOptions:t});return this.socChunkFromResponse(r)},s=async(e,n)=>{const s=this.generateRequestId(),r=await this.sendRequest({type:"socRawDownload",requestId:s,owner:i,identifier:this.normalizeSocIdentifier(e),encryptionKey:n?this.normalizeSocKey(n):void 0,requestOptions:t});return this.socChunkFromResponse(r)};return{getOwner:async()=>i,rawDownload:(e,t)=>s(e,t),download:(e,t)=>n(e,t)}}makeSOCWriter(e,t){this.ensureReady();const i=e?new w(e):void 0,n=i?i.toHex():void 0;let s=i?i.publicKey().address().toHex():void 0;const r=async(e,i)=>{const n=this.generateRequestId(),r=await this.sendRequest({type:"socDownload",requestId:n,owner:s,identifier:this.normalizeSocIdentifier(e),encryptionKey:this.normalizeSocKey(i),requestOptions:t});return this.socChunkFromResponse(r)},o=async(e,i)=>{const n=this.generateRequestId(),r=await this.sendRequest({type:"socRawDownload",requestId:n,owner:s,identifier:this.normalizeSocIdentifier(e),encryptionKey:i?this.normalizeSocKey(i):void 0,requestOptions:t});return this.socChunkFromResponse(r)},a=async(e,i,r)=>{const o=this.generateRequestId(),a=await this.sendRequest({type:"socUpload",requestId:o,identifier:this.normalizeSocIdentifier(e),data:new Uint8Array(i),signer:n,options:r,requestOptions:t});return s=a.owner,{reference:a.reference,tagUid:a.tagUid,encryptionKey:a.encryptionKey,owner:a.owner}},d=async(e,i,r)=>{const o=this.generateRequestId(),a=await this.sendRequest({type:"socRawUpload",requestId:o,identifier:this.normalizeSocIdentifier(e),data:new Uint8Array(i),signer:n,options:r,requestOptions:t});return s=a.owner,{reference:a.reference,tagUid:a.tagUid,encryptionKey:a.encryptionKey,owner:a.owner}};return{getOwner:async()=>{if(s)return s;const e=this.generateRequestId(),t=await this.sendRequest({type:"socGetOwner",requestId:e});return s=t.owner,s},rawDownload:(e,t)=>o(e,t),download:(e,t)=>r(e,t),upload:(e,t,i)=>a(e,t,i),rawUpload:(e,t,i)=>d(e,t,i)}}makeEpochFeedReader(e,t){this.ensureReady();const i=this.normalizeFeedTopic(e.topic);let n=e.owner?new y(e.owner).toHex():void 0;const s=async e=>{const s=void 0!==e?.at?e.at:BigInt(Math.floor(Date.now()/1e3)),r=this.generateRequestId(),o=(await this.sendRequest({type:"epochFeedDownloadReference",requestId:r,topic:i,owner:n,at:this.normalizeFeedTimestamp(s),after:void 0!==e?.after?this.normalizeFeedTimestamp(e.after):void 0,encryptionKey:void 0!==e?.encryptionKey?this.normalizeSocKey(e.encryptionKey):void 0,requestOptions:t})).reference,a=o&&o.startsWith("0x")?o.slice(2):o;return{reference:o,encryptionKey:a&&128===a.length?a.slice(64):void 0}},r=async e=>{const s=void 0!==e?.at?e.at:BigInt(Math.floor(Date.now()/1e3)),r=this.generateRequestId();return{reference:(await this.sendRequest({type:"epochFeedDownloadReference",requestId:r,topic:i,owner:n,at:this.normalizeFeedTimestamp(s),after:void 0!==e?.after?this.normalizeFeedTimestamp(e.after):void 0,encryptionKey:void 0,requestOptions:t})).reference,encryptionKey:void 0}};return{getOwner:async()=>{if(n)return n;const e=this.generateRequestId(),t=await this.sendRequest({type:"feedGetOwner",requestId:e});return n=t.owner,n},downloadReference:s,downloadPayload:async e=>{const i=await s(e);if(!i.reference)return{reference:void 0,payload:void 0,encryptionKey:void 0};const n=await this.downloadData(i.reference,void 0,t);return{reference:i.reference,payload:n,encryptionKey:i.encryptionKey}},downloadRawReference:r,downloadRawPayload:async e=>{const i=await r(e);if(!i.reference)return{reference:void 0,payload:void 0,encryptionKey:void 0};const n=await this.downloadData(i.reference,void 0,t);return{reference:i.reference,payload:n,encryptionKey:void 0}}}}makeEpochFeedWriter(e,t){this.ensureReady();const i=this.normalizeFeedTopic(e.topic),n=e.signer?new w(e.signer):void 0,s=n?n.toHex():void 0;let r=n?n.publicKey().address().toHex():void 0;const o=async e=>{const n=void 0!==e?.at?e.at:BigInt(Math.floor(Date.now()/1e3)),s=this.generateRequestId(),o=(await this.sendRequest({type:"epochFeedDownloadReference",requestId:s,topic:i,owner:r,at:this.normalizeFeedTimestamp(n),after:void 0!==e?.after?this.normalizeFeedTimestamp(e.after):void 0,encryptionKey:void 0!==e?.encryptionKey?this.normalizeSocKey(e.encryptionKey):void 0,requestOptions:t})).reference,a=o&&o.startsWith("0x")?o.slice(2):o;return{reference:o,encryptionKey:a&&128===a.length?a.slice(64):void 0}},a=async e=>{const n=void 0!==e?.at?e.at:BigInt(Math.floor(Date.now()/1e3)),s=this.generateRequestId();return{reference:(await this.sendRequest({type:"epochFeedDownloadReference",requestId:s,topic:i,owner:r,at:this.normalizeFeedTimestamp(n),after:void 0!==e?.after?this.normalizeFeedTimestamp(e.after):void 0,encryptionKey:void 0,requestOptions:t})).reference,encryptionKey:void 0}};return{getOwner:async()=>{if(r)return r;const e=this.generateRequestId(),t=await this.sendRequest({type:"feedGetOwner",requestId:e});return r=t.owner,r},downloadReference:o,downloadPayload:async e=>{const i=await o(e);if(!i.reference)return{reference:void 0,payload:void 0,encryptionKey:void 0};const n=await this.downloadData(i.reference,void 0,t);return{reference:i.reference,payload:n,encryptionKey:i.encryptionKey}},downloadRawReference:a,downloadRawPayload:async e=>{const i=await a(e);if(!i.reference)return{reference:void 0,payload:void 0,encryptionKey:void 0};const n=await this.downloadData(i.reference,void 0,t);return{reference:i.reference,payload:n,encryptionKey:void 0}},uploadReference:async(e,n)=>{const r=void 0!==n?.at?n.at:BigInt(Math.floor(Date.now()/1e3)),o=this.normalizeReference(e),a=o.startsWith("0x")?o.slice(2):o,d=128===a.length?a.slice(64):void 0,c=n?.encryptionKey??d,u=this.generateRequestId(),h=await this.sendRequest({type:"epochFeedUploadReference",requestId:u,topic:i,signer:s,at:this.normalizeFeedTimestamp(r),reference:o,encryptionKey:void 0!==c?this.normalizeSocKey(c):void 0,hints:n?.hints,requestOptions:t});return{socAddress:h.socAddress,reference:o,encryptionKey:d,epoch:h.epoch,timestamp:h.timestamp}},uploadPayload:async(e,n)=>{const r=void 0!==n?.at?n.at:BigInt(Math.floor(Date.now()/1e3)),o=!1!==n?.encrypt,a=await this.uploadData(this.normalizePayload(e),{...n?.uploadOptions,encrypt:o},t),d=a.reference.startsWith("0x")?a.reference.slice(2):a.reference,c=128===d.length?d.slice(64):void 0,u=n?.encryptionKey??c,h=this.generateRequestId(),p=await this.sendRequest({type:"epochFeedUploadReference",requestId:h,topic:i,signer:s,at:this.normalizeFeedTimestamp(r),reference:a.reference,encryptionKey:void 0!==u?this.normalizeSocKey(u):void 0,hints:n?.hints,requestOptions:t}),y=c;return{socAddress:p.socAddress,reference:a.reference,encryptionKey:y,epoch:p.epoch,timestamp:p.timestamp}},uploadRawReference:async(e,n)=>{const r=void 0!==n?.at?n.at:BigInt(Math.floor(Date.now()/1e3)),o=this.normalizeReference(e),a=this.generateRequestId(),d=await this.sendRequest({type:"epochFeedUploadReference",requestId:a,topic:i,signer:s,at:this.normalizeFeedTimestamp(r),reference:o,encryptionKey:void 0,hints:n?.hints,requestOptions:t});return{socAddress:d.socAddress,reference:o,encryptionKey:void 0,epoch:d.epoch,timestamp:d.timestamp}},uploadRawPayload:async(e,n)=>{const r=void 0!==n?.at?n.at:BigInt(Math.floor(Date.now()/1e3)),o=await this.uploadData(this.normalizePayload(e),{...n?.uploadOptions,encrypt:!1},t),a=this.generateRequestId(),d=await this.sendRequest({type:"epochFeedUploadReference",requestId:a,topic:i,signer:s,at:this.normalizeFeedTimestamp(r),reference:o.reference,encryptionKey:void 0,hints:n?.hints,requestOptions:t});return{socAddress:d.socAddress,reference:o.reference,encryptionKey:void 0,epoch:d.epoch,timestamp:d.timestamp}}}}makeSequentialFeedReader(e,t){this.ensureReady();const i=this.normalizeFeedTopic(e.topic);let n=e.owner?new y(e.owner).toHex():void 0;return{getOwner:async()=>{if(n)return n;const e=this.generateRequestId(),t=await this.sendRequest({type:"seqFeedGetOwner",requestId:e});return n=t.owner,n},downloadPayload:async(e,s)=>{const r=this.generateRequestId(),o=await this.sendRequest({type:"seqFeedDownloadPayload",requestId:r,topic:i,owner:n,index:void 0!==s?.index?this.normalizeFeedIndex(s.index):void 0,at:void 0!==s?.at?this.normalizeFeedTimestamp(s.at):void 0,hasTimestamp:s?.hasTimestamp,lookupTimeoutMs:s?.lookupTimeoutMs,encryptionKey:this.normalizeSocKey(e),requestOptions:t});return{payload:o.payload,timestamp:o.timestamp,feedIndex:o.feedIndex,feedIndexNext:o.feedIndexNext}},downloadRawPayload:async e=>{const s=this.generateRequestId(),r=await this.sendRequest({type:"seqFeedDownloadRawPayload",requestId:s,topic:i,owner:n,index:void 0!==e?.index?this.normalizeFeedIndex(e.index):void 0,at:void 0!==e?.at?this.normalizeFeedTimestamp(e.at):void 0,hasTimestamp:e?.hasTimestamp,lookupTimeoutMs:e?.lookupTimeoutMs,encryptionKey:e?.encryptionKey?this.normalizeSocKey(e.encryptionKey):void 0,requestOptions:t});return{payload:r.payload,timestamp:r.timestamp,feedIndex:r.feedIndex,feedIndexNext:r.feedIndexNext}},downloadReference:async(e,s)=>{const r=this.generateRequestId(),o=await this.sendRequest({type:"seqFeedDownloadReference",requestId:r,topic:i,owner:n,index:void 0!==s?.index?this.normalizeFeedIndex(s.index):void 0,at:void 0!==s?.at?this.normalizeFeedTimestamp(s.at):void 0,hasTimestamp:s?.hasTimestamp,lookupTimeoutMs:s?.lookupTimeoutMs,encryptionKey:this.normalizeSocKey(e),requestOptions:t});return{reference:o.reference,feedIndex:o.feedIndex,feedIndexNext:o.feedIndexNext}}}}makeSequentialFeedWriter(e,t){this.ensureReady();const i=this.normalizeFeedTopic(e.topic),n=e.signer?new w(e.signer):void 0,s=n?n.toHex():void 0;let r=n?n.publicKey().address().toHex():void 0;return{getOwner:async()=>{if(r)return r;const e=this.generateRequestId(),t=await this.sendRequest({type:"seqFeedGetOwner",requestId:e});return r=t.owner,r},downloadPayload:async(e,n)=>{const s=this.generateRequestId(),o=await this.sendRequest({type:"seqFeedDownloadPayload",requestId:s,topic:i,owner:r,index:void 0!==n?.index?this.normalizeFeedIndex(n.index):void 0,at:void 0!==n?.at?this.normalizeFeedTimestamp(n.at):void 0,hasTimestamp:n?.hasTimestamp,encryptionKey:this.normalizeSocKey(e),requestOptions:t});return{payload:o.payload,timestamp:o.timestamp,feedIndex:o.feedIndex,feedIndexNext:o.feedIndexNext}},downloadRawPayload:async e=>{const n=this.generateRequestId(),s=await this.sendRequest({type:"seqFeedDownloadRawPayload",requestId:n,topic:i,owner:r,index:void 0!==e?.index?this.normalizeFeedIndex(e.index):void 0,at:void 0!==e?.at?this.normalizeFeedTimestamp(e.at):void 0,hasTimestamp:e?.hasTimestamp,encryptionKey:e?.encryptionKey?this.normalizeSocKey(e.encryptionKey):void 0,requestOptions:t});return{payload:s.payload,timestamp:s.timestamp,feedIndex:s.feedIndex,feedIndexNext:s.feedIndexNext}},downloadReference:async(e,n)=>{const s=this.generateRequestId(),o=await this.sendRequest({type:"seqFeedDownloadReference",requestId:s,topic:i,owner:r,index:void 0!==n?.index?this.normalizeFeedIndex(n.index):void 0,at:void 0!==n?.at?this.normalizeFeedTimestamp(n.at):void 0,hasTimestamp:n?.hasTimestamp,encryptionKey:this.normalizeSocKey(e),requestOptions:t});return{reference:o.reference,feedIndex:o.feedIndex,feedIndexNext:o.feedIndexNext}},uploadPayload:async(e,n)=>{const o=this.generateRequestId(),a=await this.sendRequest({type:"seqFeedUploadPayload",requestId:o,topic:i,signer:s,data:this.normalizePayload(e),index:void 0!==n?.index?this.normalizeFeedIndex(n.index):void 0,at:void 0!==n?.at?this.normalizeFeedTimestamp(n.at):void 0,hasTimestamp:n?.hasTimestamp,lookupTimeoutMs:n?.lookupTimeoutMs,options:n,requestOptions:t});return r=a.owner,{reference:a.reference,feedIndex:a.feedIndex,owner:a.owner,encryptionKey:a.encryptionKey,tagUid:a.tagUid}},uploadRawPayload:async(e,n)=>{const o=this.generateRequestId(),a=await this.sendRequest({type:"seqFeedUploadRawPayload",requestId:o,topic:i,signer:s,data:this.normalizePayload(e),index:void 0!==n?.index?this.normalizeFeedIndex(n.index):void 0,at:void 0!==n?.at?this.normalizeFeedTimestamp(n.at):void 0,hasTimestamp:n?.hasTimestamp,lookupTimeoutMs:n?.lookupTimeoutMs,encryptionKey:n?.encryptionKey?this.normalizeSocKey(n.encryptionKey):void 0,options:n,requestOptions:t});return r=a.owner,{reference:a.reference,feedIndex:a.feedIndex,owner:a.owner,encryptionKey:a.encryptionKey,tagUid:a.tagUid}},uploadReference:async(e,n)=>{const o=this.generateRequestId(),a=await this.sendRequest({type:"seqFeedUploadReference",requestId:o,topic:i,signer:s,reference:this.normalizeReference(e),index:void 0!==n?.index?this.normalizeFeedIndex(n.index):void 0,at:void 0!==n?.at?this.normalizeFeedTimestamp(n.at):void 0,hasTimestamp:n?.hasTimestamp,lookupTimeoutMs:n?.lookupTimeoutMs,options:n,requestOptions:t});return r=a.owner,{reference:a.reference,feedIndex:a.feedIndex,owner:a.owner,encryptionKey:a.encryptionKey,tagUid:a.tagUid}}}}async createFeedManifest(e,t,i){this.ensureReady();const n=this.normalizeFeedTopic(e),s=this.generateRequestId();return(await this.sendRequest({type:"createFeedManifest",requestId:s,topic:n,owner:t?.owner,feedType:t?.feedType,uploadOptions:t?.uploadOptions,requestOptions:i})).reference}async gsocMine(e,t,i){this.ensureReady();const n=this.generateRequestId();return(await this.sendRequest({type:"gsocMine",requestId:n,targetOverlay:e,identifier:t,proximity:i})).signer}async gsocSend(e,t,i,n,s){this.ensureReady();const r=this.generateRequestId(),o=await this.sendRequest({type:"gsocSend",requestId:r,signer:e,identifier:t,data:new Uint8Array(i),options:n,requestOptions:s});return{reference:o.reference,tagUid:o.tagUid}}async actUploadData(e,t,i,n){this.ensureReady();const s=this.generateRequestId(),{onProgress:r,...o}=i??{},a=this.listenForProgress(s,r);try{const i=await this.sendRequest({type:"actUploadData",requestId:s,data:new Uint8Array(e),grantees:t,options:o,requestOptions:n,enableProgress:!!r});return{encryptedReference:i.encryptedReference,historyReference:i.historyReference,granteeListReference:i.granteeListReference,publisherPubKey:i.publisherPubKey,actReference:i.actReference,tagUid:i.tagUid}}finally{a()}}async actDownloadData(e,t,i,n,s){this.ensureReady();const r=this.generateRequestId();return(await this.sendRequest({type:"actDownloadData",requestId:r,encryptedReference:e,historyReference:t,publisherPubKey:i,timestamp:n,requestOptions:s})).data}async actAddGrantees(e,t,i){this.ensureReady();const n=this.generateRequestId(),s=await this.sendRequest({type:"actAddGrantees",requestId:n,historyReference:e,grantees:t,requestOptions:i});return{historyReference:s.historyReference,granteeListReference:s.granteeListReference,actReference:s.actReference}}async actRevokeGrantees(e,t,i,n){this.ensureReady();const s=this.generateRequestId(),r=await this.sendRequest({type:"actRevokeGrantees",requestId:s,historyReference:e,encryptedReference:t,revokeGrantees:i,requestOptions:n});return{encryptedReference:r.encryptedReference,historyReference:r.historyReference,granteeListReference:r.granteeListReference,actReference:r.actReference}}async actGetGrantees(e,t){this.ensureReady();const i=this.generateRequestId();return(await this.sendRequest({type:"actGetGrantees",requestId:i,historyReference:e,requestOptions:t})).grantees}destroy(){const e=()=>new n("invalid-state","Client destroyed");this.pendingRequests.forEach(t=>{clearTimeout(t.timeoutId),t.reject(e())}),this.pendingRequests.clear(),this.progressListeners.clear(),this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=void 0),this.iframe&&this.iframe.parentNode&&(this.iframe.parentNode.removeChild(this.iframe),this.iframe=void 0),this.iframeLoadReject?.(e()),this.proxyInitializedReject?.(e()),this.readyReject?.(e()),this.firstConnectionInfoReject?.(e()),this.iframeLoadReject=void 0,this.readyResolve=void 0,this.readyReject=void 0,this.proxyInitializedResolve=void 0,this.proxyInitializedReject=void 0,this.firstConnectionInfoResolve=void 0,this.firstConnectionInfoReject=void 0,this.readyPromise=void 0,this.proxyInitializedPromise=void 0,this.firstConnectionInfoPromise=void 0,this.ready=!1}}function K(e){const t=e instanceof Uint8Array?e:I(e);if(32!==t.length)throw new Error(`Invalid content reference length: ${t.length} (expected 32 bytes)`);const i=new q;return i.addFork("/",x,{"website-index-document":"index.bin"}),i.addFork("index.bin",t,{"Content-Type":"application/octet-stream",Filename:"index.bin"}),{manifestNode:i}}function P(e){let t=0;for(;e;)t+=1&e,e>>>=1;return t}function O(e){for(let t=0;t<e.length;t++)if(0!==e[t])return!1;return!0}function U(e){if(e.length<96)throw new Error(`Manifest too small: ${e.length} bytes (expected at least 96)`);const t=e.slice(64,96);if(O(t))throw new Error("Manifest entry is zero");return new z(t).toHex()}function M(e){if(e.length<192)throw new Error(`Manifest too small: ${e.length} bytes (expected at least 192)`);const t=e.slice(96,128),i=Math.floor(105/8);if(!(2&t[i]))throw new Error('Manifest does not contain "index.bin" fork');let n=0;for(let e=0;e<i;e++)n+=P(t[e]);for(let e=0;e<1;e++)t[i]&1<<e&&n++;let s=128;for(let t=0;t<n;t++){const t=e[s];if(s+=64,!!(16&t)){s+=2+(e[s]<<8|e[s+1])}}const r=e[s],o=e[s+1];if(105!==e[s+2])throw new Error(`Expected "index.bin" prefix, got byte 0x${e[s+2].toString(16)}`);if(o>=9){const t=e.slice(s+2,s+2+9),i=(new TextEncoder).encode("index.bin");t.every((e,t)=>e===i[t])||console.warn('[ManifestBuilder] Prefix does not fully match "index.bin"')}if(!!!(2&r))throw new Error('"index.bin" fork is not a VALUE type');const a=s+32,d=e.slice(a,a+32);if(O(d))throw new Error('Manifest "index.bin" fork has zero reference');return new z(d).toHex()}export{T as SwarmIdClient,n as SwarmIdError,g as TimeoutError,K as buildBzzManifestNode,F as collectionPath,M as extractContentFromFlatManifest,U as extractEntryFromManifest,h as generatedAvatar,I as hexToUint8Array,d as uint8ArrayToHex,R as withTimeout};
1
+ import{A as t,S as i,I as r,P as a,a as o,u as d,T as c,b as u,g as h,E as y,c as w,i as R,w as g,d as I,h as q,M as x,N as z,R as b}from"./chunks/chat-binding-DgECjSWW.js";export{C as CHAT_BINDING_TITLE,D as DEFAULT_BEE_NODE_URL,l as acceptedChatBinding,m as buildChatBindingMessage,f as formatTTL,e as generatedAvatarSvg,n as isCleanSiteOrigin,k as jsonRpcBatch,j as jsonRpcCall,p as parseChatBindingMessage,s as saveMantarayTreeRecursively,v as verifyChatBinding}from"./chunks/chat-binding-DgECjSWW.js";function F(e){const t=e.webkitRelativePath;return t?t.replace(/^[^/]*\//,""):e.name}function T(e,t,n){return g(e,t,n).catch(e=>{throw e instanceof I?new i("init-failed",e.message,{cause:e}):e})}function K(e){if(!R(e))throw new i("invalid-request","Invalid beeApiUrl: must be an http(s) URL, optionally with a path, and no credentials, query or fragment");return e}class U{constructor(e){if(this.ready=!1,this.pendingRequests=new Map,this.progressListeners=new Map,this.requestIdCounter=0,"undefined"==typeof window)throw new Error("@solarpunkltd/swarm-id runs in the browser only: construct SwarmIdClient in code that runs there (an effect, onMount, or behind `typeof window !== 'undefined'`), not in a server render");this.iframeOrigin=e.iframeOrigin,this.iframePath=e.iframePath||"/proxy",this.timeout=e.timeout??3e4,this.initializationTimeout=e.initializationTimeout??3e4,this.onConnectionChange=e.onConnectionChange,this.popupMode=e.popupMode||"window",this.metadata=e.metadata,this.buttonConfig=e.buttonConfig,this.containerId=e.containerId,this.subsidisedGatewayUrl=e.subsidisedGatewayUrl,void 0!==e.beeApiUrl&&(this.beeApiUrl=K(e.beeApiUrl));try{t.parse(this.metadata)}catch(e){throw new i("invalid-request",`Invalid app metadata: ${e}`,{cause:e})}this.setupMessageListener()}async initialize(){if(this.iframe)throw new i("invalid-state","SwarmIdClient already initialized");let e;if(this.firstConnectionInfoPromise=T(new Promise((e,t)=>{this.firstConnectionInfoResolve=e,this.firstConnectionInfoReject=t}),this.initializationTimeout,`Proxy initialization timeout - proxy did not send initial connectionInfoChanged within ${this.initializationTimeout}ms`),this.firstConnectionInfoPromise.catch(()=>{}),this.proxyInitializedPromise=T(new Promise((e,t)=>{this.proxyInitializedResolve=e,this.proxyInitializedReject=t}),this.initializationTimeout,`Proxy initialization timeout - proxy did not signal readiness within ${this.initializationTimeout}ms`),this.proxyInitializedPromise.catch(()=>{}),this.readyPromise=T(new Promise((e,t)=>{this.readyResolve=e,this.readyReject=t}),this.initializationTimeout,`Proxy initialization timeout - proxy did not respond within ${this.initializationTimeout}ms`),this.readyPromise.catch(()=>{}),this.iframe=document.createElement("iframe"),this.iframe.src=`${this.iframeOrigin}${this.iframePath}`,this.iframe.style.border="none",this.iframe.style.backgroundColor="transparent",this.iframe.style.borderRadius=this.buttonConfig?.borderRadius||"0",this.containerId){if(e=document.getElementById(this.containerId)||void 0,!e)throw new i("invalid-request",`Container element with ID "${this.containerId}" not found`);this.iframe.style.width="100%",this.iframe.style.height="100%",this.iframe.style.display="block"}else this.iframe.style.display="none",this.iframe.style.position="fixed",this.iframe.style.bottom="20px",this.iframe.style.right="20px",this.iframe.style.width="300px",this.iframe.style.height="50px",this.iframe.style.zIndex="999999";await new Promise((t,n)=>{this.iframeLoadReject=n,this.iframe.onload=()=>t(),this.iframe.onerror=()=>n(new i("init-failed","Failed to load Swarm ID iframe")),e?e.appendChild(this.iframe):document.body.appendChild(this.iframe)}),this.iframeLoadReject=void 0,await this.proxyInitializedPromise,this.sendMessage({type:"parentIdentify",requestId:this.generateRequestId(),popupMode:this.popupMode,metadata:this.metadata,buttonConfig:this.buttonConfig,subsidisedGatewayUrl:this.subsidisedGatewayUrl,beeApiUrl:this.beeApiUrl}),await this.readyPromise,await this.firstConnectionInfoPromise}setupMessageListener(){this.messageListener=e=>{if(!this.iframe||e.source!==this.iframe.contentWindow)return;if("proxyInitialized"===e.data?.type)return void(this.proxyInitializedResolve&&(this.proxyInitializedResolve(),this.proxyInitializedResolve=void 0));const t=new URL(this.iframeOrigin).origin;if(e.origin!==t)return void console.warn("[SwarmIdClient] Rejected message from unauthorized origin:",e.origin);let i;try{i=r.parse(e.data)}catch(t){return void console.warn("[SwarmIdClient] Invalid message format:",e.data,t)}this.handleIframeMessage(i)},window.addEventListener("message",this.messageListener)}handleIframeMessage(e){switch(e.type){case"proxyReady":this.ready=!0,this.storageShared=e.storageShared,this.readyResolve&&this.readyResolve(),this.iframe&&(this.iframe.style.display="block");break;case"authStatusResponse":if(this.iframe&&(this.iframe.style.display="block"),"requestId"in e){const t=this.pendingRequests.get(e.requestId);t&&(clearTimeout(t.timeoutId),this.pendingRequests.delete(e.requestId),t.resolve(e))}break;case"authSuccess":this.iframe&&(this.iframe.style.display="block");break;case"connectionInfoChanged":{const t={canUpload:e.canUpload,storagePartitioned:e.storagePartitioned,uploadMode:e.uploadMode,uploadUnavailableReason:e.uploadUnavailableReason,identity:e.identity,appKey:e.appKey,partition:e.partition,chatBinding:e.chatBinding,beeApiUrl:e.beeApiUrl,postageBatchId:e.postageBatchId};this.lastConnectionInfo=t,this.firstConnectionInfoResolve&&(this.firstConnectionInfoResolve(),this.firstConnectionInfoResolve=void 0),this.onConnectionChange&&this.onConnectionChange(t);break}case"initError":console.error("[SwarmIdClient] Proxy initialization error:",e.error),this.readyReject&&this.readyReject(new i("init-failed",e.error));break;case"disconnectResponse":if("requestId"in e){const t=this.pendingRequests.get(e.requestId);t&&(clearTimeout(t.timeoutId),this.pendingRequests.delete(e.requestId),t.resolve(e))}break;case"error":{const t=this.pendingRequests.get(e.requestId);t&&(clearTimeout(t.timeoutId),this.pendingRequests.delete(e.requestId),t.reject(i.fromWire(e)));break}case"uploadProgress":this.progressListeners.get(e.requestId)?.({total:e.total,processed:e.processed});break;default:if("requestId"in e){const t=this.pendingRequests.get(e.requestId);t&&(clearTimeout(t.timeoutId),this.pendingRequests.delete(e.requestId),t.resolve(e))}}}sendMessage(e){if(!this.iframe||!this.iframe.contentWindow)throw new i("invalid-state","Iframe not initialized");try{a.parse(e)}catch(e){throw new i("invalid-request",`Invalid message format: ${e}`,{cause:e})}this.iframe.contentWindow.postMessage(e,this.iframeOrigin)}async sendRequest(e){const t=this.roundTripTimeout(e.requestOptions?.timeout);return new Promise((n,s)=>{const r=setTimeout(()=>{this.pendingRequests.delete(e.requestId),s(new i("timeout",`Request timeout after ${t}ms`))},t);this.pendingRequests.set(e.requestId,{resolve:n,reject:s,timeoutId:r}),this.sendMessage(e)})}roundTripTimeout(e){return void 0===e||e<=0?this.timeout:Math.min(e,2147483647)}generateRequestId(){return`req-${++this.requestIdCounter}-${Date.now()}`}normalizeSocIdentifier(e){return e instanceof o?e.toHex():e instanceof Uint8Array?d(e):e}normalizeSocKey(e){return e instanceof Uint8Array?d(e):e}normalizeFeedTopic(e){return e instanceof c?d(e.toUint8Array()):e instanceof o?e.toHex():e instanceof Uint8Array?d(e):e}normalizeReference(e){return e instanceof Uint8Array?d(e):e}normalizeFeedTimestamp(e){return"bigint"==typeof e?e.toString():"number"==typeof e?BigInt(Math.floor(e)).toString():e}normalizeFeedIndex(e){return"bigint"==typeof e?e.toString():"number"==typeof e?BigInt(Math.floor(e)).toString():e}normalizePayload(e){return e instanceof Uint8Array?e:(new TextEncoder).encode(e)}socChunkFromResponse(e){return{data:e.data,identifier:e.identifier,signature:e.signature,span:e.span,payload:e.payload,address:e.address,owner:e.owner}}ensureReady(){if(!this.ready)throw new i("invalid-state","SwarmIdClient not initialized. Call initialize() first.")}getAuthIframe(){if(this.ensureReady(),!this.iframe)throw new i("invalid-state","Iframe not initialized");return this.iframe}async checkAuthStatus(){this.ensureReady();const e=this.generateRequestId(),t=await this.sendRequest({type:"checkAuth",requestId:e});return{authenticated:t.authenticated,origin:t.origin,beeApiUrl:t.beeApiUrl}}async setBeeApiUrl(e){const t=K(e);this.ensureReady(),await this.sendRequest({type:"setBeeApiUrl",requestId:this.generateRequestId(),beeApiUrl:t}),this.beeApiUrl=t}async getPostageBatch(){this.ensureReady();const e=this.generateRequestId();return(await this.sendRequest({type:"getPostageBatch",requestId:e})).postageBatch}async disconnect(){this.ensureReady();const e=this.generateRequestId();if(!(await this.sendRequest({type:"disconnect",requestId:e})).success)throw new i("internal","Failed to disconnect")}async connect(e={}){if(this.ensureReady(),!0===this.storageShared){if(!this.openAuthWindow(e))throw new i("popup-blocked","Failed to open authentication popup");return}const t=this.generateRequestId();if(!(await this.sendRequest({type:"connect",requestId:t,popupMode:e.popupMode})).success&&!this.openAuthWindow(e))throw new i("popup-blocked","Failed to open authentication popup")}openAuthWindow(e){const t=this.iframePath.replace(/\/proxy$/,""),i=u(this.iframeOrigin+t,window.location.origin,this.metadata),n="popup"===(e.popupMode??this.popupMode)?window.open(i,"_blank","width=500,height=600"):window.open(i,"_blank");return Boolean(n)}get connectionInfo(){if(this.ensureReady(),!this.lastConnectionInfo)throw new i("invalid-state","SwarmIdClient connectionInfo not yet available.");return this.lastConnectionInfo}async getAvatar(e={}){const{identity:t}=this.connectionInfo;if(t)return void 0!==e.size&&"generated"===t.avatar.source?h(t.id,e.size):t.avatar}async isBeeConnected(){try{this.ensureReady();const e=this.generateRequestId();return(await this.sendRequest({type:"isConnected",requestId:e})).connected}catch{return!1}}async getNodeInfo(){this.ensureReady();const e=this.generateRequestId(),t=await this.sendRequest({type:"getNodeInfo",requestId:e});return{beeMode:t.beeMode,chequebookEnabled:t.chequebookEnabled,swapEnabled:t.swapEnabled}}async uploadData(e,t,i){this.ensureReady();const n=this.generateRequestId(),{onProgress:s,useWebSocket:r,useWorkers:a,workerCount:o,concurrency:d,...c}=t??{},u=this.listenForProgress(n,s);try{const t=await this.sendRequest({type:"uploadData",requestId:n,data:new Uint8Array(e),options:c,requestOptions:i,enableProgress:!!s,useWebSocket:r,useWorkers:a,workerCount:o,concurrency:d});return{reference:t.reference,tagUid:t.tagUid}}finally{u()}}async downloadData(e,t,i){this.ensureReady();const n=this.generateRequestId();return(await this.sendRequest({type:"downloadData",requestId:n,reference:e,options:t,requestOptions:i})).data}async deriveAppSecret(e){this.ensureReady();const t=this.generateRequestId();return(await this.sendRequest({type:"deriveAppSecret",requestId:t,label:e})).secret}async getChatKey(){this.ensureReady();const e=this.generateRequestId();return(await this.sendRequest({type:"getChatKey",requestId:e})).chatKey}async stampChunk(e){this.ensureReady();const t=this.generateRequestId(),i="soc"===e.kind?{...e,identifier:this.normalizeSocIdentifier(e.identifier),signer:"app"===e.signer?e.signer:{...e.signer,privateKey:this.normalizeSocKey(e.signer.privateKey)}}:e,n=await this.sendRequest({type:"stampChunk",requestId:t,chunk:i});return{address:n.address,stamp:n.stamp,...void 0!==n.owner&&{owner:n.owner},...void 0!==n.signature&&{signature:n.signature}}}async uploadFile(e,t,i,n){this.ensureReady();const s=this.generateRequestId(),{onProgress:r,useWebSocket:a,useWorkers:o,workerCount:d,concurrency:c,...u}=i??{};let h,p=t;if(e instanceof File){const t=await e.arrayBuffer();h=new Uint8Array(t),p=p||e.name}else h=new Uint8Array(e.buffer.slice(0),e.byteOffset,e.byteLength);const l=this.listenForProgress(s,r);try{const e=await this.sendRequest({type:"uploadFile",requestId:s,data:h,name:p,options:u,requestOptions:n,enableProgress:!!r,useWebSocket:a,useWorkers:o,workerCount:d,concurrency:c});return{reference:e.reference,tagUid:e.tagUid}}finally{l()}}async downloadFile(e,t,i,n){this.ensureReady();const s=this.generateRequestId(),r=await this.sendRequest({type:"downloadFile",requestId:s,reference:e,path:t,options:i,requestOptions:n});return{name:r.name,data:new Uint8Array(r.data)}}async uploadFiles(e,t,i){this.ensureReady();const n=this.generateRequestId(),{onProgress:s,useWorkers:r,workerCount:a,...o}=t??{},d=await Promise.all(Array.from(e,async e=>{const{path:t,file:i}=e instanceof File?{path:F(e),file:e}:e;return{path:t,data:new Uint8Array(await i.arrayBuffer()),contentType:i.type||void 0}})),c=this.listenForProgress(n,s);try{const e=await this.sendRequest({type:"uploadFiles",requestId:n,files:d,options:o,requestOptions:i,enableProgress:!!s,useWorkers:r,workerCount:a});return{reference:e.reference,tagUid:e.tagUid}}finally{c()}}async listFiles(e,t){this.ensureReady();const i=this.generateRequestId();return(await this.sendRequest({type:"listFiles",requestId:i,reference:e,requestOptions:t})).entries}listenForProgress(e,t){return t?(this.progressListeners.set(e,t),()=>{this.progressListeners.delete(e)}):()=>{}}async uploadChunk(e,t,i){this.ensureReady();const n=this.generateRequestId(),{onProgress:s,...r}=t??{};return{reference:(await this.sendRequest({type:"uploadChunk",requestId:n,data:e,options:r,requestOptions:i})).reference}}async downloadChunk(e,t,i){this.ensureReady();const n=this.generateRequestId(),s=await this.sendRequest({type:"downloadChunk",requestId:n,reference:e,options:t,requestOptions:i});return new Uint8Array(s.data)}makeSOCReader(e,t){this.ensureReady();const i=new y(e).toHex(),n=async(e,n)=>{const s=this.generateRequestId(),r=await this.sendRequest({type:"socDownload",requestId:s,owner:i,identifier:this.normalizeSocIdentifier(e),encryptionKey:this.normalizeSocKey(n),requestOptions:t});return this.socChunkFromResponse(r)},s=async(e,n)=>{const s=this.generateRequestId(),r=await this.sendRequest({type:"socRawDownload",requestId:s,owner:i,identifier:this.normalizeSocIdentifier(e),encryptionKey:n?this.normalizeSocKey(n):void 0,requestOptions:t});return this.socChunkFromResponse(r)};return{getOwner:async()=>i,rawDownload:(e,t)=>s(e,t),download:(e,t)=>n(e,t)}}makeSOCWriter(e,t){this.ensureReady();const i=e?new w(e):void 0,n=i?i.toHex():void 0;let s=i?i.publicKey().address().toHex():void 0;const r=async(e,i)=>{const n=this.generateRequestId(),r=await this.sendRequest({type:"socDownload",requestId:n,owner:s,identifier:this.normalizeSocIdentifier(e),encryptionKey:this.normalizeSocKey(i),requestOptions:t});return this.socChunkFromResponse(r)},a=async(e,i)=>{const n=this.generateRequestId(),r=await this.sendRequest({type:"socRawDownload",requestId:n,owner:s,identifier:this.normalizeSocIdentifier(e),encryptionKey:i?this.normalizeSocKey(i):void 0,requestOptions:t});return this.socChunkFromResponse(r)},o=async(e,i,r)=>{const a=this.generateRequestId(),o=await this.sendRequest({type:"socUpload",requestId:a,identifier:this.normalizeSocIdentifier(e),data:new Uint8Array(i),signer:n,options:r,requestOptions:t});return s=o.owner,{reference:o.reference,tagUid:o.tagUid,encryptionKey:o.encryptionKey,owner:o.owner}},d=async(e,i,r)=>{const a=this.generateRequestId(),o=await this.sendRequest({type:"socRawUpload",requestId:a,identifier:this.normalizeSocIdentifier(e),data:new Uint8Array(i),signer:n,options:r,requestOptions:t});return s=o.owner,{reference:o.reference,tagUid:o.tagUid,encryptionKey:o.encryptionKey,owner:o.owner}};return{getOwner:async()=>{if(s)return s;const e=this.generateRequestId(),t=await this.sendRequest({type:"socGetOwner",requestId:e});return s=t.owner,s},rawDownload:(e,t)=>a(e,t),download:(e,t)=>r(e,t),upload:(e,t,i)=>o(e,t,i),rawUpload:(e,t,i)=>d(e,t,i)}}makeEpochFeedReader(e,t){this.ensureReady();const i=this.normalizeFeedTopic(e.topic);let n=e.owner?new y(e.owner).toHex():void 0;const s=async e=>{const s=void 0!==e?.at?e.at:BigInt(Math.floor(Date.now()/1e3)),r=this.generateRequestId(),a=(await this.sendRequest({type:"epochFeedDownloadReference",requestId:r,topic:i,owner:n,at:this.normalizeFeedTimestamp(s),after:void 0!==e?.after?this.normalizeFeedTimestamp(e.after):void 0,encryptionKey:void 0!==e?.encryptionKey?this.normalizeSocKey(e.encryptionKey):void 0,requestOptions:t})).reference,o=a&&a.startsWith("0x")?a.slice(2):a;return{reference:a,encryptionKey:o&&128===o.length?o.slice(64):void 0}},r=async e=>{const s=void 0!==e?.at?e.at:BigInt(Math.floor(Date.now()/1e3)),r=this.generateRequestId();return{reference:(await this.sendRequest({type:"epochFeedDownloadReference",requestId:r,topic:i,owner:n,at:this.normalizeFeedTimestamp(s),after:void 0!==e?.after?this.normalizeFeedTimestamp(e.after):void 0,encryptionKey:void 0,requestOptions:t})).reference,encryptionKey:void 0}};return{getOwner:async()=>{if(n)return n;const e=this.generateRequestId(),t=await this.sendRequest({type:"feedGetOwner",requestId:e});return n=t.owner,n},downloadReference:s,downloadPayload:async e=>{const i=await s(e);if(!i.reference)return{reference:void 0,payload:void 0,encryptionKey:void 0};const n=await this.downloadData(i.reference,void 0,t);return{reference:i.reference,payload:n,encryptionKey:i.encryptionKey}},downloadRawReference:r,downloadRawPayload:async e=>{const i=await r(e);if(!i.reference)return{reference:void 0,payload:void 0,encryptionKey:void 0};const n=await this.downloadData(i.reference,void 0,t);return{reference:i.reference,payload:n,encryptionKey:void 0}}}}makeEpochFeedWriter(e,t){this.ensureReady();const i=this.normalizeFeedTopic(e.topic),n=e.signer?new w(e.signer):void 0,s=n?n.toHex():void 0;let r=n?n.publicKey().address().toHex():void 0;const a=async e=>{const n=void 0!==e?.at?e.at:BigInt(Math.floor(Date.now()/1e3)),s=this.generateRequestId(),a=(await this.sendRequest({type:"epochFeedDownloadReference",requestId:s,topic:i,owner:r,at:this.normalizeFeedTimestamp(n),after:void 0!==e?.after?this.normalizeFeedTimestamp(e.after):void 0,encryptionKey:void 0!==e?.encryptionKey?this.normalizeSocKey(e.encryptionKey):void 0,requestOptions:t})).reference,o=a&&a.startsWith("0x")?a.slice(2):a;return{reference:a,encryptionKey:o&&128===o.length?o.slice(64):void 0}},o=async e=>{const n=void 0!==e?.at?e.at:BigInt(Math.floor(Date.now()/1e3)),s=this.generateRequestId();return{reference:(await this.sendRequest({type:"epochFeedDownloadReference",requestId:s,topic:i,owner:r,at:this.normalizeFeedTimestamp(n),after:void 0!==e?.after?this.normalizeFeedTimestamp(e.after):void 0,encryptionKey:void 0,requestOptions:t})).reference,encryptionKey:void 0}};return{getOwner:async()=>{if(r)return r;const e=this.generateRequestId(),t=await this.sendRequest({type:"feedGetOwner",requestId:e});return r=t.owner,r},downloadReference:a,downloadPayload:async e=>{const i=await a(e);if(!i.reference)return{reference:void 0,payload:void 0,encryptionKey:void 0};const n=await this.downloadData(i.reference,void 0,t);return{reference:i.reference,payload:n,encryptionKey:i.encryptionKey}},downloadRawReference:o,downloadRawPayload:async e=>{const i=await o(e);if(!i.reference)return{reference:void 0,payload:void 0,encryptionKey:void 0};const n=await this.downloadData(i.reference,void 0,t);return{reference:i.reference,payload:n,encryptionKey:void 0}},uploadReference:async(e,n)=>{const r=void 0!==n?.at?n.at:BigInt(Math.floor(Date.now()/1e3)),a=this.normalizeReference(e),o=a.startsWith("0x")?a.slice(2):a,d=128===o.length?o.slice(64):void 0,c=n?.encryptionKey??d,u=this.generateRequestId(),h=await this.sendRequest({type:"epochFeedUploadReference",requestId:u,topic:i,signer:s,at:this.normalizeFeedTimestamp(r),reference:a,encryptionKey:void 0!==c?this.normalizeSocKey(c):void 0,hints:n?.hints,requestOptions:t});return{socAddress:h.socAddress,reference:a,encryptionKey:d,epoch:h.epoch,timestamp:h.timestamp}},uploadPayload:async(e,n)=>{const r=void 0!==n?.at?n.at:BigInt(Math.floor(Date.now()/1e3)),a=!1!==n?.encrypt,o=await this.uploadData(this.normalizePayload(e),{...n?.uploadOptions,encrypt:a},t),d=o.reference.startsWith("0x")?o.reference.slice(2):o.reference,c=128===d.length?d.slice(64):void 0,u=n?.encryptionKey??c,h=this.generateRequestId(),p=await this.sendRequest({type:"epochFeedUploadReference",requestId:h,topic:i,signer:s,at:this.normalizeFeedTimestamp(r),reference:o.reference,encryptionKey:void 0!==u?this.normalizeSocKey(u):void 0,hints:n?.hints,requestOptions:t}),l=c;return{socAddress:p.socAddress,reference:o.reference,encryptionKey:l,epoch:p.epoch,timestamp:p.timestamp}},uploadRawReference:async(e,n)=>{const r=void 0!==n?.at?n.at:BigInt(Math.floor(Date.now()/1e3)),a=this.normalizeReference(e),o=this.generateRequestId(),d=await this.sendRequest({type:"epochFeedUploadReference",requestId:o,topic:i,signer:s,at:this.normalizeFeedTimestamp(r),reference:a,encryptionKey:void 0,hints:n?.hints,requestOptions:t});return{socAddress:d.socAddress,reference:a,encryptionKey:void 0,epoch:d.epoch,timestamp:d.timestamp}},uploadRawPayload:async(e,n)=>{const r=void 0!==n?.at?n.at:BigInt(Math.floor(Date.now()/1e3)),a=await this.uploadData(this.normalizePayload(e),{...n?.uploadOptions,encrypt:!1},t),o=this.generateRequestId(),d=await this.sendRequest({type:"epochFeedUploadReference",requestId:o,topic:i,signer:s,at:this.normalizeFeedTimestamp(r),reference:a.reference,encryptionKey:void 0,hints:n?.hints,requestOptions:t});return{socAddress:d.socAddress,reference:a.reference,encryptionKey:void 0,epoch:d.epoch,timestamp:d.timestamp}}}}makeSequentialFeedReader(e,t){this.ensureReady();const i=this.normalizeFeedTopic(e.topic);let n=e.owner?new y(e.owner).toHex():void 0;return{getOwner:async()=>{if(n)return n;const e=this.generateRequestId(),t=await this.sendRequest({type:"seqFeedGetOwner",requestId:e});return n=t.owner,n},downloadPayload:async(e,s)=>{const r=this.generateRequestId(),a=await this.sendRequest({type:"seqFeedDownloadPayload",requestId:r,topic:i,owner:n,index:void 0!==s?.index?this.normalizeFeedIndex(s.index):void 0,at:void 0!==s?.at?this.normalizeFeedTimestamp(s.at):void 0,hasTimestamp:s?.hasTimestamp,lookupTimeoutMs:s?.lookupTimeoutMs,encryptionKey:this.normalizeSocKey(e),requestOptions:t});return{payload:a.payload,timestamp:a.timestamp,feedIndex:a.feedIndex,feedIndexNext:a.feedIndexNext}},downloadRawPayload:async e=>{const s=this.generateRequestId(),r=await this.sendRequest({type:"seqFeedDownloadRawPayload",requestId:s,topic:i,owner:n,index:void 0!==e?.index?this.normalizeFeedIndex(e.index):void 0,at:void 0!==e?.at?this.normalizeFeedTimestamp(e.at):void 0,hasTimestamp:e?.hasTimestamp,lookupTimeoutMs:e?.lookupTimeoutMs,encryptionKey:e?.encryptionKey?this.normalizeSocKey(e.encryptionKey):void 0,requestOptions:t});return{payload:r.payload,timestamp:r.timestamp,feedIndex:r.feedIndex,feedIndexNext:r.feedIndexNext}},downloadReference:async(e,s)=>{const r=this.generateRequestId(),a=await this.sendRequest({type:"seqFeedDownloadReference",requestId:r,topic:i,owner:n,index:void 0!==s?.index?this.normalizeFeedIndex(s.index):void 0,at:void 0!==s?.at?this.normalizeFeedTimestamp(s.at):void 0,hasTimestamp:s?.hasTimestamp,lookupTimeoutMs:s?.lookupTimeoutMs,encryptionKey:this.normalizeSocKey(e),requestOptions:t});return{reference:a.reference,feedIndex:a.feedIndex,feedIndexNext:a.feedIndexNext}}}}makeSequentialFeedWriter(e,t){this.ensureReady();const i=this.normalizeFeedTopic(e.topic),n=e.signer?new w(e.signer):void 0,s=n?n.toHex():void 0;let r=n?n.publicKey().address().toHex():void 0;return{getOwner:async()=>{if(r)return r;const e=this.generateRequestId(),t=await this.sendRequest({type:"seqFeedGetOwner",requestId:e});return r=t.owner,r},downloadPayload:async(e,n)=>{const s=this.generateRequestId(),a=await this.sendRequest({type:"seqFeedDownloadPayload",requestId:s,topic:i,owner:r,index:void 0!==n?.index?this.normalizeFeedIndex(n.index):void 0,at:void 0!==n?.at?this.normalizeFeedTimestamp(n.at):void 0,hasTimestamp:n?.hasTimestamp,encryptionKey:this.normalizeSocKey(e),requestOptions:t});return{payload:a.payload,timestamp:a.timestamp,feedIndex:a.feedIndex,feedIndexNext:a.feedIndexNext}},downloadRawPayload:async e=>{const n=this.generateRequestId(),s=await this.sendRequest({type:"seqFeedDownloadRawPayload",requestId:n,topic:i,owner:r,index:void 0!==e?.index?this.normalizeFeedIndex(e.index):void 0,at:void 0!==e?.at?this.normalizeFeedTimestamp(e.at):void 0,hasTimestamp:e?.hasTimestamp,encryptionKey:e?.encryptionKey?this.normalizeSocKey(e.encryptionKey):void 0,requestOptions:t});return{payload:s.payload,timestamp:s.timestamp,feedIndex:s.feedIndex,feedIndexNext:s.feedIndexNext}},downloadReference:async(e,n)=>{const s=this.generateRequestId(),a=await this.sendRequest({type:"seqFeedDownloadReference",requestId:s,topic:i,owner:r,index:void 0!==n?.index?this.normalizeFeedIndex(n.index):void 0,at:void 0!==n?.at?this.normalizeFeedTimestamp(n.at):void 0,hasTimestamp:n?.hasTimestamp,encryptionKey:this.normalizeSocKey(e),requestOptions:t});return{reference:a.reference,feedIndex:a.feedIndex,feedIndexNext:a.feedIndexNext}},uploadPayload:async(e,n)=>{const a=this.generateRequestId(),o=await this.sendRequest({type:"seqFeedUploadPayload",requestId:a,topic:i,signer:s,data:this.normalizePayload(e),index:void 0!==n?.index?this.normalizeFeedIndex(n.index):void 0,at:void 0!==n?.at?this.normalizeFeedTimestamp(n.at):void 0,hasTimestamp:n?.hasTimestamp,lookupTimeoutMs:n?.lookupTimeoutMs,options:n,requestOptions:t});return r=o.owner,{reference:o.reference,feedIndex:o.feedIndex,owner:o.owner,encryptionKey:o.encryptionKey,tagUid:o.tagUid}},uploadRawPayload:async(e,n)=>{const a=this.generateRequestId(),o=await this.sendRequest({type:"seqFeedUploadRawPayload",requestId:a,topic:i,signer:s,data:this.normalizePayload(e),index:void 0!==n?.index?this.normalizeFeedIndex(n.index):void 0,at:void 0!==n?.at?this.normalizeFeedTimestamp(n.at):void 0,hasTimestamp:n?.hasTimestamp,lookupTimeoutMs:n?.lookupTimeoutMs,encryptionKey:n?.encryptionKey?this.normalizeSocKey(n.encryptionKey):void 0,options:n,requestOptions:t});return r=o.owner,{reference:o.reference,feedIndex:o.feedIndex,owner:o.owner,encryptionKey:o.encryptionKey,tagUid:o.tagUid}},uploadReference:async(e,n)=>{const a=this.generateRequestId(),o=await this.sendRequest({type:"seqFeedUploadReference",requestId:a,topic:i,signer:s,reference:this.normalizeReference(e),index:void 0!==n?.index?this.normalizeFeedIndex(n.index):void 0,at:void 0!==n?.at?this.normalizeFeedTimestamp(n.at):void 0,hasTimestamp:n?.hasTimestamp,lookupTimeoutMs:n?.lookupTimeoutMs,options:n,requestOptions:t});return r=o.owner,{reference:o.reference,feedIndex:o.feedIndex,owner:o.owner,encryptionKey:o.encryptionKey,tagUid:o.tagUid}}}}async createFeedManifest(e,t,i){this.ensureReady();const n=this.normalizeFeedTopic(e),s=this.generateRequestId();return(await this.sendRequest({type:"createFeedManifest",requestId:s,topic:n,owner:t?.owner,feedType:t?.feedType,uploadOptions:t?.uploadOptions,requestOptions:i})).reference}async gsocMine(e,t,i){this.ensureReady();const n=this.generateRequestId();return(await this.sendRequest({type:"gsocMine",requestId:n,targetOverlay:e,identifier:t,proximity:i})).signer}async gsocSend(e,t,i,n,s){this.ensureReady();const r=this.generateRequestId(),a=await this.sendRequest({type:"gsocSend",requestId:r,signer:e,identifier:t,data:new Uint8Array(i),options:n,requestOptions:s});return{reference:a.reference,tagUid:a.tagUid}}async actUploadData(e,t,i,n){this.ensureReady();const s=this.generateRequestId(),{onProgress:r,...a}=i??{},o=this.listenForProgress(s,r);try{const i=await this.sendRequest({type:"actUploadData",requestId:s,data:new Uint8Array(e),grantees:t,options:a,requestOptions:n,enableProgress:!!r});return{encryptedReference:i.encryptedReference,historyReference:i.historyReference,granteeListReference:i.granteeListReference,publisherPubKey:i.publisherPubKey,actReference:i.actReference,tagUid:i.tagUid}}finally{o()}}async actDownloadData(e,t,i,n,s){this.ensureReady();const r=this.generateRequestId();return(await this.sendRequest({type:"actDownloadData",requestId:r,encryptedReference:e,historyReference:t,publisherPubKey:i,timestamp:n,requestOptions:s})).data}async actAddGrantees(e,t,i){this.ensureReady();const n=this.generateRequestId(),s=await this.sendRequest({type:"actAddGrantees",requestId:n,historyReference:e,grantees:t,requestOptions:i});return{historyReference:s.historyReference,granteeListReference:s.granteeListReference,actReference:s.actReference}}async actRevokeGrantees(e,t,i,n){this.ensureReady();const s=this.generateRequestId(),r=await this.sendRequest({type:"actRevokeGrantees",requestId:s,historyReference:e,encryptedReference:t,revokeGrantees:i,requestOptions:n});return{encryptedReference:r.encryptedReference,historyReference:r.historyReference,granteeListReference:r.granteeListReference,actReference:r.actReference}}async actGetGrantees(e,t){this.ensureReady();const i=this.generateRequestId();return(await this.sendRequest({type:"actGetGrantees",requestId:i,historyReference:e,requestOptions:t})).grantees}destroy(){const e=()=>new i("invalid-state","Client destroyed");this.pendingRequests.forEach(t=>{clearTimeout(t.timeoutId),t.reject(e())}),this.pendingRequests.clear(),this.progressListeners.clear(),this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=void 0),this.iframe&&this.iframe.parentNode&&(this.iframe.parentNode.removeChild(this.iframe),this.iframe=void 0),this.iframeLoadReject?.(e()),this.proxyInitializedReject?.(e()),this.readyReject?.(e()),this.firstConnectionInfoReject?.(e()),this.iframeLoadReject=void 0,this.readyResolve=void 0,this.readyReject=void 0,this.proxyInitializedResolve=void 0,this.proxyInitializedReject=void 0,this.firstConnectionInfoResolve=void 0,this.firstConnectionInfoReject=void 0,this.readyPromise=void 0,this.proxyInitializedPromise=void 0,this.firstConnectionInfoPromise=void 0,this.ready=!1}}function P(e){const t=e instanceof Uint8Array?e:q(e);if(32!==t.length)throw new Error(`Invalid content reference length: ${t.length} (expected 32 bytes)`);const i=new x;return i.addFork("/",z,{"website-index-document":"index.bin"}),i.addFork("index.bin",t,{"Content-Type":"application/octet-stream",Filename:"index.bin"}),{manifestNode:i}}function O(e){let t=0;for(;e;)t+=1&e,e>>>=1;return t}function M(e){for(let t=0;t<e.length;t++)if(0!==e[t])return!1;return!0}function S(e){if(e.length<96)throw new Error(`Manifest too small: ${e.length} bytes (expected at least 96)`);const t=e.slice(64,96);if(M(t))throw new Error("Manifest entry is zero");return new b(t).toHex()}function A(e){if(e.length<192)throw new Error(`Manifest too small: ${e.length} bytes (expected at least 192)`);const t=e.slice(96,128),i=Math.floor(105/8);if(!(2&t[i]))throw new Error('Manifest does not contain "index.bin" fork');let n=0;for(let e=0;e<i;e++)n+=O(t[e]);for(let e=0;e<1;e++)t[i]&1<<e&&n++;let s=128;for(let t=0;t<n;t++){const t=e[s];if(s+=64,!!(16&t)){s+=2+(e[s]<<8|e[s+1])}}const r=e[s],a=e[s+1];if(105!==e[s+2])throw new Error(`Expected "index.bin" prefix, got byte 0x${e[s+2].toString(16)}`);if(a>=9){const t=e.slice(s+2,s+2+9),i=(new TextEncoder).encode("index.bin");t.every((e,t)=>e===i[t])||console.warn('[ManifestBuilder] Prefix does not fully match "index.bin"')}if(!!!(2&r))throw new Error('"index.bin" fork is not a VALUE type');const o=s+32,d=e.slice(o,o+32);if(M(d))throw new Error('Manifest "index.bin" fork has zero reference');return new b(d).toHex()}export{U as SwarmIdClient,i as SwarmIdError,I as TimeoutError,P as buildBzzManifestNode,F as collectionPath,A as extractContentFromFlatManifest,S as extractEntryFromManifest,h as generatedAvatar,q as hexToUint8Array,d as uint8ArrayToHex,g as withTimeout};
2
2
  //# sourceMappingURL=swarm-id.esm.js.map