@nevermined-io/ui-widgets 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +345 -0
- package/dist/index.js +1 -0
- package/dist/index.mjs +510 -0
- package/package.json +21 -0
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
export declare interface CardAction {
|
|
2
|
+
/** Currently the only emitted action; reserved as a discriminator for future ones. */
|
|
3
|
+
action: 'delegate';
|
|
4
|
+
paymentMethodId: string;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export declare interface CheckoutOptions {
|
|
8
|
+
did: string;
|
|
9
|
+
planId?: string;
|
|
10
|
+
container?: HTMLElement;
|
|
11
|
+
onBooted?: () => void;
|
|
12
|
+
onReady?: () => void;
|
|
13
|
+
onSuccess?: (result: CheckoutResult) => void;
|
|
14
|
+
onError?: (error: EmbedError) => void;
|
|
15
|
+
onClose?: () => void;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export declare interface CheckoutResult {
|
|
19
|
+
did: string;
|
|
20
|
+
planId?: string;
|
|
21
|
+
txHash?: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Checkout widget.
|
|
26
|
+
*
|
|
27
|
+
* Lifecycle note for SDK consumers: when the iframe sends `nvm:close` the
|
|
28
|
+
* widget instance auto-calls `destroy()` and becomes terminal — any
|
|
29
|
+
* subsequent `start()` call throws. If the host page needs to re-show the
|
|
30
|
+
* checkout after a close, construct a new `CheckoutWidget` (typically via
|
|
31
|
+
* `nvm.checkout`) and call `start()` on the fresh instance.
|
|
32
|
+
*/
|
|
33
|
+
export declare class CheckoutWidget {
|
|
34
|
+
private readonly session;
|
|
35
|
+
private readonly webappBase;
|
|
36
|
+
private manager;
|
|
37
|
+
private destroyed;
|
|
38
|
+
constructor(session: SessionManager, webappBase: string);
|
|
39
|
+
/**
|
|
40
|
+
* Mounts the checkout iframe into `options.container`.
|
|
41
|
+
* Throws if called after `destroy()` (including the implicit destroy on
|
|
42
|
+
* `nvm:close` — see class JSDoc).
|
|
43
|
+
*/
|
|
44
|
+
start(options: CheckoutOptions): void;
|
|
45
|
+
destroy(): void;
|
|
46
|
+
private handleMessage;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export declare interface CreateDelegationOptions {
|
|
50
|
+
paymentMethodId: string;
|
|
51
|
+
container?: HTMLElement;
|
|
52
|
+
onBooted?: () => void;
|
|
53
|
+
onReady?: () => void;
|
|
54
|
+
onSuccess?: (result: CreateDelegationResult) => void;
|
|
55
|
+
onError?: (error: EmbedError) => void;
|
|
56
|
+
onClose?: () => void;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export declare interface CreateDelegationResult {
|
|
60
|
+
delegationId: string;
|
|
61
|
+
paymentMethodId: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export declare function createMessage<T>(type: WidgetMessageType, payload?: T): WidgetMessage<T>;
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Card and delegation management widget.
|
|
68
|
+
*
|
|
69
|
+
* Surfaces three iframe-based flows (enrollment, listing, delegation creation)
|
|
70
|
+
* and two SDK-direct revocations. The three iframe flows share the single
|
|
71
|
+
* `manager` slot — calling any of them destroys the previously-mounted iframe
|
|
72
|
+
* (same semantics as calling `enrollCard()` twice). Once any iframe is closed
|
|
73
|
+
* by the user (`nvm:close`), the instance is implicitly destroyed and any
|
|
74
|
+
* subsequent iframe call throws. Construct a fresh widget (via
|
|
75
|
+
* `nvm.delegations`) to mount another flow after a close.
|
|
76
|
+
*
|
|
77
|
+
* The two `revoke*` methods do NOT use an iframe — they hit the
|
|
78
|
+
* `/api/v1/widgets/...` endpoints directly with the widget session token.
|
|
79
|
+
* They exist because the SDK consumer on the host page only holds the widget
|
|
80
|
+
* session token; the apiKeyHash that gates the standard delegation/payment
|
|
81
|
+
* endpoints never leaves the embedded iframe.
|
|
82
|
+
*/
|
|
83
|
+
export declare class DelegationsWidget {
|
|
84
|
+
private readonly session;
|
|
85
|
+
private readonly webappBase;
|
|
86
|
+
private readonly apiBase;
|
|
87
|
+
private manager;
|
|
88
|
+
private destroyed;
|
|
89
|
+
constructor(session: SessionManager, webappBase: string, apiBase: string);
|
|
90
|
+
/**
|
|
91
|
+
* Mounts the enrollment iframe at `/embed/cards/enroll`.
|
|
92
|
+
* Throws if called after `destroy()` (including the implicit destroy on
|
|
93
|
+
* `nvm:close` — see class JSDoc).
|
|
94
|
+
*/
|
|
95
|
+
enrollCard(options: EnrollCardOptions): void;
|
|
96
|
+
/**
|
|
97
|
+
* Mounts the cards-list iframe at `/embed/cards/list`. Per-row actions
|
|
98
|
+
* (currently only "Create Delegation") are forwarded via `onCardAction` so
|
|
99
|
+
* the host can mount the appropriate follow-up widget.
|
|
100
|
+
*/
|
|
101
|
+
listCards(options: ListCardsOptions): void;
|
|
102
|
+
/**
|
|
103
|
+
* Mounts the delegation creation iframe at `/embed/cards/delegate` for a
|
|
104
|
+
* specific payment method. The `paymentMethodId` is required and is passed
|
|
105
|
+
* as a search param so the embed route can scope the form to that card.
|
|
106
|
+
*/
|
|
107
|
+
createDelegation(options: CreateDelegationOptions): void;
|
|
108
|
+
/**
|
|
109
|
+
* Revoke (detach) a payment method via the widget-prefixed API endpoint.
|
|
110
|
+
* Resolves on 2xx; throws `WidgetApiError` on any other response or
|
|
111
|
+
* network failure.
|
|
112
|
+
*/
|
|
113
|
+
revokeCard(paymentMethodId: string): Promise<void>;
|
|
114
|
+
/**
|
|
115
|
+
* Revoke a delegation via the widget-prefixed API endpoint.
|
|
116
|
+
* Resolves on 2xx; throws `WidgetApiError` on any other response or
|
|
117
|
+
* network failure.
|
|
118
|
+
*/
|
|
119
|
+
revokeDelegation(delegationId: string): Promise<void>;
|
|
120
|
+
destroy(): void;
|
|
121
|
+
private assertAlive;
|
|
122
|
+
private mountIframe;
|
|
123
|
+
private postInitOnBooted;
|
|
124
|
+
private handleEnrollMessage;
|
|
125
|
+
private handleListMessage;
|
|
126
|
+
private handleCreateDelegationMessage;
|
|
127
|
+
private deleteWithSession;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export declare interface EmbedError {
|
|
131
|
+
code: 'UNAUTHORIZED' | 'NETWORK' | 'PAYMENT_NOT_CONFIRMED' | 'UNKNOWN';
|
|
132
|
+
message: string;
|
|
133
|
+
status?: number;
|
|
134
|
+
apiCode?: string;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export declare interface EnrollCardOptions {
|
|
138
|
+
container?: HTMLElement;
|
|
139
|
+
onBooted?: () => void;
|
|
140
|
+
onReady?: () => void;
|
|
141
|
+
onSuccess?: (result: EnrollCardResult) => void;
|
|
142
|
+
onError?: (error: EmbedError) => void;
|
|
143
|
+
onClose?: () => void;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export declare interface EnrollCardResult {
|
|
147
|
+
paymentMethodId: string;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export declare type Environment = (typeof ENVIRONMENTS)[number];
|
|
151
|
+
|
|
152
|
+
declare const ENVIRONMENTS: readonly ["local", "sandbox", "live", "staging_sandbox", "staging_live"];
|
|
153
|
+
|
|
154
|
+
declare type EventHandler<T> = (payload: T) => void;
|
|
155
|
+
|
|
156
|
+
export declare class IframeManager {
|
|
157
|
+
private expectedOrigin;
|
|
158
|
+
private iframe;
|
|
159
|
+
private messageHandlers;
|
|
160
|
+
private protocolErrorHandlers;
|
|
161
|
+
private messageListener;
|
|
162
|
+
private destroyed;
|
|
163
|
+
constructor(expectedOrigin: string);
|
|
164
|
+
create(url: string, options?: IframeOptions): HTMLIFrameElement;
|
|
165
|
+
destroy(): void;
|
|
166
|
+
postMessage(msg: WidgetMessage): void;
|
|
167
|
+
onMessage(handler: (msg: WidgetMessage) => void): () => void;
|
|
168
|
+
onProtocolError(handler: (reason: string) => void): () => void;
|
|
169
|
+
private ensureListener;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export declare interface IframeOptions {
|
|
173
|
+
container?: HTMLElement;
|
|
174
|
+
style?: Partial<CSSStyleDeclaration>;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export declare interface ListCardsOptions {
|
|
178
|
+
container?: HTMLElement;
|
|
179
|
+
onBooted?: () => void;
|
|
180
|
+
onReady?: () => void;
|
|
181
|
+
onCardAction?: (action: CardAction) => void;
|
|
182
|
+
onError?: (error: EmbedError) => void;
|
|
183
|
+
onClose?: () => void;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export declare class NeverminedWidgets {
|
|
187
|
+
private readonly sessionManager;
|
|
188
|
+
private readonly _account;
|
|
189
|
+
private readonly environment;
|
|
190
|
+
private _checkout;
|
|
191
|
+
private _delegations;
|
|
192
|
+
private readonly events;
|
|
193
|
+
private constructor();
|
|
194
|
+
static initialize(config: WidgetConfig): Promise<NeverminedWidgets>;
|
|
195
|
+
private refreshSession;
|
|
196
|
+
on<K extends keyof NeverminedWidgetsEvents>(event: K, handler: (payload: NeverminedWidgetsEvents[K]) => void): this;
|
|
197
|
+
off<K extends keyof NeverminedWidgetsEvents>(event: K, handler: (payload: NeverminedWidgetsEvents[K]) => void): this;
|
|
198
|
+
get account(): WidgetAccount;
|
|
199
|
+
get hasValidSession(): boolean;
|
|
200
|
+
getSessionToken(): string;
|
|
201
|
+
get checkout(): CheckoutWidget;
|
|
202
|
+
get delegations(): DelegationsWidget;
|
|
203
|
+
/**
|
|
204
|
+
* Resets the parent widget container: tears down any live child widget (e.g.
|
|
205
|
+
* the checkout widget) and clears the internal cache. This is a reset, not a
|
|
206
|
+
* terminal state — accessing `widget.checkout` after `destroy()` lazily
|
|
207
|
+
* creates a fresh `CheckoutWidget` instance. If you need a terminal "this
|
|
208
|
+
* widget can no longer be used" semantics, call `destroy()` on the child
|
|
209
|
+
* widget directly (e.g. `widget.checkout.destroy()`), which flips its
|
|
210
|
+
* internal `destroyed` flag and makes subsequent `start()` calls throw.
|
|
211
|
+
*/
|
|
212
|
+
destroy(): void;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
declare interface NeverminedWidgetsEvents {
|
|
216
|
+
'session-expired': void;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
export declare function parseMessage(data: unknown): ParseResult;
|
|
220
|
+
|
|
221
|
+
export declare type ParseResult<T = unknown> = {
|
|
222
|
+
ok: true;
|
|
223
|
+
message: WidgetMessage<T>;
|
|
224
|
+
} | {
|
|
225
|
+
ok: false;
|
|
226
|
+
reason: string;
|
|
227
|
+
};
|
|
228
|
+
|
|
229
|
+
export declare class SessionManager {
|
|
230
|
+
private session;
|
|
231
|
+
private expiresMs;
|
|
232
|
+
private timer;
|
|
233
|
+
constructor(session: WidgetSession);
|
|
234
|
+
isValid(): boolean;
|
|
235
|
+
getToken(): string;
|
|
236
|
+
getSession(): WidgetSession;
|
|
237
|
+
startAutoRefresh(refreshFn: () => Promise<WidgetSession>, onExpired: () => void): void;
|
|
238
|
+
stopAutoRefresh(): void;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
export declare class TypedEventEmitter<Events extends object> {
|
|
242
|
+
private listeners;
|
|
243
|
+
on<K extends keyof Events>(event: K, handler: EventHandler<Events[K]>): this;
|
|
244
|
+
off<K extends keyof Events>(event: K, handler: EventHandler<Events[K]>): this;
|
|
245
|
+
once<K extends keyof Events>(event: K, handler: EventHandler<Events[K]>): this;
|
|
246
|
+
removeAllListeners(event?: keyof Events): this;
|
|
247
|
+
emit<K extends keyof Events>(event: K, payload: Events[K]): void;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
declare const WIDGET_ERRORS: {
|
|
251
|
+
readonly MISSING_INIT_TOKEN: {
|
|
252
|
+
readonly numericCode: "WDG.0001";
|
|
253
|
+
readonly message: "initToken is required and must be a non-empty string";
|
|
254
|
+
};
|
|
255
|
+
readonly INVALID_ENVIRONMENT: {
|
|
256
|
+
readonly numericCode: "WDG.0002";
|
|
257
|
+
readonly message: "environment must be one of: sandbox, live, staging_sandbox, staging_live, local";
|
|
258
|
+
};
|
|
259
|
+
readonly INVALID_INIT_TOKEN: {
|
|
260
|
+
readonly numericCode: "WDG.0003";
|
|
261
|
+
readonly message: "Init token is invalid or expired";
|
|
262
|
+
};
|
|
263
|
+
readonly INVALID_RESPONSE: {
|
|
264
|
+
readonly numericCode: "WDG.0004";
|
|
265
|
+
readonly message: "Server response is missing required fields";
|
|
266
|
+
};
|
|
267
|
+
readonly NETWORK_ERROR: {
|
|
268
|
+
readonly numericCode: "WDG.0005";
|
|
269
|
+
readonly message: "Network request failed";
|
|
270
|
+
};
|
|
271
|
+
readonly SESSION_EXPIRED: {
|
|
272
|
+
readonly numericCode: "WDG.0006";
|
|
273
|
+
readonly message: "Widget session has expired";
|
|
274
|
+
};
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
export declare const WIDGET_MESSAGE_VERSION: "1";
|
|
278
|
+
|
|
279
|
+
export declare interface WidgetAccount {
|
|
280
|
+
userId: string;
|
|
281
|
+
userWallet: `0x${string}`;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Thrown by SDK methods that hit the API directly (no iframe), e.g.
|
|
286
|
+
* `delegations.revokeCard()` / `delegations.revokeDelegation()`. Carries the
|
|
287
|
+
* HTTP status and the optional BCK error code so consumers can branch on
|
|
288
|
+
* 401/403/etc. without parsing the message.
|
|
289
|
+
*/
|
|
290
|
+
export declare class WidgetApiError extends Error {
|
|
291
|
+
readonly status?: number | undefined;
|
|
292
|
+
readonly apiCode?: string | undefined;
|
|
293
|
+
constructor(message: string, status?: number | undefined, apiCode?: string | undefined);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
export declare interface WidgetConfig {
|
|
297
|
+
initToken: string;
|
|
298
|
+
environment: Environment;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
declare type WidgetErrorCode = keyof typeof WIDGET_ERRORS;
|
|
302
|
+
|
|
303
|
+
export declare class WidgetInitError extends Error {
|
|
304
|
+
readonly code: WidgetErrorCode;
|
|
305
|
+
constructor(code: WidgetErrorCode, message?: string, cause?: unknown);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
export declare interface WidgetMessage<T = unknown> {
|
|
309
|
+
type: WidgetMessageType;
|
|
310
|
+
version: '1';
|
|
311
|
+
payload?: T;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
export declare enum WidgetMessageType {
|
|
315
|
+
INIT = "nvm:init",
|
|
316
|
+
CLOSE = "nvm:close",
|
|
317
|
+
BOOTED = "nvm:booted",
|
|
318
|
+
READY = "nvm:ready",
|
|
319
|
+
RESIZE = "nvm:resize",
|
|
320
|
+
SUCCESS = "nvm:success",
|
|
321
|
+
ERROR = "nvm:error",
|
|
322
|
+
CARD_ACTION = "nvm:card-action"
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
export declare interface WidgetSession {
|
|
326
|
+
sessionToken: string;
|
|
327
|
+
userId: string;
|
|
328
|
+
userWallet: `0x${string}`;
|
|
329
|
+
/**
|
|
330
|
+
* Hash of the NVM API key bound to this widget session user. Returned by
|
|
331
|
+
* `POST /api/v1/widgets/session` so host pages that want to call user-scoped
|
|
332
|
+
* endpoints directly (outside the iframe) have the bearer token to do so.
|
|
333
|
+
* The embedded iframe flow consumes it via the session JWT claims rather
|
|
334
|
+
* than this field.
|
|
335
|
+
*/
|
|
336
|
+
apiKeyHash: string;
|
|
337
|
+
expiresAt: string;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
export declare class WidgetSessionExpiredError extends Error {
|
|
341
|
+
readonly code: "SESSION_EXPIRED";
|
|
342
|
+
constructor();
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
export { }
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.NeverminedWidgets={}))})(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=[`local`,`sandbox`,`live`,`staging_sandbox`,`staging_live`],n={local:`http://localhost:3001`,sandbox:`https://api.sandbox.nevermined.app`,live:`https://api.live.nevermined.app`,staging_sandbox:`https://api.sandbox.nevermined.dev`,staging_live:`https://api.live.nevermined.dev`},r={local:`http://localhost:4200`,sandbox:`https://nevermined.app`,live:`https://nevermined.app`,staging_sandbox:`https://nevermined.dev`,staging_live:`https://nevermined.dev`};function i(e){return n[e]}function a(e){return r[e]}var o={MISSING_INIT_TOKEN:{numericCode:`WDG.0001`,message:`initToken is required and must be a non-empty string`},INVALID_ENVIRONMENT:{numericCode:`WDG.0002`,message:`environment must be one of: sandbox, live, staging_sandbox, staging_live, local`},INVALID_INIT_TOKEN:{numericCode:`WDG.0003`,message:`Init token is invalid or expired`},INVALID_RESPONSE:{numericCode:`WDG.0004`,message:`Server response is missing required fields`},NETWORK_ERROR:{numericCode:`WDG.0005`,message:`Network request failed`},SESSION_EXPIRED:{numericCode:`WDG.0006`,message:`Widget session has expired`}},s=class extends Error{constructor(e,t,n){super(t??o[e].message,{cause:n}),this.code=e,this.name=`WidgetInitError`}},c=class extends Error{code=`SESSION_EXPIRED`;constructor(){super(o.SESSION_EXPIRED.message),this.name=`WidgetSessionExpiredError`}},l=class extends Error{constructor(e,t,n){super(e),this.status=t,this.apiCode=n,this.name=`WidgetApiError`}},u=.8,d=class{session;expiresMs;timer=null;constructor(e){this.session=e,this.expiresMs=new Date(e.expiresAt).getTime(),Number.isNaN(this.expiresMs)&&console.warn(`[SessionManager] malformed expiresAt, session will be treated as expired:`,e.expiresAt)}isValid(){return!Number.isNaN(this.expiresMs)&&this.expiresMs>Date.now()}getToken(){return this.session.sessionToken}getSession(){return this.session}startAutoRefresh(e,t){if(this.stopAutoRefresh(),!this.isValid()){t();return}let n=Math.max(0,Math.floor((this.expiresMs-Date.now())*u));this.timer=setTimeout(()=>{this.timer=null,e().then(n=>{if(this.session=n,this.expiresMs=new Date(n.expiresAt).getTime(),!this.isValid()){t();return}this.startAutoRefresh(e,t)},e=>{console.error(`[SessionManager] session refresh failed:`,e),t()})},n)}stopAutoRefresh(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}},f=class{listeners=new Map;on(e,t){let n=this.listeners.get(e)??new Set;return n.add(t),this.listeners.set(e,n),this}off(e,t){let n=this.listeners.get(e);return n?(n.delete(t),n.size===0&&this.listeners.delete(e),this):this}once(e,t){let n=r=>{this.off(e,n),t(r)};return this.on(e,n)}removeAllListeners(e){return e===void 0?this.listeners.clear():this.listeners.delete(e),this}emit(e,t){let n=this.listeners.get(e);n&&[...n].forEach(e=>{try{e(t)}catch(e){console.error(`[TypedEventEmitter] Handler threw:`,e)}})}},p=function(e){return e.INIT=`nvm:init`,e.CLOSE=`nvm:close`,e.BOOTED=`nvm:booted`,e.READY=`nvm:ready`,e.RESIZE=`nvm:resize`,e.SUCCESS=`nvm:success`,e.ERROR=`nvm:error`,e.CARD_ACTION=`nvm:card-action`,e}({}),m=`1`,h=`1`;function g(e){return typeof e==`string`&&Object.values(p).includes(e)}function _(e,t){return{type:e,version:h,payload:t}}function v(e){if(typeof e!=`object`||!e)return{ok:!1,reason:`not an object`};let t=e;return g(t.type)?t.version===h?{ok:!0,message:{type:t.type,version:t.version,payload:t.payload}}:{ok:!1,reason:`version mismatch: received "${t.version}", expected "${h}"`}:{ok:!1,reason:typeof t.type==`string`&&t.type.startsWith(`nvm:`)?`unknown nvm: type "${t.type}"`:`missing or unknown type`}}var y=class{iframe=null;messageHandlers=new Set;protocolErrorHandlers=new Set;messageListener=null;destroyed=!1;constructor(e){if(this.expectedOrigin=e,e===`*`)throw Error(`[IframeManager] Wildcard origin "*" is not allowed — pass an explicit origin`)}create(e,t){this.iframe?.remove();let n=document.createElement(`iframe`);return n.src=e,n.style.width=`100%`,n.style.height=`100%`,n.style.border=`none`,n.style.display=`block`,n.setAttribute(`sandbox`,`allow-scripts allow-same-origin allow-forms`),t?.container||(n.style.position=`fixed`,n.style.top=`0`,n.style.left=`0`,n.style.right=`0`,n.style.bottom=`0`,n.style.zIndex=`9999`),t?.style&&Object.assign(n.style,t.style),(t?.container??document.body).appendChild(n),this.iframe=n,n}destroy(){this.destroyed=!0,this.messageListener&&=(window.removeEventListener(`message`,this.messageListener),null),this.messageHandlers.clear(),this.protocolErrorHandlers.clear(),this.iframe?.remove(),this.iframe=null}postMessage(e){this.destroyed||this.iframe?.contentWindow?.postMessage(e,this.expectedOrigin)}onMessage(e){return this.destroyed?()=>void 0:(this.messageHandlers.add(e),this.ensureListener(),()=>this.messageHandlers.delete(e))}onProtocolError(e){return this.destroyed?()=>void 0:(this.protocolErrorHandlers.add(e),this.ensureListener(),()=>this.protocolErrorHandlers.delete(e))}ensureListener(){this.messageListener||(this.messageListener=e=>{if(e.origin!==this.expectedOrigin)return;let t=v(e.data);if(!t.ok){console.warn(`[IframeManager] Discarding message from ${this.expectedOrigin}: ${t.reason}`),this.protocolErrorHandlers.forEach(e=>{try{e(t.reason)}catch(e){console.error(`[IframeManager] Protocol error handler threw:`,e)}});return}this.messageHandlers.forEach(e=>{try{e(t.message)}catch(e){console.error(`[IframeManager] Message handler threw:`,e)}})},window.addEventListener(`message`,this.messageListener))}},b={code:`UNKNOWN`,message:`Unknown widget error`},x=class{manager=null;destroyed=!1;constructor(e,t){this.session=e,this.webappBase=t}start(e){if(this.destroyed)throw Error(`[CheckoutWidget] cannot start: instance has been destroyed`);if(!e.did||typeof e.did!=`string`)throw Error(`[CheckoutWidget] did is required`);this.manager?.destroy();let t=new URL(this.webappBase).origin,n=window.location.origin,r=new URL(`/embed/checkout/${encodeURIComponent(e.did)}`,this.webappBase);r.searchParams.set(`parentOrigin`,n),e.planId&&r.searchParams.set(`planId`,e.planId);let i=new y(t);this.manager=i,i.create(r.toString(),{container:e.container}),i.onMessage(t=>this.handleMessage(t,e))}destroy(){this.destroyed=!0,this.manager?.destroy(),this.manager=null}handleMessage(e,t){switch(e.type){case p.BOOTED:this.manager?.postMessage(_(p.INIT,{sessionToken:this.session.getToken()})),t.onBooted?.();return;case p.READY:t.onReady?.();return;case p.SUCCESS:{let n=e.payload??{};t.onSuccess?.({did:n.did??t.did,planId:n.planId??t.planId,txHash:n.txHash});return}case p.ERROR:{let n=e.payload;t.onError?.(n?.error??b);return}case p.CLOSE:t.onClose?.(),this.destroy();return;default:return}}},S={code:`UNKNOWN`,message:`Unknown widget error`},C={code:`UNKNOWN`,message:`Malformed nvm:success payload — paymentMethodId missing or invalid`},w={code:`UNKNOWN`,message:`Malformed nvm:success payload — delegationId missing or invalid`},T=class{manager=null;destroyed=!1;constructor(e,t,n){this.session=e,this.webappBase=t,this.apiBase=n}enrollCard(e){this.assertAlive(`enrollCard`),this.mountIframe(`/embed/cards/enroll`,e.container).onMessage(t=>this.handleEnrollMessage(t,e))}listCards(e){this.assertAlive(`listCards`),this.mountIframe(`/embed/cards/list`,e.container).onMessage(t=>this.handleListMessage(t,e))}createDelegation(e){if(this.assertAlive(`createDelegation`),typeof e.paymentMethodId!=`string`||e.paymentMethodId.length===0)throw Error(`[DelegationsWidget] createDelegation: paymentMethodId is required`);this.mountIframe(`/embed/cards/delegate`,e.container,{paymentMethodId:e.paymentMethodId}).onMessage(t=>this.handleCreateDelegationMessage(t,e))}async revokeCard(e){if(typeof e!=`string`||e.length===0)throw Error(`[DelegationsWidget] revokeCard: paymentMethodId is required`);await this.deleteWithSession(`${this.apiBase}/api/v1/widgets/payment-methods/${encodeURIComponent(e)}`,`Failed to revoke payment method`)}async revokeDelegation(e){if(typeof e!=`string`||e.length===0)throw Error(`[DelegationsWidget] revokeDelegation: delegationId is required`);await this.deleteWithSession(`${this.apiBase}/api/v1/widgets/delegation/${encodeURIComponent(e)}`,`Failed to revoke delegation`)}destroy(){this.destroyed=!0,this.manager?.destroy(),this.manager=null}assertAlive(e){if(this.destroyed)throw Error(`[DelegationsWidget] cannot ${e}: instance has been destroyed`)}mountIframe(e,t,n={}){this.manager?.destroy();let r=new URL(this.webappBase).origin,i=window.location.origin,a=new URL(e,this.webappBase);a.searchParams.set(`parentOrigin`,i);for(let[e,t]of Object.entries(n))a.searchParams.set(e,t);let o=new y(r);return this.manager=o,o.create(a.toString(),{container:t}),o}postInitOnBooted(){this.manager?.postMessage(_(p.INIT,{sessionToken:this.session.getToken()}))}handleEnrollMessage(e,t){switch(e.type){case p.BOOTED:this.postInitOnBooted(),t.onBooted?.();return;case p.READY:t.onReady?.();return;case p.SUCCESS:{let n=(e.payload??{}).paymentMethodId;if(typeof n!=`string`||n.length===0){t.onError?.(C);return}t.onSuccess?.({paymentMethodId:n});return}case p.ERROR:{let n=e.payload;t.onError?.(n?.error??S);return}case p.CLOSE:t.onClose?.(),this.destroy();return;default:return}}handleListMessage(e,t){switch(e.type){case p.BOOTED:this.postInitOnBooted(),t.onBooted?.();return;case p.READY:t.onReady?.();return;case p.CARD_ACTION:{let n=e.payload??{};if(n.action!==`delegate`||typeof n.paymentMethodId!=`string`||n.paymentMethodId.length===0)return;t.onCardAction?.({action:n.action,paymentMethodId:n.paymentMethodId});return}case p.ERROR:{let n=e.payload;t.onError?.(n?.error??S);return}case p.CLOSE:t.onClose?.(),this.destroy();return;default:return}}handleCreateDelegationMessage(e,t){switch(e.type){case p.BOOTED:this.postInitOnBooted(),t.onBooted?.();return;case p.READY:t.onReady?.();return;case p.SUCCESS:{let n=(e.payload??{}).delegationId;if(typeof n!=`string`||n.length===0){t.onError?.(w);return}t.onSuccess?.({delegationId:n,paymentMethodId:t.paymentMethodId});return}case p.ERROR:{let n=e.payload;t.onError?.(n?.error??S);return}case p.CLOSE:t.onClose?.(),this.destroy();return;default:return}}async deleteWithSession(e,t){let n;try{n=await fetch(e,{method:`DELETE`,headers:{Authorization:`Bearer ${this.session.getToken()}`,Accept:`application/json`}})}catch(e){throw new l(e instanceof Error&&e.message?e.message:t)}if(n.ok)return;let r,i=t;try{let e=await n.json();typeof e?.message==`string`&&e.message.length>0&&(i=e.message),typeof e?.code==`string`&&(r=e.code)}catch{}throw new l(i,n.status,r)}};function E(e){if(typeof e!=`object`||!e)return!1;let t=e;return[`sessionToken`,`userId`,`expiresAt`,`apiKeyHash`].every(e=>typeof t[e]==`string`)&&typeof t.userWallet==`string`&&t.userWallet.startsWith(`0x`)}var D=class e{_checkout=null;_delegations=null;events=new f;constructor(e,t,n){this.sessionManager=e,this._account=t,this.environment=n}static async initialize(n){let{initToken:r,environment:a}=n;if(!r||typeof r!=`string`)throw new s(`MISSING_INIT_TOKEN`);if(!a||!t.includes(a))throw new s(`INVALID_ENVIRONMENT`);let o=i(a),c;try{c=await fetch(`${o}/api/v1/widgets/session`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({initToken:r})})}catch(e){throw console.error(`[NeverminedWidgets] fetch failed:`,e),new s(`NETWORK_ERROR`,void 0,e)}if(!c.ok)throw c.status===401?new s(`INVALID_INIT_TOKEN`):new s(`NETWORK_ERROR`,`Request failed with status ${c.status}`);let l;try{l=await c.json()}catch(e){throw new s(`INVALID_RESPONSE`,void 0,e)}if(!E(l))throw new s(`INVALID_RESPONSE`);let u=new d(l),f=new e(u,{userId:l.userId,userWallet:l.userWallet},a);return u.startAutoRefresh(()=>f.refreshSession(),()=>f.events.emit(`session-expired`,void 0)),f}async refreshSession(){let e=await fetch(`${i(this.environment)}/api/v1/widgets/session/refresh`,{method:`POST`,headers:{Authorization:`Bearer ${this.sessionManager.getToken()}`}});if(!e.ok)throw Error(`Session refresh failed with status ${e.status}`);let t=await e.json();if(!E(t))throw Error(`Session refresh returned an invalid response`);return t}on(e,t){return this.events.on(e,t),this}off(e,t){return this.events.off(e,t),this}get account(){return this._account}get hasValidSession(){return this.sessionManager.isValid()}getSessionToken(){if(!this.sessionManager.isValid())throw new c;return this.sessionManager.getToken()}get checkout(){return this._checkout||=new x(this.sessionManager,a(this.environment)),this._checkout}get delegations(){return this._delegations||=new T(this.sessionManager,a(this.environment),i(this.environment)),this._delegations}destroy(){this.sessionManager.stopAutoRefresh(),this._checkout?.destroy(),this._checkout=null,this._delegations?.destroy(),this._delegations=null,this.events.removeAllListeners()}};e.CheckoutWidget=x,e.DelegationsWidget=T,e.IframeManager=y,e.NeverminedWidgets=D,e.SessionManager=d,e.TypedEventEmitter=f,e.WIDGET_MESSAGE_VERSION=m,e.WidgetApiError=l,e.WidgetInitError=s,e.WidgetMessageType=p,e.WidgetSessionExpiredError=c,e.createMessage=_,e.parseMessage=v});
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,510 @@
|
|
|
1
|
+
//#region src/types.ts
|
|
2
|
+
var e = [
|
|
3
|
+
"local",
|
|
4
|
+
"sandbox",
|
|
5
|
+
"live",
|
|
6
|
+
"staging_sandbox",
|
|
7
|
+
"staging_live"
|
|
8
|
+
], t = {
|
|
9
|
+
local: "http://localhost:3001",
|
|
10
|
+
sandbox: "https://api.sandbox.nevermined.app",
|
|
11
|
+
live: "https://api.live.nevermined.app",
|
|
12
|
+
staging_sandbox: "https://api.sandbox.nevermined.dev",
|
|
13
|
+
staging_live: "https://api.live.nevermined.dev"
|
|
14
|
+
}, n = {
|
|
15
|
+
local: "http://localhost:4200",
|
|
16
|
+
sandbox: "https://nevermined.app",
|
|
17
|
+
live: "https://nevermined.app",
|
|
18
|
+
staging_sandbox: "https://nevermined.dev",
|
|
19
|
+
staging_live: "https://nevermined.dev"
|
|
20
|
+
};
|
|
21
|
+
function r(e) {
|
|
22
|
+
return t[e];
|
|
23
|
+
}
|
|
24
|
+
function i(e) {
|
|
25
|
+
return n[e];
|
|
26
|
+
}
|
|
27
|
+
//#endregion
|
|
28
|
+
//#region src/utils/errors.ts
|
|
29
|
+
var a = {
|
|
30
|
+
MISSING_INIT_TOKEN: {
|
|
31
|
+
numericCode: "WDG.0001",
|
|
32
|
+
message: "initToken is required and must be a non-empty string"
|
|
33
|
+
},
|
|
34
|
+
INVALID_ENVIRONMENT: {
|
|
35
|
+
numericCode: "WDG.0002",
|
|
36
|
+
message: "environment must be one of: sandbox, live, staging_sandbox, staging_live, local"
|
|
37
|
+
},
|
|
38
|
+
INVALID_INIT_TOKEN: {
|
|
39
|
+
numericCode: "WDG.0003",
|
|
40
|
+
message: "Init token is invalid or expired"
|
|
41
|
+
},
|
|
42
|
+
INVALID_RESPONSE: {
|
|
43
|
+
numericCode: "WDG.0004",
|
|
44
|
+
message: "Server response is missing required fields"
|
|
45
|
+
},
|
|
46
|
+
NETWORK_ERROR: {
|
|
47
|
+
numericCode: "WDG.0005",
|
|
48
|
+
message: "Network request failed"
|
|
49
|
+
},
|
|
50
|
+
SESSION_EXPIRED: {
|
|
51
|
+
numericCode: "WDG.0006",
|
|
52
|
+
message: "Widget session has expired"
|
|
53
|
+
}
|
|
54
|
+
}, o = class extends Error {
|
|
55
|
+
constructor(e, t, n) {
|
|
56
|
+
super(t ?? a[e].message, { cause: n }), this.code = e, this.name = "WidgetInitError";
|
|
57
|
+
}
|
|
58
|
+
}, s = class extends Error {
|
|
59
|
+
code = "SESSION_EXPIRED";
|
|
60
|
+
constructor() {
|
|
61
|
+
super(a.SESSION_EXPIRED.message), this.name = "WidgetSessionExpiredError";
|
|
62
|
+
}
|
|
63
|
+
}, c = class extends Error {
|
|
64
|
+
constructor(e, t, n) {
|
|
65
|
+
super(e), this.status = t, this.apiCode = n, this.name = "WidgetApiError";
|
|
66
|
+
}
|
|
67
|
+
}, l = .8, u = class {
|
|
68
|
+
session;
|
|
69
|
+
expiresMs;
|
|
70
|
+
timer = null;
|
|
71
|
+
constructor(e) {
|
|
72
|
+
this.session = e, this.expiresMs = new Date(e.expiresAt).getTime(), Number.isNaN(this.expiresMs) && console.warn("[SessionManager] malformed expiresAt, session will be treated as expired:", e.expiresAt);
|
|
73
|
+
}
|
|
74
|
+
isValid() {
|
|
75
|
+
return !Number.isNaN(this.expiresMs) && this.expiresMs > Date.now();
|
|
76
|
+
}
|
|
77
|
+
getToken() {
|
|
78
|
+
return this.session.sessionToken;
|
|
79
|
+
}
|
|
80
|
+
getSession() {
|
|
81
|
+
return this.session;
|
|
82
|
+
}
|
|
83
|
+
startAutoRefresh(e, t) {
|
|
84
|
+
if (this.stopAutoRefresh(), !this.isValid()) {
|
|
85
|
+
t();
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
let n = Math.max(0, Math.floor((this.expiresMs - Date.now()) * l));
|
|
89
|
+
this.timer = setTimeout(() => {
|
|
90
|
+
this.timer = null, e().then((n) => {
|
|
91
|
+
if (this.session = n, this.expiresMs = new Date(n.expiresAt).getTime(), !this.isValid()) {
|
|
92
|
+
t();
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
this.startAutoRefresh(e, t);
|
|
96
|
+
}, (e) => {
|
|
97
|
+
console.error("[SessionManager] session refresh failed:", e), t();
|
|
98
|
+
});
|
|
99
|
+
}, n);
|
|
100
|
+
}
|
|
101
|
+
stopAutoRefresh() {
|
|
102
|
+
this.timer !== null && (clearTimeout(this.timer), this.timer = null);
|
|
103
|
+
}
|
|
104
|
+
}, d = class {
|
|
105
|
+
listeners = /* @__PURE__ */ new Map();
|
|
106
|
+
on(e, t) {
|
|
107
|
+
let n = this.listeners.get(e) ?? /* @__PURE__ */ new Set();
|
|
108
|
+
return n.add(t), this.listeners.set(e, n), this;
|
|
109
|
+
}
|
|
110
|
+
off(e, t) {
|
|
111
|
+
let n = this.listeners.get(e);
|
|
112
|
+
return n ? (n.delete(t), n.size === 0 && this.listeners.delete(e), this) : this;
|
|
113
|
+
}
|
|
114
|
+
once(e, t) {
|
|
115
|
+
let n = (r) => {
|
|
116
|
+
this.off(e, n), t(r);
|
|
117
|
+
};
|
|
118
|
+
return this.on(e, n);
|
|
119
|
+
}
|
|
120
|
+
removeAllListeners(e) {
|
|
121
|
+
return e === void 0 ? this.listeners.clear() : this.listeners.delete(e), this;
|
|
122
|
+
}
|
|
123
|
+
emit(e, t) {
|
|
124
|
+
let n = this.listeners.get(e);
|
|
125
|
+
n && [...n].forEach((e) => {
|
|
126
|
+
try {
|
|
127
|
+
e(t);
|
|
128
|
+
} catch (e) {
|
|
129
|
+
console.error("[TypedEventEmitter] Handler threw:", e);
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
}, f = /* @__PURE__ */ function(e) {
|
|
134
|
+
return e.INIT = "nvm:init", e.CLOSE = "nvm:close", e.BOOTED = "nvm:booted", e.READY = "nvm:ready", e.RESIZE = "nvm:resize", e.SUCCESS = "nvm:success", e.ERROR = "nvm:error", e.CARD_ACTION = "nvm:card-action", e;
|
|
135
|
+
}({}), p = "1", m = "1";
|
|
136
|
+
function h(e) {
|
|
137
|
+
return typeof e == "string" && Object.values(f).includes(e);
|
|
138
|
+
}
|
|
139
|
+
function g(e, t) {
|
|
140
|
+
return {
|
|
141
|
+
type: e,
|
|
142
|
+
version: m,
|
|
143
|
+
payload: t
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
function _(e) {
|
|
147
|
+
if (typeof e != "object" || !e) return {
|
|
148
|
+
ok: !1,
|
|
149
|
+
reason: "not an object"
|
|
150
|
+
};
|
|
151
|
+
let t = e;
|
|
152
|
+
return h(t.type) ? t.version === m ? {
|
|
153
|
+
ok: !0,
|
|
154
|
+
message: {
|
|
155
|
+
type: t.type,
|
|
156
|
+
version: t.version,
|
|
157
|
+
payload: t.payload
|
|
158
|
+
}
|
|
159
|
+
} : {
|
|
160
|
+
ok: !1,
|
|
161
|
+
reason: `version mismatch: received "${t.version}", expected "${m}"`
|
|
162
|
+
} : {
|
|
163
|
+
ok: !1,
|
|
164
|
+
reason: typeof t.type == "string" && t.type.startsWith("nvm:") ? `unknown nvm: type "${t.type}"` : "missing or unknown type"
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
//#endregion
|
|
168
|
+
//#region src/iframe-manager.ts
|
|
169
|
+
var v = class {
|
|
170
|
+
iframe = null;
|
|
171
|
+
messageHandlers = /* @__PURE__ */ new Set();
|
|
172
|
+
protocolErrorHandlers = /* @__PURE__ */ new Set();
|
|
173
|
+
messageListener = null;
|
|
174
|
+
destroyed = !1;
|
|
175
|
+
constructor(e) {
|
|
176
|
+
if (this.expectedOrigin = e, e === "*") throw Error("[IframeManager] Wildcard origin \"*\" is not allowed — pass an explicit origin");
|
|
177
|
+
}
|
|
178
|
+
create(e, t) {
|
|
179
|
+
this.iframe?.remove();
|
|
180
|
+
let n = document.createElement("iframe");
|
|
181
|
+
return n.src = e, n.style.width = "100%", n.style.height = "100%", n.style.border = "none", n.style.display = "block", n.setAttribute("sandbox", "allow-scripts allow-same-origin allow-forms"), t?.container || (n.style.position = "fixed", n.style.top = "0", n.style.left = "0", n.style.right = "0", n.style.bottom = "0", n.style.zIndex = "9999"), t?.style && Object.assign(n.style, t.style), (t?.container ?? document.body).appendChild(n), this.iframe = n, n;
|
|
182
|
+
}
|
|
183
|
+
destroy() {
|
|
184
|
+
this.destroyed = !0, this.messageListener &&= (window.removeEventListener("message", this.messageListener), null), this.messageHandlers.clear(), this.protocolErrorHandlers.clear(), this.iframe?.remove(), this.iframe = null;
|
|
185
|
+
}
|
|
186
|
+
postMessage(e) {
|
|
187
|
+
this.destroyed || this.iframe?.contentWindow?.postMessage(e, this.expectedOrigin);
|
|
188
|
+
}
|
|
189
|
+
onMessage(e) {
|
|
190
|
+
return this.destroyed ? () => void 0 : (this.messageHandlers.add(e), this.ensureListener(), () => this.messageHandlers.delete(e));
|
|
191
|
+
}
|
|
192
|
+
onProtocolError(e) {
|
|
193
|
+
return this.destroyed ? () => void 0 : (this.protocolErrorHandlers.add(e), this.ensureListener(), () => this.protocolErrorHandlers.delete(e));
|
|
194
|
+
}
|
|
195
|
+
ensureListener() {
|
|
196
|
+
this.messageListener || (this.messageListener = (e) => {
|
|
197
|
+
if (e.origin !== this.expectedOrigin) return;
|
|
198
|
+
let t = _(e.data);
|
|
199
|
+
if (!t.ok) {
|
|
200
|
+
console.warn(`[IframeManager] Discarding message from ${this.expectedOrigin}: ${t.reason}`), this.protocolErrorHandlers.forEach((e) => {
|
|
201
|
+
try {
|
|
202
|
+
e(t.reason);
|
|
203
|
+
} catch (e) {
|
|
204
|
+
console.error("[IframeManager] Protocol error handler threw:", e);
|
|
205
|
+
}
|
|
206
|
+
});
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
this.messageHandlers.forEach((e) => {
|
|
210
|
+
try {
|
|
211
|
+
e(t.message);
|
|
212
|
+
} catch (e) {
|
|
213
|
+
console.error("[IframeManager] Message handler threw:", e);
|
|
214
|
+
}
|
|
215
|
+
});
|
|
216
|
+
}, window.addEventListener("message", this.messageListener));
|
|
217
|
+
}
|
|
218
|
+
}, y = {
|
|
219
|
+
code: "UNKNOWN",
|
|
220
|
+
message: "Unknown widget error"
|
|
221
|
+
}, b = class {
|
|
222
|
+
manager = null;
|
|
223
|
+
destroyed = !1;
|
|
224
|
+
constructor(e, t) {
|
|
225
|
+
this.session = e, this.webappBase = t;
|
|
226
|
+
}
|
|
227
|
+
start(e) {
|
|
228
|
+
if (this.destroyed) throw Error("[CheckoutWidget] cannot start: instance has been destroyed");
|
|
229
|
+
if (!e.did || typeof e.did != "string") throw Error("[CheckoutWidget] did is required");
|
|
230
|
+
this.manager?.destroy();
|
|
231
|
+
let t = new URL(this.webappBase).origin, n = window.location.origin, r = new URL(`/embed/checkout/${encodeURIComponent(e.did)}`, this.webappBase);
|
|
232
|
+
r.searchParams.set("parentOrigin", n), e.planId && r.searchParams.set("planId", e.planId);
|
|
233
|
+
let i = new v(t);
|
|
234
|
+
this.manager = i, i.create(r.toString(), { container: e.container }), i.onMessage((t) => this.handleMessage(t, e));
|
|
235
|
+
}
|
|
236
|
+
destroy() {
|
|
237
|
+
this.destroyed = !0, this.manager?.destroy(), this.manager = null;
|
|
238
|
+
}
|
|
239
|
+
handleMessage(e, t) {
|
|
240
|
+
switch (e.type) {
|
|
241
|
+
case f.BOOTED:
|
|
242
|
+
this.manager?.postMessage(g(f.INIT, { sessionToken: this.session.getToken() })), t.onBooted?.();
|
|
243
|
+
return;
|
|
244
|
+
case f.READY:
|
|
245
|
+
t.onReady?.();
|
|
246
|
+
return;
|
|
247
|
+
case f.SUCCESS: {
|
|
248
|
+
let n = e.payload ?? {};
|
|
249
|
+
t.onSuccess?.({
|
|
250
|
+
did: n.did ?? t.did,
|
|
251
|
+
planId: n.planId ?? t.planId,
|
|
252
|
+
txHash: n.txHash
|
|
253
|
+
});
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
case f.ERROR: {
|
|
257
|
+
let n = e.payload;
|
|
258
|
+
t.onError?.(n?.error ?? y);
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
case f.CLOSE:
|
|
262
|
+
t.onClose?.(), this.destroy();
|
|
263
|
+
return;
|
|
264
|
+
default: return;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}, x = {
|
|
268
|
+
code: "UNKNOWN",
|
|
269
|
+
message: "Unknown widget error"
|
|
270
|
+
}, S = {
|
|
271
|
+
code: "UNKNOWN",
|
|
272
|
+
message: "Malformed nvm:success payload — paymentMethodId missing or invalid"
|
|
273
|
+
}, C = {
|
|
274
|
+
code: "UNKNOWN",
|
|
275
|
+
message: "Malformed nvm:success payload — delegationId missing or invalid"
|
|
276
|
+
}, w = class {
|
|
277
|
+
manager = null;
|
|
278
|
+
destroyed = !1;
|
|
279
|
+
constructor(e, t, n) {
|
|
280
|
+
this.session = e, this.webappBase = t, this.apiBase = n;
|
|
281
|
+
}
|
|
282
|
+
enrollCard(e) {
|
|
283
|
+
this.assertAlive("enrollCard"), this.mountIframe("/embed/cards/enroll", e.container).onMessage((t) => this.handleEnrollMessage(t, e));
|
|
284
|
+
}
|
|
285
|
+
listCards(e) {
|
|
286
|
+
this.assertAlive("listCards"), this.mountIframe("/embed/cards/list", e.container).onMessage((t) => this.handleListMessage(t, e));
|
|
287
|
+
}
|
|
288
|
+
createDelegation(e) {
|
|
289
|
+
if (this.assertAlive("createDelegation"), typeof e.paymentMethodId != "string" || e.paymentMethodId.length === 0) throw Error("[DelegationsWidget] createDelegation: paymentMethodId is required");
|
|
290
|
+
this.mountIframe("/embed/cards/delegate", e.container, { paymentMethodId: e.paymentMethodId }).onMessage((t) => this.handleCreateDelegationMessage(t, e));
|
|
291
|
+
}
|
|
292
|
+
async revokeCard(e) {
|
|
293
|
+
if (typeof e != "string" || e.length === 0) throw Error("[DelegationsWidget] revokeCard: paymentMethodId is required");
|
|
294
|
+
await this.deleteWithSession(`${this.apiBase}/api/v1/widgets/payment-methods/${encodeURIComponent(e)}`, "Failed to revoke payment method");
|
|
295
|
+
}
|
|
296
|
+
async revokeDelegation(e) {
|
|
297
|
+
if (typeof e != "string" || e.length === 0) throw Error("[DelegationsWidget] revokeDelegation: delegationId is required");
|
|
298
|
+
await this.deleteWithSession(`${this.apiBase}/api/v1/widgets/delegation/${encodeURIComponent(e)}`, "Failed to revoke delegation");
|
|
299
|
+
}
|
|
300
|
+
destroy() {
|
|
301
|
+
this.destroyed = !0, this.manager?.destroy(), this.manager = null;
|
|
302
|
+
}
|
|
303
|
+
assertAlive(e) {
|
|
304
|
+
if (this.destroyed) throw Error(`[DelegationsWidget] cannot ${e}: instance has been destroyed`);
|
|
305
|
+
}
|
|
306
|
+
mountIframe(e, t, n = {}) {
|
|
307
|
+
this.manager?.destroy();
|
|
308
|
+
let r = new URL(this.webappBase).origin, i = window.location.origin, a = new URL(e, this.webappBase);
|
|
309
|
+
a.searchParams.set("parentOrigin", i);
|
|
310
|
+
for (let [e, t] of Object.entries(n)) a.searchParams.set(e, t);
|
|
311
|
+
let o = new v(r);
|
|
312
|
+
return this.manager = o, o.create(a.toString(), { container: t }), o;
|
|
313
|
+
}
|
|
314
|
+
postInitOnBooted() {
|
|
315
|
+
this.manager?.postMessage(g(f.INIT, { sessionToken: this.session.getToken() }));
|
|
316
|
+
}
|
|
317
|
+
handleEnrollMessage(e, t) {
|
|
318
|
+
switch (e.type) {
|
|
319
|
+
case f.BOOTED:
|
|
320
|
+
this.postInitOnBooted(), t.onBooted?.();
|
|
321
|
+
return;
|
|
322
|
+
case f.READY:
|
|
323
|
+
t.onReady?.();
|
|
324
|
+
return;
|
|
325
|
+
case f.SUCCESS: {
|
|
326
|
+
let n = (e.payload ?? {}).paymentMethodId;
|
|
327
|
+
if (typeof n != "string" || n.length === 0) {
|
|
328
|
+
t.onError?.(S);
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
t.onSuccess?.({ paymentMethodId: n });
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
case f.ERROR: {
|
|
335
|
+
let n = e.payload;
|
|
336
|
+
t.onError?.(n?.error ?? x);
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
case f.CLOSE:
|
|
340
|
+
t.onClose?.(), this.destroy();
|
|
341
|
+
return;
|
|
342
|
+
default: return;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
handleListMessage(e, t) {
|
|
346
|
+
switch (e.type) {
|
|
347
|
+
case f.BOOTED:
|
|
348
|
+
this.postInitOnBooted(), t.onBooted?.();
|
|
349
|
+
return;
|
|
350
|
+
case f.READY:
|
|
351
|
+
t.onReady?.();
|
|
352
|
+
return;
|
|
353
|
+
case f.CARD_ACTION: {
|
|
354
|
+
let n = e.payload ?? {};
|
|
355
|
+
if (n.action !== "delegate" || typeof n.paymentMethodId != "string" || n.paymentMethodId.length === 0) return;
|
|
356
|
+
t.onCardAction?.({
|
|
357
|
+
action: n.action,
|
|
358
|
+
paymentMethodId: n.paymentMethodId
|
|
359
|
+
});
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
case f.ERROR: {
|
|
363
|
+
let n = e.payload;
|
|
364
|
+
t.onError?.(n?.error ?? x);
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
case f.CLOSE:
|
|
368
|
+
t.onClose?.(), this.destroy();
|
|
369
|
+
return;
|
|
370
|
+
default: return;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
handleCreateDelegationMessage(e, t) {
|
|
374
|
+
switch (e.type) {
|
|
375
|
+
case f.BOOTED:
|
|
376
|
+
this.postInitOnBooted(), t.onBooted?.();
|
|
377
|
+
return;
|
|
378
|
+
case f.READY:
|
|
379
|
+
t.onReady?.();
|
|
380
|
+
return;
|
|
381
|
+
case f.SUCCESS: {
|
|
382
|
+
let n = (e.payload ?? {}).delegationId;
|
|
383
|
+
if (typeof n != "string" || n.length === 0) {
|
|
384
|
+
t.onError?.(C);
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
t.onSuccess?.({
|
|
388
|
+
delegationId: n,
|
|
389
|
+
paymentMethodId: t.paymentMethodId
|
|
390
|
+
});
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
case f.ERROR: {
|
|
394
|
+
let n = e.payload;
|
|
395
|
+
t.onError?.(n?.error ?? x);
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
case f.CLOSE:
|
|
399
|
+
t.onClose?.(), this.destroy();
|
|
400
|
+
return;
|
|
401
|
+
default: return;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
async deleteWithSession(e, t) {
|
|
405
|
+
let n;
|
|
406
|
+
try {
|
|
407
|
+
n = await fetch(e, {
|
|
408
|
+
method: "DELETE",
|
|
409
|
+
headers: {
|
|
410
|
+
Authorization: `Bearer ${this.session.getToken()}`,
|
|
411
|
+
Accept: "application/json"
|
|
412
|
+
}
|
|
413
|
+
});
|
|
414
|
+
} catch (e) {
|
|
415
|
+
throw new c(e instanceof Error && e.message ? e.message : t);
|
|
416
|
+
}
|
|
417
|
+
if (n.ok) return;
|
|
418
|
+
let r, i = t;
|
|
419
|
+
try {
|
|
420
|
+
let e = await n.json();
|
|
421
|
+
typeof e?.message == "string" && e.message.length > 0 && (i = e.message), typeof e?.code == "string" && (r = e.code);
|
|
422
|
+
} catch {}
|
|
423
|
+
throw new c(i, n.status, r);
|
|
424
|
+
}
|
|
425
|
+
};
|
|
426
|
+
//#endregion
|
|
427
|
+
//#region src/nevermined-widgets.ts
|
|
428
|
+
function T(e) {
|
|
429
|
+
if (typeof e != "object" || !e) return !1;
|
|
430
|
+
let t = e;
|
|
431
|
+
return [
|
|
432
|
+
"sessionToken",
|
|
433
|
+
"userId",
|
|
434
|
+
"expiresAt",
|
|
435
|
+
"apiKeyHash"
|
|
436
|
+
].every((e) => typeof t[e] == "string") && typeof t.userWallet == "string" && t.userWallet.startsWith("0x");
|
|
437
|
+
}
|
|
438
|
+
var E = class t {
|
|
439
|
+
_checkout = null;
|
|
440
|
+
_delegations = null;
|
|
441
|
+
events = new d();
|
|
442
|
+
constructor(e, t, n) {
|
|
443
|
+
this.sessionManager = e, this._account = t, this.environment = n;
|
|
444
|
+
}
|
|
445
|
+
static async initialize(n) {
|
|
446
|
+
let { initToken: i, environment: a } = n;
|
|
447
|
+
if (!i || typeof i != "string") throw new o("MISSING_INIT_TOKEN");
|
|
448
|
+
if (!a || !e.includes(a)) throw new o("INVALID_ENVIRONMENT");
|
|
449
|
+
let s = r(a), c;
|
|
450
|
+
try {
|
|
451
|
+
c = await fetch(`${s}/api/v1/widgets/session`, {
|
|
452
|
+
method: "POST",
|
|
453
|
+
headers: { "Content-Type": "application/json" },
|
|
454
|
+
body: JSON.stringify({ initToken: i })
|
|
455
|
+
});
|
|
456
|
+
} catch (e) {
|
|
457
|
+
throw console.error("[NeverminedWidgets] fetch failed:", e), new o("NETWORK_ERROR", void 0, e);
|
|
458
|
+
}
|
|
459
|
+
if (!c.ok) throw c.status === 401 ? new o("INVALID_INIT_TOKEN") : new o("NETWORK_ERROR", `Request failed with status ${c.status}`);
|
|
460
|
+
let l;
|
|
461
|
+
try {
|
|
462
|
+
l = await c.json();
|
|
463
|
+
} catch (e) {
|
|
464
|
+
throw new o("INVALID_RESPONSE", void 0, e);
|
|
465
|
+
}
|
|
466
|
+
if (!T(l)) throw new o("INVALID_RESPONSE");
|
|
467
|
+
let d = new u(l), f = new t(d, {
|
|
468
|
+
userId: l.userId,
|
|
469
|
+
userWallet: l.userWallet
|
|
470
|
+
}, a);
|
|
471
|
+
return d.startAutoRefresh(() => f.refreshSession(), () => f.events.emit("session-expired", void 0)), f;
|
|
472
|
+
}
|
|
473
|
+
async refreshSession() {
|
|
474
|
+
let e = await fetch(`${r(this.environment)}/api/v1/widgets/session/refresh`, {
|
|
475
|
+
method: "POST",
|
|
476
|
+
headers: { Authorization: `Bearer ${this.sessionManager.getToken()}` }
|
|
477
|
+
});
|
|
478
|
+
if (!e.ok) throw Error(`Session refresh failed with status ${e.status}`);
|
|
479
|
+
let t = await e.json();
|
|
480
|
+
if (!T(t)) throw Error("Session refresh returned an invalid response");
|
|
481
|
+
return t;
|
|
482
|
+
}
|
|
483
|
+
on(e, t) {
|
|
484
|
+
return this.events.on(e, t), this;
|
|
485
|
+
}
|
|
486
|
+
off(e, t) {
|
|
487
|
+
return this.events.off(e, t), this;
|
|
488
|
+
}
|
|
489
|
+
get account() {
|
|
490
|
+
return this._account;
|
|
491
|
+
}
|
|
492
|
+
get hasValidSession() {
|
|
493
|
+
return this.sessionManager.isValid();
|
|
494
|
+
}
|
|
495
|
+
getSessionToken() {
|
|
496
|
+
if (!this.sessionManager.isValid()) throw new s();
|
|
497
|
+
return this.sessionManager.getToken();
|
|
498
|
+
}
|
|
499
|
+
get checkout() {
|
|
500
|
+
return this._checkout ||= new b(this.sessionManager, i(this.environment)), this._checkout;
|
|
501
|
+
}
|
|
502
|
+
get delegations() {
|
|
503
|
+
return this._delegations ||= new w(this.sessionManager, i(this.environment), r(this.environment)), this._delegations;
|
|
504
|
+
}
|
|
505
|
+
destroy() {
|
|
506
|
+
this.sessionManager.stopAutoRefresh(), this._checkout?.destroy(), this._checkout = null, this._delegations?.destroy(), this._delegations = null, this.events.removeAllListeners();
|
|
507
|
+
}
|
|
508
|
+
};
|
|
509
|
+
//#endregion
|
|
510
|
+
export { b as CheckoutWidget, w as DelegationsWidget, v as IframeManager, E as NeverminedWidgets, u as SessionManager, d as TypedEventEmitter, p as WIDGET_MESSAGE_VERSION, c as WidgetApiError, o as WidgetInitError, f as WidgetMessageType, s as WidgetSessionExpiredError, g as createMessage, _ as parseMessage };
|
package/package.json
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@nevermined-io/ui-widgets",
|
|
3
|
+
"version": "0.3.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"main": "./dist/index.js",
|
|
6
|
+
"module": "./dist/index.mjs",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.mjs",
|
|
12
|
+
"require": "./dist/index.js"
|
|
13
|
+
},
|
|
14
|
+
"./package.json": "./package.json"
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"dist",
|
|
18
|
+
"!**/*.tsbuildinfo"
|
|
19
|
+
],
|
|
20
|
+
"devDependencies": {}
|
|
21
|
+
}
|