@solarpunkltd/swarm-id 0.8.1 → 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<{
@@ -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
@@ -334,6 +342,18 @@ export declare class SwarmIdProxy {
334
342
  * Used as storage partitioning fallback when storage events don't fire due to partitioning.
335
343
  */
336
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;
337
357
  /**
338
358
  * End the connect attempt a refused handover belonged to.
339
359
  *
@@ -1,2 +1,2 @@
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-DO5aGhPl.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-DO5aGhPl.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};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};
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