@ledewire/browser 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +12 -0
  2. package/dist/index.d.ts +1457 -33
  3. package/dist/index.js +53 -28
  4. package/dist/index.js.map +1 -1
  5. package/dist/ledewire.min.js +1 -1
  6. package/dist/ledewire.min.js.map +1 -1
  7. package/package.json +2 -2
  8. package/dist/client.d.ts +0 -89
  9. package/dist/client.d.ts.map +0 -1
  10. package/dist/client.test.d.ts +0 -2
  11. package/dist/client.test.d.ts.map +0 -1
  12. package/dist/index.d.ts.map +0 -1
  13. package/dist/local-storage-adapter.d.ts +0 -27
  14. package/dist/local-storage-adapter.d.ts.map +0 -1
  15. package/dist/local-storage-adapter.test.d.ts +0 -2
  16. package/dist/local-storage-adapter.test.d.ts.map +0 -1
  17. package/dist/resources/auth.d.ts +0 -45
  18. package/dist/resources/auth.d.ts.map +0 -1
  19. package/dist/resources/auth.test.d.ts +0 -2
  20. package/dist/resources/auth.test.d.ts.map +0 -1
  21. package/dist/resources/checkout.d.ts +0 -31
  22. package/dist/resources/checkout.d.ts.map +0 -1
  23. package/dist/resources/checkout.test.d.ts +0 -2
  24. package/dist/resources/checkout.test.d.ts.map +0 -1
  25. package/dist/resources/content.d.ts +0 -27
  26. package/dist/resources/content.d.ts.map +0 -1
  27. package/dist/resources/content.test.d.ts +0 -2
  28. package/dist/resources/content.test.d.ts.map +0 -1
  29. package/dist/resources/purchases.d.ts +0 -38
  30. package/dist/resources/purchases.d.ts.map +0 -1
  31. package/dist/resources/purchases.test.d.ts +0 -2
  32. package/dist/resources/purchases.test.d.ts.map +0 -1
  33. package/dist/resources/wallet.d.ts +0 -44
  34. package/dist/resources/wallet.d.ts.map +0 -1
  35. package/dist/resources/wallet.test.d.ts +0 -2
  36. package/dist/resources/wallet.test.d.ts.map +0 -1
package/dist/index.d.ts CHANGED
@@ -1,33 +1,1457 @@
1
- /**
2
- * @ledewire/browser
3
- *
4
- * LedeWire SDK for browser environments.
5
- * Enables buyer authentication, content checkout, wallet funding,
6
- * and purchases — embeddable with a single `<script>` tag.
7
- *
8
- * **CDN usage (no build step required):**
9
- * ```html
10
- * <script src="https://cdn.jsdelivr.net/npm/@ledewire/browser@1/dist/ledewire.min.js"></script>
11
- * <script>
12
- * const lw = Ledewire.init({ apiKey: 'your_api_key' })
13
- * const state = await lw.checkout.state('content-id')
14
- * // state.checkout_state.next_required_action:
15
- * // 'authenticate' | 'fund_wallet' | 'purchase' | 'view_content'
16
- * </script>
17
- * ```
18
- *
19
- * **npm / bundler usage:**
20
- * ```ts
21
- * import { init } from '@ledewire/browser'
22
- * const lw = init({ apiKey: 'your_api_key' })
23
- * ```
24
- *
25
- * @see {@link https://docs.ledewire.org} for guides and examples
26
- * @packageDocumentation
27
- */
28
- export type { AuthenticationResponse, CheckoutNextAction, CheckoutState, CheckoutStateResponse, ContentAccessInfo, ContentWithAccessResponse, NextRequiredAction, PurchaseCreateRequest, PurchaseResponse, StoredTokens, TokenStorage, WalletBalanceResponse, WalletPaymentSessionRequest, WalletPaymentSessionResponse, WalletPaymentStatusResponse, WalletTransactionItem, } from '@ledewire/core';
29
- export { AuthError, ForbiddenError, LedewireError, MemoryTokenStorage, NotFoundError, PurchaseError, parseExpiresAt, } from '@ledewire/core';
30
- export { init } from './client.js';
31
- export type { BrowserClientConfig } from './client.js';
32
- export { localStorageAdapter } from './local-storage-adapter.js';
33
- //# sourceMappingURL=index.d.ts.map
1
+ /**
2
+ * @ledewire/browser
3
+ *
4
+ * LedeWire SDK for browser environments.
5
+ * Enables buyer authentication, content checkout, wallet funding,
6
+ * and purchases — embeddable with a single `<script>` tag.
7
+ *
8
+ * **CDN usage (no build step required):**
9
+ * ```html
10
+ * <script src="https://cdn.jsdelivr.net/npm/@ledewire/browser@1/dist/ledewire.min.js"></script>
11
+ * <script>
12
+ * const lw = Ledewire.init({ apiKey: 'your_api_key' })
13
+ * const state = await lw.checkout.state('content-id')
14
+ * // state.checkout_state.next_required_action:
15
+ * // 'authenticate' | 'fund_wallet' | 'purchase' | 'view_content'
16
+ * </script>
17
+ * ```
18
+ *
19
+ * **npm / bundler usage:**
20
+ * ```ts
21
+ * import { init } from '@ledewire/browser'
22
+ * const lw = init({ apiKey: 'your_api_key' })
23
+ * ```
24
+ *
25
+ * @see {@link https://docs.ledewire.org} for guides and examples
26
+ * @packageDocumentation
27
+ */
28
+
29
+ /**
30
+ * Core TypeScript types for the LedeWire SDK.
31
+ *
32
+ * API shape types are generated from `ledewire.yml`
33
+ * (run `pnpm --filter @ledewire/core generate:types` to regenerate).
34
+ * SDK-internal types (token storage, stored tokens) are hand-written below.
35
+ *
36
+ * @module
37
+ */
38
+
39
+ /** JWT bearer token response returned by all buyer authentication endpoints. */
40
+ export declare type AuthenticationResponse = components['schemas']['AuthenticationResponse'];
41
+
42
+ /**
43
+ * Thrown when the request lacks valid authentication credentials,
44
+ * or when a token refresh fails and re-authentication is required.
45
+ */
46
+ export declare class AuthError extends LedewireError {
47
+ constructor(message: string, code?: number);
48
+ }
49
+
50
+ /** Request body for buyer email/password login. */
51
+ declare type AuthLoginEmailRequest = components['schemas']['AuthLoginEmailRequest'];
52
+
53
+ /** Request body for buyer Google OAuth login. */
54
+ declare type AuthLoginOAuthRequest = components['schemas']['AuthLoginOAuthRequest'];
55
+
56
+ /** Request body for buyer email/password signup. */
57
+ declare type AuthSignupRequest = components['schemas']['AuthSignupRequest'];
58
+
59
+ /**
60
+ * Buyer authentication: signup, email/password login, Google OAuth.
61
+ *
62
+ * Obtain via `lw.auth` — do not construct directly.
63
+ *
64
+ * @example
65
+ * ```ts
66
+ * const lw = Ledewire.init({ apiKey: 'your_api_key' })
67
+ * await lw.auth.loginWithEmail({ email: 'u@example.com', password: 'pw' })
68
+ * ```
69
+ */
70
+ declare class BrowserAuthNamespace {
71
+ private readonly http;
72
+ private readonly tokenManager;
73
+ /* Excluded from this release type: __constructor */
74
+ /**
75
+ * Register a new buyer account with email and password.
76
+ * Tokens are stored automatically after successful signup.
77
+ *
78
+ * @param body - Signup credentials and display name.
79
+ * @returns The authentication token response.
80
+ */
81
+ signup(body: AuthSignupRequest): Promise<AuthenticationResponse>;
82
+ /**
83
+ * Log in with email and password.
84
+ * Tokens are stored automatically after successful login.
85
+ *
86
+ * @param body - Email and password credentials.
87
+ * @returns The authentication token response.
88
+ */
89
+ loginWithEmail(body: AuthLoginEmailRequest): Promise<AuthenticationResponse>;
90
+ /**
91
+ * Log in with a Google ID token obtained from the Google OAuth flow.
92
+ * Tokens are stored automatically after successful login.
93
+ *
94
+ * @param body - The Google ID token.
95
+ * @returns The authentication token response.
96
+ */
97
+ loginWithGoogle(body: AuthLoginOAuthRequest): Promise<AuthenticationResponse>;
98
+ private storeTokens;
99
+ }
100
+
101
+ /**
102
+ * The LedeWire browser client.
103
+ * Access buyer flows through the namespaced properties.
104
+ *
105
+ * @remarks
106
+ * Instantiate with {@link init} rather than constructing directly.
107
+ */
108
+ declare class BrowserClient {
109
+ readonly _http: HttpClient;
110
+ readonly _tokenManager: TokenManager;
111
+ readonly _config: BrowserClientConfig;
112
+ /** Platform-level public configuration (no auth required) */
113
+ readonly config: BrowserConfigNamespace;
114
+ /** Buyer authentication: email/password signup/login, Google, password reset */
115
+ readonly auth: BrowserAuthNamespace;
116
+ /** Checkout state machine: determines next action for a piece of content */
117
+ readonly checkout: CheckoutNamespace;
118
+ /** Wallet: balance, fund via payment session, transaction history */
119
+ readonly wallet: BrowserWalletNamespace;
120
+ /** Content purchases for the authenticated buyer */
121
+ readonly purchases: BrowserPurchasesNamespace;
122
+ /** Public content with per-user access information */
123
+ readonly content: BrowserContentNamespace;
124
+ /* Excluded from this release type: __constructor */
125
+ }
126
+
127
+ /**
128
+ * Configuration options for the LedeWire browser client.
129
+ */
130
+ export declare interface BrowserClientConfig {
131
+ /**
132
+ * LedeWire API key that identifies the store.
133
+ * Obtained from the LedeWire merchant dashboard.
134
+ */
135
+ apiKey: string;
136
+ /**
137
+ * Override the API base URL.
138
+ * Defaults to `https://api.ledewire.com`.
139
+ */
140
+ baseUrl?: string;
141
+ /**
142
+ * Token storage adapter.
143
+ * Defaults to {@link MemoryTokenStorage} (in-memory, most secure).
144
+ *
145
+ * To persist sessions across page reloads, use the built-in
146
+ * `localStorageAdapter`:
147
+ * ```ts
148
+ * import { init, localStorageAdapter } from '@ledewire/browser'
149
+ * const lw = init({ apiKey: '...', storage: localStorageAdapter() })
150
+ * ```
151
+ */
152
+ storage?: TokenStorage;
153
+ /**
154
+ * Called when the user's session expires and cannot be refreshed.
155
+ * Use this to show a re-authentication prompt.
156
+ *
157
+ * @example
158
+ * ```ts
159
+ * onAuthExpired: () => showLoginModal()
160
+ * ```
161
+ */
162
+ onAuthExpired?: () => void;
163
+ }
164
+
165
+ /**
166
+ * Platform-level configuration for browser clients.
167
+ *
168
+ * Obtain via `client.config` — do not construct directly.
169
+ */
170
+ declare class BrowserConfigNamespace {
171
+ protected readonly http: HttpClient;
172
+ /* Excluded from this release type: __constructor */
173
+ /**
174
+ * Returns platform-level public configuration.
175
+ * No authentication required — safe to call before the user has signed in.
176
+ *
177
+ * Use `google_client_id` to initialise the Google Identity Services library
178
+ * on the storefront login page without requiring a prior authenticated call.
179
+ *
180
+ * @example
181
+ * ```ts
182
+ * const lw = init({ apiKey: 'your_api_key' })
183
+ * const { google_client_id } = await lw.config.getPublic()
184
+ * google.accounts.id.initialize({ client_id: google_client_id, callback })
185
+ * ```
186
+ */
187
+ getPublic(): Promise<PublicConfigResponse>;
188
+ }
189
+
190
+ /**
191
+ * Buyer content namespace — fetch content with real-time access information.
192
+ *
193
+ * Obtain via `lw.content` — do not construct directly.
194
+ *
195
+ * @example
196
+ * ```ts
197
+ * const { content, access } = await lw.content.getWithAccess('content-id')
198
+ * if (access.has_access) showFullContent(content)
199
+ * ```
200
+ */
201
+ declare class BrowserContentNamespace {
202
+ protected readonly http: HttpClient;
203
+ constructor(http: HttpClient);
204
+ /**
205
+ * Returns a content item together with access information for the
206
+ * authenticated buyer (or a generic access response when unauthenticated).
207
+ *
208
+ * @param id - The content ID.
209
+ * @param userId - Optional user ID to check a specific user's access status.
210
+ * @returns The content item with access information.
211
+ */
212
+ getWithAccess(id: string, userId?: string): Promise<ContentWithAccessResponse>;
213
+ }
214
+
215
+ /**
216
+ * Buyer purchases namespace — create and retrieve content purchases.
217
+ *
218
+ * Obtain via `lw.purchases` — do not construct directly.
219
+ *
220
+ * @example
221
+ * ```ts
222
+ * await lw.purchases.create({ content_id: 'content-id' })
223
+ * const all = await lw.purchases.list()
224
+ * ```
225
+ */
226
+ declare class BrowserPurchasesNamespace {
227
+ protected readonly http: HttpClient;
228
+ constructor(http: HttpClient);
229
+ /**
230
+ * Completes a content purchase using the buyer's wallet balance.
231
+ *
232
+ * @param body - The content ID and expected price in cents.
233
+ * @returns The completed purchase record.
234
+ */
235
+ create(body: PurchaseCreateRequest): Promise<PurchaseResponse>;
236
+ /**
237
+ * Returns all purchases made by the authenticated buyer.
238
+ *
239
+ * @returns A list of purchase records, newest first.
240
+ */
241
+ list(): Promise<PurchaseResponse[]>;
242
+ /**
243
+ * Returns a single purchase by ID.
244
+ *
245
+ * @param id - The purchase ID.
246
+ * @returns The purchase record.
247
+ */
248
+ get(id: string): Promise<PurchaseResponse>;
249
+ }
250
+
251
+ /**
252
+ * Buyer wallet namespace — balance, transactions, and payment session management.
253
+ *
254
+ * Obtain via `lw.wallet` — do not construct directly.
255
+ *
256
+ * @example
257
+ * ```ts
258
+ * const { balance_cents } = await lw.wallet.balance()
259
+ * const session = await lw.wallet.createPaymentSession({ amount_cents: 500 })
260
+ * ```
261
+ */
262
+ declare class BrowserWalletNamespace {
263
+ protected readonly http: HttpClient;
264
+ constructor(http: HttpClient);
265
+ /**
266
+ * Returns the authenticated buyer's current wallet balance.
267
+ *
268
+ * @returns The current wallet balance in cents.
269
+ */
270
+ balance(): Promise<WalletBalanceResponse>;
271
+ /**
272
+ * Returns the authenticated buyer's wallet transaction history, newest first.
273
+ *
274
+ * @returns A list of completed wallet transaction entries.
275
+ */
276
+ transactions(): Promise<WalletTransactionItem[]>;
277
+ /**
278
+ * Creates a payment session for funding the buyer's wallet.
279
+ *
280
+ * @param body - The amount and currency to fund.
281
+ * @returns Payment session details for use with the payment provider widget.
282
+ */
283
+ createPaymentSession(body: WalletPaymentSessionRequest): Promise<WalletPaymentSessionResponse>;
284
+ /**
285
+ * Polls the status of a wallet funding payment session.
286
+ *
287
+ * @param sessionId - The session ID returned by `createPaymentSession`.
288
+ * @returns The current payment status.
289
+ */
290
+ getPaymentStatus(sessionId: string): Promise<WalletPaymentStatusResponse>;
291
+ }
292
+
293
+ /**
294
+ * Checkout namespace — buyer checkout state for a specific content item.
295
+ *
296
+ * Obtain via `lw.checkout` — do not construct directly.
297
+ *
298
+ * @example
299
+ * ```ts
300
+ * const state = await lw.checkout.state('content-id')
301
+ * // state.checkout_state.next_required_action:
302
+ * // 'authenticate' | 'fund_wallet' | 'purchase' | 'view_content'
303
+ * ```
304
+ */
305
+ declare class CheckoutNamespace {
306
+ protected readonly http: HttpClient;
307
+ constructor(http: HttpClient);
308
+ /**
309
+ * Returns the authenticated buyer's checkout readiness for a given piece of
310
+ * content. Indicates whether the buyer needs to authenticate, fund their
311
+ * wallet, or purchase before accessing the content.
312
+ *
313
+ * Works without authentication — returns anonymous checkout state when the
314
+ * buyer is not logged in.
315
+ *
316
+ * @param contentId - The content item ID.
317
+ * @returns The checkout state, including what action is required next.
318
+ */
319
+ state(contentId: string): Promise<CheckoutStateResponse>;
320
+ }
321
+
322
+ /**
323
+ * Next step in a content checkout flow.
324
+ * Extends `NextRequiredAction` with the terminal `view_content` state
325
+ * (returned once the buyer has purchased and can view the content).
326
+ */
327
+ export declare type CheckoutNextAction = 'authenticate' | 'fund_wallet' | 'purchase' | 'view_content';
328
+
329
+ /** Checkout state machine result for a specific content item. */
330
+ export declare interface CheckoutState {
331
+ content_id: string;
332
+ checkout_state: {
333
+ is_authenticated: boolean;
334
+ has_sufficient_funds: boolean;
335
+ has_purchased: boolean;
336
+ next_required_action: CheckoutNextAction;
337
+ };
338
+ }
339
+
340
+ /** Full checkout state for a buyer/content pair, including auth and fund status. */
341
+ export declare type CheckoutStateResponse = components['schemas']['CheckoutStateResponse'];
342
+
343
+ declare interface components {
344
+ schemas: {
345
+ /** @description Platform-level public configuration. No authentication required. */
346
+ PublicConfigResponse: {
347
+ /** @description Google OAuth client ID for initialising the Google Identity Services library. */
348
+ google_client_id: string;
349
+ };
350
+ ContentAccessInfo: {
351
+ user_id: string | null;
352
+ has_purchased: boolean;
353
+ has_sufficient_funds: boolean;
354
+ wallet_balance_cents: number;
355
+ /** @enum {string} */
356
+ next_required_action: 'authenticate' | 'fund_wallet' | 'purchase' | 'none';
357
+ };
358
+ AuthenticationResponse: {
359
+ /** @enum {string} */
360
+ token_type: 'Bearer';
361
+ /** @example eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIwOTM1N2MyMi0zODlhLTRmYWItYjE2Ni04MjJlNTJhNWJmNWUiLCJyb2xlIjoiYnV5ZXIiLCJidXllcl9jbGFpbXMiOnsidXNlcl9pZCI6IjA5MzU3YzIyLTM4OWEtNGZhYi1iMTY2LTgyMmU1MmE1YmY1ZSIsImVtYWlsIjoidGVzdC0xM0BleGFtcGxlLmNvbSJ9LCJpc3MiOiJMZWRlV2lyZSBBUEkiLCJhdWQiOiJ3ZWIiLCJleHAiOjE3NDc0OTk5NzMsImlhdCI6MTc0NzQ5ODE3MywibmJmIjoxNzQ3NDk4MTczLCJqdGkiOiIwZTMyYzNkNi02OWQwLTRmNTItYTczNS1hZTJiOGNlMmY1MmQiLCJ0b2tlbl9tZXRhZGF0YSI6eyJjcmVhdGVkX2F0IjoiMjAyNS0wNS0xN1QxNjowOTozM1oiLCJleHBpcmVzX2F0IjoiMjAyNS0wNS0xN1QxNjozOTozM1oiLCJ0b2tlbl9pZCI6IjBlMzJjM2Q2LTY5ZDAtNGY1Mi1hNzM1LWFlMmI4Y2UyZjUyZCJ9fQ.VSFsm5ysjtZLheVfhv6DWwH1A9zn_WA6rnGOlPR1R3U */
362
+ access_token: string;
363
+ refresh_token: string;
364
+ /**
365
+ * Format: date-time
366
+ * @description When the Access Token expires
367
+ */
368
+ expires_at: string;
369
+ };
370
+ /** @description Token response for merchant authentication. Includes stores the user has access to so the client can prompt for store selection. */
371
+ MerchantAuthenticationResponse: {
372
+ /** @enum {string} */
373
+ token_type: 'Bearer';
374
+ access_token: string;
375
+ refresh_token: string;
376
+ /** Format: date-time */
377
+ expires_at: string;
378
+ /** @description Stores the authenticated user can manage, for store-selection on the client. */
379
+ stores: components['schemas']['MerchantLoginStore'][];
380
+ };
381
+ /** @description A store the authenticated merchant user has access to. */
382
+ MerchantLoginStore: {
383
+ id: string;
384
+ name: string;
385
+ /**
386
+ * @description Derived role. `owner` if the user owns this store; `author` if they have author permissions only.
387
+ * @enum {string}
388
+ */
389
+ role: 'owner' | 'author';
390
+ };
391
+ JWTClaims: {
392
+ /** @description User or Store identifier */
393
+ sub?: string;
394
+ /** @enum {string} */
395
+ role?: 'buyer' | 'seller-view' | 'seller-full' | 'merchant';
396
+ seller_claims?: {
397
+ seller_id?: string;
398
+ };
399
+ buyer_claims?: {
400
+ user_id?: string;
401
+ email?: string;
402
+ };
403
+ /** @description Present on merchant tokens */
404
+ user_claims?: {
405
+ id?: string;
406
+ email?: string;
407
+ full_name?: string;
408
+ };
409
+ iat?: number;
410
+ exp?: number;
411
+ nbf?: number;
412
+ iss?: string;
413
+ aud?: string;
414
+ token_metadata?: {
415
+ /** Format: date-time */
416
+ created_at?: string;
417
+ /** Format: date-time */
418
+ expires_at?: string;
419
+ token_id?: string;
420
+ };
421
+ };
422
+ MessageResponse: {
423
+ message: string;
424
+ };
425
+ ErrorResponse: {
426
+ error: {
427
+ code: number;
428
+ message: string;
429
+ };
430
+ };
431
+ AuthSignupRequest: {
432
+ email: string;
433
+ password: string;
434
+ name: string;
435
+ };
436
+ AuthLoginEmailRequest: {
437
+ email?: string;
438
+ password?: string;
439
+ };
440
+ AuthLoginOAuthRequest: {
441
+ id_token?: string;
442
+ };
443
+ MerchantEmailLoginRequest: {
444
+ email: string;
445
+ password: string;
446
+ };
447
+ MerchantGoogleLoginRequest: {
448
+ id_token: string;
449
+ };
450
+ AuthLoginApiKeyRequest: {
451
+ key: string;
452
+ secret?: string;
453
+ };
454
+ AuthTokenRefreshRequest: {
455
+ refresh_token?: string;
456
+ };
457
+ ManageableStore: {
458
+ store_id: string;
459
+ store_name: string;
460
+ store_key: string;
461
+ /**
462
+ * @description Derived role. `owner` if the user owns this store; `author` if they have author permissions only.
463
+ * @enum {string}
464
+ */
465
+ role: 'owner' | 'author';
466
+ /** @description Whether the authenticated user has author permissions for this store. */
467
+ is_author: boolean;
468
+ logo: string | null;
469
+ };
470
+ MerchantUser: {
471
+ id: string;
472
+ user_id: string | null;
473
+ store_id: string;
474
+ /**
475
+ * @description Ownership flag expressed as a string. `owner` when `is_owner` is true; `null` for non-owner members (authors or uninvited users).
476
+ * @enum {string|null}
477
+ */
478
+ role: 'owner' | null;
479
+ /** @description Whether this user can create and manage their own content. */
480
+ is_author: boolean;
481
+ /** @description Per-author fee override in basis points (1/100th of a percent). Overrides the store's `default_author_fee_bps` when set. `null` means the store default applies. */
482
+ author_fee_bps: number | null;
483
+ /** Format: date-time */
484
+ invited_at: string | null;
485
+ /** Format: date-time */
486
+ accepted_at: string | null;
487
+ email: string | null;
488
+ };
489
+ MerchantInviteRequest: {
490
+ /** @description Email address of the user to invite to the store. */
491
+ email: string;
492
+ /**
493
+ * @description Whether to grant author permissions. Defaults to `true`.
494
+ * @default true
495
+ */
496
+ is_author: boolean;
497
+ /** @description Per-author fee override in basis points (0–10000). Overrides the store's `default_author_fee_bps`. `null` or omitted means the store default applies. */
498
+ author_fee_bps?: number | null;
499
+ };
500
+ MerchantInviteResponse: {
501
+ invitation_token: string;
502
+ email: string;
503
+ /** @enum {string|null} */
504
+ role: 'owner' | null;
505
+ is_author: boolean;
506
+ /** @description Per-author fee override set at invitation time. */
507
+ author_fee_bps?: number | null;
508
+ /** Format: date-time */
509
+ expires_at: string;
510
+ };
511
+ WalletPaymentSessionRequest: {
512
+ /** @description Amount to fund the wallet in cents */
513
+ amount_cents: number;
514
+ /**
515
+ * @description Currency code (defaults to USD)
516
+ * @default usd
517
+ */
518
+ currency: string;
519
+ /** @description Additional metadata to include with the payment session */
520
+ metadata?: Record<string, never>;
521
+ };
522
+ WalletPaymentSessionResponse: {
523
+ /** @description The client secret used by the payment widget to confirm the payment */
524
+ client_secret: string;
525
+ /** @description The ID of the created payment session */
526
+ session_id: string;
527
+ /** @description The payment public key to be used during the payment processing */
528
+ public_key: string;
529
+ };
530
+ /** @description A payment provider webhook event object */
531
+ PaymentWebhookEvent: {
532
+ /** @description Unique identifier for the event */
533
+ id?: string;
534
+ /** @description Type of event (e.g., payment_intent.succeeded, payment_intent.payment_failed) */
535
+ type?: string;
536
+ /** @description Event data containing the object that triggered the event */
537
+ data?: Record<string, never>;
538
+ };
539
+ WalletBalanceResponse: {
540
+ balance_cents: number;
541
+ };
542
+ WalletTransactionItem: {
543
+ /** @description ID of the transaction entry (matches the source record) */
544
+ id: string;
545
+ /**
546
+ * @description Direction relative to the user's wallet
547
+ * @enum {string}
548
+ */
549
+ type: 'credit' | 'debit';
550
+ /**
551
+ * @description What caused this wallet movement
552
+ * @enum {string}
553
+ */
554
+ reason: 'wallet_funding' | 'purchase' | 'refund';
555
+ /** @description Always positive; direction expressed by `type` */
556
+ amount_cents: number;
557
+ /** @description Running wallet balance immediately after this event */
558
+ balance_after_cents: number;
559
+ /** @enum {string} */
560
+ status: 'completed' | 'pending' | 'failed' | 'cancelled';
561
+ /** @description ID of the source record (Purchase or FundingTransfer) */
562
+ reference_id: string;
563
+ /** @description Human-readable label suitable for display */
564
+ description: string;
565
+ /**
566
+ * Format: date-time
567
+ * @description created_at of the source record
568
+ */
569
+ occurred_at: string;
570
+ };
571
+ PurchaseCreateRequest: {
572
+ content_id?: string;
573
+ price_cents?: number;
574
+ };
575
+ PurchaseVerifyResponse: {
576
+ has_purchased: boolean;
577
+ purchase_details?: {
578
+ purchase_id?: string;
579
+ /** Format: date-time */
580
+ purchase_date?: string;
581
+ };
582
+ checkout_readiness?: {
583
+ is_authenticated?: boolean;
584
+ has_sufficient_funds?: boolean;
585
+ };
586
+ };
587
+ /** @description Update request for content. `content_body` applies to `markdown` content; `content_uri` and `external_identifier` apply to `external_ref` content. */
588
+ ContentUpdateRequest: {
589
+ /** @description Content title */
590
+ title?: string;
591
+ /**
592
+ * Format: byte
593
+ * @description Full article body in markdown, base64 encoded. For `markdown` content only.
594
+ */
595
+ content_body?: string;
596
+ /**
597
+ * @description URI of the resource. Required for `external_ref` content; optional for `markdown` content.
598
+ * @example https://vimeo.com/123456789
599
+ */
600
+ content_uri?: string;
601
+ /**
602
+ * @description Namespaced platform ID, e.g. `vimeo:123456789`. For `external_ref` content only.
603
+ * @example vimeo:123456789
604
+ */
605
+ external_identifier?: string | null;
606
+ /**
607
+ * Format: byte
608
+ * @description Content teaser, base64 encoded
609
+ */
610
+ teaser?: string;
611
+ /** @description Price in cents (must be greater than 0) */
612
+ price_cents?: number;
613
+ /** @enum {string} */
614
+ visibility?: 'public' | 'unlisted';
615
+ metadata?: {
616
+ [key: string]: unknown;
617
+ };
618
+ /** @description Assign or clear content authorship. Provide the `id` of a `StoreUser` from `GET /v1/merchant/{store_id}/users` to assign an author, or `null` to clear attribution. Only available to `owner` role and API key auth. Users with `is_author: true` (non-owner) cannot reassign their own content. */
619
+ store_user_id?: string | null;
620
+ };
621
+ SalesStatisticsItem: {
622
+ content_id: string;
623
+ title: string;
624
+ total_sales: number;
625
+ total_revenue_cents: number;
626
+ };
627
+ /**
628
+ * @description Seller-scoped buyer aggregate statistics for reporting.
629
+ *
630
+ * Prefer `buyer_ref` over any global buyer identifier.
631
+ */
632
+ BuyerStatisticsItem: {
633
+ /** @description Opaque, seller-scoped identifier for a buyer (not the global user id). */
634
+ buyer_ref: string;
635
+ /** @description Number of completed purchases by this buyer for this seller. */
636
+ purchases_count: number;
637
+ /** @description Total amount spent by this buyer for this seller, in cents. */
638
+ total_spent_cents: number;
639
+ /**
640
+ * Format: date-time
641
+ * @description Timestamp of the buyer's first completed purchase for this seller.
642
+ */
643
+ first_purchase_at: string;
644
+ /**
645
+ * Format: date-time
646
+ * @description Timestamp of the buyer's most recent completed purchase for this seller.
647
+ */
648
+ last_purchase_at: string;
649
+ /**
650
+ * @description Coarse segmentation label derived by the platform.
651
+ * @enum {string}
652
+ */
653
+ buyer_status: 'new' | 'repeat' | 'inactive';
654
+ };
655
+ AhoyEvent: {
656
+ /** @description Name of the event being tracked */
657
+ name?: string;
658
+ /** @description Additional properties for the event */
659
+ properties?: {
660
+ [key: string]: unknown;
661
+ };
662
+ /**
663
+ * Format: date-time
664
+ * @description When the event occurred
665
+ */
666
+ time?: string;
667
+ /**
668
+ * Format: uuid
669
+ * @description ID of the user associated with the event
670
+ */
671
+ user_id?: string;
672
+ /**
673
+ * Format: uuid
674
+ * @description ID of the visit associated with the event
675
+ */
676
+ visit_id?: string;
677
+ };
678
+ AhoyVisit: {
679
+ /** @description Unique token for this visit */
680
+ visit_token?: string;
681
+ /** @description Token identifying the visitor */
682
+ visitor_token?: string;
683
+ /**
684
+ * Format: uuid
685
+ * @description ID of the user associated with the visit
686
+ */
687
+ user_id?: string;
688
+ /** @description IP address of the visitor */
689
+ ip?: string;
690
+ /** @description User agent string */
691
+ user_agent?: string;
692
+ /** @description Referrer URL */
693
+ referrer?: string;
694
+ /** @description Domain of the referrer */
695
+ referring_domain?: string;
696
+ /** @description Landing page URL */
697
+ landing_page?: string;
698
+ /** @description Browser name */
699
+ browser?: string;
700
+ /** @description Operating system */
701
+ os?: string;
702
+ /** @description Type of device */
703
+ device_type?: string;
704
+ /** @description Country of the visitor */
705
+ country?: string;
706
+ /** @description Region of the visitor */
707
+ region?: string;
708
+ /** @description City of the visitor */
709
+ city?: string;
710
+ /**
711
+ * Format: float
712
+ * @description Latitude coordinate
713
+ */
714
+ latitude?: number;
715
+ /**
716
+ * Format: float
717
+ * @description Longitude coordinate
718
+ */
719
+ longitude?: number;
720
+ /** @description UTM source parameter */
721
+ utm_source?: string;
722
+ /** @description UTM medium parameter */
723
+ utm_medium?: string;
724
+ /** @description UTM term parameter */
725
+ utm_term?: string;
726
+ /** @description UTM content parameter */
727
+ utm_content?: string;
728
+ /** @description UTM campaign parameter */
729
+ utm_campaign?: string;
730
+ /** @description App version (for native apps) */
731
+ app_version?: string;
732
+ /** @description OS version (for native apps) */
733
+ os_version?: string;
734
+ /** @description Platform (for native apps) */
735
+ platform?: string;
736
+ /**
737
+ * Format: date-time
738
+ * @description When the visit started
739
+ */
740
+ started_at?: string;
741
+ };
742
+ AhoyEventRequest: {
743
+ /** @description Name of the event being tracked */
744
+ name: string;
745
+ /** @description Additional properties for the event */
746
+ properties?: {
747
+ [key: string]: unknown;
748
+ };
749
+ /**
750
+ * Format: date-time
751
+ * @description When the event occurred (defaults to current time)
752
+ */
753
+ time?: string;
754
+ /**
755
+ * Format: uuid
756
+ * @description ID of the user associated with the event
757
+ */
758
+ user_id?: string;
759
+ /**
760
+ * Format: uuid
761
+ * @description ID of the visit associated with the event
762
+ */
763
+ visit_id?: string;
764
+ };
765
+ AhoyVisitRequest: {
766
+ /** @description Unique token for this visit */
767
+ visit_token?: string;
768
+ /** @description Token identifying the visitor */
769
+ visitor_token?: string;
770
+ /**
771
+ * Format: uuid
772
+ * @description ID of the user associated with the visit
773
+ */
774
+ user_id?: string;
775
+ /** @description IP address of the visitor */
776
+ ip?: string;
777
+ /** @description User agent string */
778
+ user_agent?: string;
779
+ /** @description Referrer URL */
780
+ referrer?: string;
781
+ /** @description Domain of the referrer */
782
+ referring_domain?: string;
783
+ /** @description Landing page URL */
784
+ landing_page?: string;
785
+ /** @description Browser name */
786
+ browser?: string;
787
+ /** @description Operating system */
788
+ os?: string;
789
+ /** @description Type of device */
790
+ device_type?: string;
791
+ /** @description Country of the visitor */
792
+ country?: string;
793
+ /** @description Region of the visitor */
794
+ region?: string;
795
+ /** @description City of the visitor */
796
+ city?: string;
797
+ /**
798
+ * Format: float
799
+ * @description Latitude coordinate
800
+ */
801
+ latitude?: number;
802
+ /**
803
+ * Format: float
804
+ * @description Longitude coordinate
805
+ */
806
+ longitude?: number;
807
+ /** @description UTM source parameter */
808
+ utm_source?: string;
809
+ /** @description UTM medium parameter */
810
+ utm_medium?: string;
811
+ /** @description UTM term parameter */
812
+ utm_term?: string;
813
+ /** @description UTM content parameter */
814
+ utm_content?: string;
815
+ /** @description UTM campaign parameter */
816
+ utm_campaign?: string;
817
+ /** @description App version (for native apps) */
818
+ app_version?: string;
819
+ /** @description OS version (for native apps) */
820
+ os_version?: string;
821
+ /** @description Platform (for native apps) */
822
+ platform?: string;
823
+ /**
824
+ * Format: date-time
825
+ * @description When the visit started (defaults to current time)
826
+ */
827
+ started_at?: string;
828
+ };
829
+ /** @description Create request body for content. Required fields vary by `content_type`: `markdown` requires `content_body`; `external_ref` requires `content_uri`. Both types accept an optional `content_uri` link. */
830
+ Content: {
831
+ /**
832
+ * @description The type of content being created.
833
+ * @enum {string}
834
+ */
835
+ content_type: 'markdown' | 'external_ref';
836
+ /** @description Content title */
837
+ title: string;
838
+ /**
839
+ * Format: byte
840
+ * @description Full article body in markdown, base64 encoded. Required when `content_type` is `markdown`.
841
+ */
842
+ content_body?: string;
843
+ /**
844
+ * @description URI of the resource. Required when `content_type` is `external_ref`; optional for `markdown` content.
845
+ * @example https://vimeo.com/123456789
846
+ */
847
+ content_uri?: string;
848
+ /**
849
+ * @description Optional namespaced platform ID, e.g. `vimeo:123456789` or `youtube:dQw4w9WgXcQ`.
850
+ * @example vimeo:123456789
851
+ */
852
+ external_identifier?: string;
853
+ /**
854
+ * Format: byte
855
+ * @description (Optional) Article teaser, written in markdown and base64 encoded.
856
+ */
857
+ teaser?: string;
858
+ /** @description Price for the content in cents. */
859
+ price_cents: number;
860
+ /**
861
+ * @default public
862
+ * @enum {string}
863
+ */
864
+ visibility: 'public' | 'unlisted';
865
+ /** @description Flexible metadata for additional context */
866
+ metadata?: {
867
+ author?: string;
868
+ /** Format: date-time */
869
+ publication_date?: string;
870
+ reading_time?: string;
871
+ } & {
872
+ [key: string]: unknown;
873
+ };
874
+ };
875
+ /** @description Response shape for a single content item. The presence of `content_body` vs `content_uri` depends on `content_type`: `markdown` includes `content_body`; `external_ref` includes `content_uri` (the external URI) and optionally `external_identifier`. */
876
+ ContentResponse: {
877
+ id: string;
878
+ /**
879
+ * @description The type of content.
880
+ * @enum {string}
881
+ */
882
+ content_type: 'markdown' | 'external_ref';
883
+ /** @description Content title */
884
+ title: string;
885
+ /**
886
+ * Format: byte
887
+ * @description Full article body in markdown, base64 encoded. Present when `content_type` is `markdown`.
888
+ */
889
+ content_body?: string | null;
890
+ /**
891
+ * @description URI of the external resource. Present when `content_type` is `external_ref`.
892
+ * @example https://vimeo.com/123456789
893
+ */
894
+ content_uri?: string | null;
895
+ /**
896
+ * @description Namespaced platform ID, e.g. `vimeo:123456789`. Present on `external_ref` content.
897
+ * @example vimeo:123456789
898
+ */
899
+ external_identifier?: string | null;
900
+ /**
901
+ * Format: byte
902
+ * @description Article teaser, base64 encoded.
903
+ */
904
+ teaser: string;
905
+ /** @description Price for the content in cents. */
906
+ price_cents: number;
907
+ /**
908
+ * @default public
909
+ * @enum {string}
910
+ */
911
+ visibility: 'public' | 'unlisted' | 'private';
912
+ /** @description Flexible metadata for additional context */
913
+ metadata?: {
914
+ author?: string;
915
+ /** Format: date-time */
916
+ publication_date?: string;
917
+ reading_time?: string;
918
+ /** Format: string */
919
+ tags?: unknown[];
920
+ /** @description flexible data for managing paywall location */
921
+ paywall?: {
922
+ /** @description Character position of the paywall */
923
+ position?: number;
924
+ /**
925
+ * @description The mechanism for determining how positioning is calculated
926
+ * @enum {string}
927
+ */
928
+ positioning_type?: 'character' | 'paragraph';
929
+ /** @description Hash anchor of nearby text */
930
+ anchor?: string;
931
+ };
932
+ } & {
933
+ [key: string]: unknown;
934
+ };
935
+ };
936
+ /** @description Pagination metadata returned on all paginated list endpoints. */
937
+ PaginationMeta: {
938
+ /**
939
+ * @description Total number of records matching the query.
940
+ * @example 84
941
+ */
942
+ total: number;
943
+ /**
944
+ * @description Maximum number of records returned per page.
945
+ * @example 25
946
+ */
947
+ per_page: number;
948
+ /**
949
+ * @description The current page number (1-based).
950
+ * @example 2
951
+ */
952
+ current_page: number;
953
+ /**
954
+ * @description Total number of pages.
955
+ * @example 4
956
+ */
957
+ total_pages: number;
958
+ /**
959
+ * @description Next page number, or null if on the last page.
960
+ * @example 3
961
+ */
962
+ next_page?: number | null;
963
+ /**
964
+ * @description Previous page number, or null if on the first page.
965
+ * @example 1
966
+ */
967
+ prev_page?: number | null;
968
+ };
969
+ /** @description Paginated list of content items. */
970
+ PaginatedContentList: {
971
+ data: components['schemas']['ContentListItem'][];
972
+ pagination: components['schemas']['PaginationMeta'];
973
+ };
974
+ /** @description Paginated list of content sales statistics. */
975
+ PaginatedSalesList: {
976
+ data: components['schemas']['SalesStatisticsItem'][];
977
+ pagination: components['schemas']['PaginationMeta'];
978
+ };
979
+ /** @description Paginated list of anonymised buyer statistics. */
980
+ PaginatedBuyersList: {
981
+ data: components['schemas']['BuyerStatisticsItem'][];
982
+ pagination: components['schemas']['PaginationMeta'];
983
+ };
984
+ /** @description Paginated list of store members. */
985
+ PaginatedUsersList: {
986
+ data: components['schemas']['MerchantUser'][];
987
+ pagination: components['schemas']['PaginationMeta'];
988
+ };
989
+ /** @description Lightweight content representation returned by list and search endpoints. Omits body fields to keep list payloads small. Use the detail endpoint (`GET /v1/merchant/:store_id/content/:id`) to retrieve the full body or URI. */
990
+ ContentListItem: {
991
+ id: string;
992
+ /** @enum {string} */
993
+ content_type: 'markdown' | 'external_ref';
994
+ title: string;
995
+ price_cents: number;
996
+ /**
997
+ * Format: byte
998
+ * @description Article teaser, base64 encoded. Null when not set.
999
+ */
1000
+ teaser: string | null;
1001
+ /** @enum {string} */
1002
+ visibility: 'public' | 'unlisted' | 'private';
1003
+ /** Format: date-time */
1004
+ created_at: string;
1005
+ /** @description Namespaced platform ID for `external_ref` content. Null for other types. */
1006
+ external_identifier?: string | null;
1007
+ };
1008
+ /**
1009
+ * @description Full content detail plus real-time access and wallet context for a specific user. Returned by the buyer-facing `GET /v1/content/:id/with-access` endpoint.
1010
+ *
1011
+ * **URI gating for `external_ref` content:** `content_uri` (the external URI) is only present in the response when `access_info.has_purchased` is `true`. For all other states (unauthenticated, insufficient funds, not yet purchased) it is omitted, ensuring buyers cannot access the Vimeo link, PDF URI, or other external resource without completing a purchase.
1012
+ */
1013
+ ContentWithAccessResponse: components['schemas']['ContentResponse'] & {
1014
+ access_info: components['schemas']['ContentAccessInfo'];
1015
+ };
1016
+ User: {
1017
+ id?: string;
1018
+ name?: string;
1019
+ email?: string;
1020
+ /** @enum {string} */
1021
+ role?: 'buyer' | 'seller';
1022
+ };
1023
+ /** @enum {string} */
1024
+ PurchaseStatus: 'completed' | 'refunded' | 'pending' | 'reverted' | 'failed';
1025
+ PurchaseResponse: {
1026
+ id: string;
1027
+ content_id: string;
1028
+ content: {
1029
+ id: string;
1030
+ content_type: string;
1031
+ title: string;
1032
+ };
1033
+ buyer_id: string;
1034
+ buyer: {
1035
+ id: string;
1036
+ name: string;
1037
+ };
1038
+ seller_id: string;
1039
+ seller: {
1040
+ id: string;
1041
+ name: string;
1042
+ };
1043
+ amount_cents: number;
1044
+ /** Format: date-time */
1045
+ timestamp: string;
1046
+ status: components['schemas']['PurchaseStatus'];
1047
+ };
1048
+ MerchantSaleResponse: {
1049
+ id: string;
1050
+ content_id: string;
1051
+ content: {
1052
+ id: string;
1053
+ content_type: string;
1054
+ title: string;
1055
+ };
1056
+ buyer_id: string;
1057
+ buyer: {
1058
+ id: string;
1059
+ name: string;
1060
+ };
1061
+ seller_id: string;
1062
+ seller: {
1063
+ id: string;
1064
+ name: string;
1065
+ };
1066
+ amount_cents: number;
1067
+ /** @description Platform fee split. Values are 0 (not null) on non-completed purchases. */
1068
+ fees: {
1069
+ platform_fee_cents: number;
1070
+ store_net_cents: number;
1071
+ /** @description 0 for content without an author */
1072
+ author_net_cents: number;
1073
+ };
1074
+ status: components['schemas']['PurchaseStatus'];
1075
+ /** Format: date-time */
1076
+ timestamp: string;
1077
+ };
1078
+ MonthlyData: {
1079
+ [key: string]: {
1080
+ [key: string]: {
1081
+ cents?: number;
1082
+ currency_iso?: string;
1083
+ };
1084
+ };
1085
+ };
1086
+ InviteInfoResponse: {
1087
+ invited_email: string;
1088
+ store_name: string;
1089
+ /** @enum {string|null} */
1090
+ role: 'owner' | null;
1091
+ /** Format: date-time */
1092
+ expires_at: string;
1093
+ };
1094
+ CheckoutStateResponse: {
1095
+ content_id: string;
1096
+ content_title: string;
1097
+ price_cents: number;
1098
+ checkout_state: {
1099
+ is_authenticated: boolean;
1100
+ has_sufficient_funds?: boolean | null;
1101
+ has_purchased: boolean;
1102
+ /** @enum {string} */
1103
+ next_required_action: 'authenticate' | 'fund_wallet' | 'purchase' | 'view_content';
1104
+ };
1105
+ };
1106
+ WalletPaymentStatusResponse: {
1107
+ /** @enum {string} */
1108
+ status: 'pending' | 'completed' | 'failed';
1109
+ /** Format: date-time */
1110
+ updated_at: string;
1111
+ balance_cents: number;
1112
+ };
1113
+ SalesSummaryResponse: {
1114
+ /** @description Amount in cents */
1115
+ total_revenue_cents: number;
1116
+ /** @description Total number of sales */
1117
+ total_sales: number;
1118
+ /** @description Monthly revenue data grouped by year and month. First level key is year (string), second level key is month number (string, 1-12) */
1119
+ monthly_revenue_cents: {
1120
+ [key: string]: {
1121
+ [key: string]: number;
1122
+ };
1123
+ };
1124
+ /** @description Monthly sales count data grouped by year and month. First level key is year (string), second level key is month number (string, 1-12) */
1125
+ monthly_sales: {
1126
+ [key: string]: {
1127
+ [key: string]: number;
1128
+ };
1129
+ };
1130
+ };
1131
+ };
1132
+ responses: never;
1133
+ parameters: never;
1134
+ requestBodies: never;
1135
+ headers: never;
1136
+ pathItems: never;
1137
+ }
1138
+
1139
+ /** Checkout state for a specific piece of content and user. */
1140
+ export declare type ContentAccessInfo = components['schemas']['ContentAccessInfo'];
1141
+
1142
+ /** A piece of content with buyer access information. */
1143
+ export declare type ContentWithAccessResponse = components['schemas']['ContentWithAccessResponse'];
1144
+
1145
+ /**
1146
+ * Thrown when the authenticated user does not have permission
1147
+ * to perform the requested operation.
1148
+ */
1149
+ export declare class ForbiddenError extends LedewireError {
1150
+ constructor(message: string, code?: number);
1151
+ }
1152
+
1153
+ /**
1154
+ * Core HTTP client used by all SDK packages.
1155
+ *
1156
+ * Features:
1157
+ * - Injects `Authorization: Bearer <token>` headers automatically
1158
+ * - Maps HTTP error responses to typed `LedewireError` subclasses
1159
+ * - On receiving a 401, calls `onUnauthorized` once and retries the request
1160
+ *
1161
+ * This is an internal class - consumers should use the
1162
+ * package-level client factories (`init` / `createClient`) instead.
1163
+ */
1164
+ declare class HttpClient {
1165
+ private readonly baseUrl;
1166
+ private readonly getAccessToken;
1167
+ private readonly onUnauthorized;
1168
+ constructor(config?: HttpClientConfig);
1169
+ /**
1170
+ * GET request with optional query parameters.
1171
+ * @param path - API path (e.g. `/v1/wallet/balance`)
1172
+ * @param params - Query string parameters
1173
+ */
1174
+ get<T>(path: string, params?: Record<string, string>): Promise<T>;
1175
+ /**
1176
+ * POST request.
1177
+ * @param path - API path
1178
+ * @param body - Request body (JSON-serialized)
1179
+ */
1180
+ post<T>(path: string, body?: unknown): Promise<T>;
1181
+ /**
1182
+ * PUT request.
1183
+ * @param path - API path
1184
+ * @param body - Request body (JSON-serialized)
1185
+ */
1186
+ put<T>(path: string, body?: unknown): Promise<T>;
1187
+ /**
1188
+ * PATCH request.
1189
+ * @param path - API path
1190
+ * @param body - Partial update body (JSON-serialized)
1191
+ */
1192
+ patch<T>(path: string, body?: unknown): Promise<T>;
1193
+ /**
1194
+ * DELETE request.
1195
+ * @param path - API path
1196
+ */
1197
+ delete<T = void>(path: string): Promise<T>;
1198
+ private buildUrl;
1199
+ private request;
1200
+ private throwApiError;
1201
+ }
1202
+
1203
+ /**
1204
+ * Configuration options for `HttpClient`.
1205
+ */
1206
+ declare interface HttpClientConfig {
1207
+ /** API base URL. Defaults to the production API. */
1208
+ baseUrl?: string;
1209
+ /**
1210
+ * Returns the current access token (or null) before each request.
1211
+ * If null, requests are sent without an Authorization header.
1212
+ */
1213
+ getAccessToken?: () => string | null | Promise<string | null>;
1214
+ /**
1215
+ * Called when a 401 is received on the first attempt.
1216
+ * Should refresh and return the new access token, or null to propagate
1217
+ * an `AuthError` to the caller.
1218
+ */
1219
+ onUnauthorized?: () => string | null | Promise<string | null>;
1220
+ }
1221
+
1222
+ /**
1223
+ * Initialises a LedeWire browser client.
1224
+ * This is the primary entry point for the browser SDK.
1225
+ *
1226
+ * @example CDN usage:
1227
+ * ```html
1228
+ * <script src="https://cdn.jsdelivr.net/npm/@ledewire/browser@1/dist/ledewire.min.js"></script>
1229
+ * <script>
1230
+ * const lw = Ledewire.init({ apiKey: 'your_api_key' })
1231
+ * const state = await lw.checkout.state('content-id')
1232
+ * </script>
1233
+ * ```
1234
+ *
1235
+ * @example npm usage:
1236
+ * ```ts
1237
+ * import { init } from '@ledewire/browser'
1238
+ * const lw = init({ apiKey: 'your_api_key' })
1239
+ * ```
1240
+ */
1241
+ export declare function init(config: BrowserClientConfig): BrowserClient;
1242
+
1243
+ /**
1244
+ * Base error class for all LedeWire SDK errors.
1245
+ * All errors thrown by the SDK are instances of this class,
1246
+ * making it safe to use `err instanceof LedewireError` as a type guard.
1247
+ *
1248
+ * @example
1249
+ * ```ts
1250
+ * try {
1251
+ * await client.purchases.create({ contentId: '...' })
1252
+ * } catch (err) {
1253
+ * if (err instanceof LedewireError) {
1254
+ * console.error(err.statusCode, err.message)
1255
+ * }
1256
+ * }
1257
+ * ```
1258
+ */
1259
+ export declare class LedewireError extends Error {
1260
+ /** HTTP status code returned by the API (e.g. 400, 401, 404, 422). */
1261
+ readonly statusCode: number;
1262
+ /** Machine-readable error code from the API error body, if present. */
1263
+ readonly code: number | undefined;
1264
+ constructor(message: string, statusCode: number, code?: number);
1265
+ }
1266
+
1267
+ /**
1268
+ * A {@link TokenStorage} adapter that persists tokens in `localStorage`.
1269
+ *
1270
+ * Tokens survive page reloads and browser restarts, which is convenient
1271
+ * for sites where users expect persistent sessions.
1272
+ *
1273
+ * **Security note:** `localStorage` is accessible to any JavaScript on the
1274
+ * same origin. Only use this adapter on sites you fully control and trust.
1275
+ * The default in-memory storage is safer for high-security use cases.
1276
+ *
1277
+ * @param key - The `localStorage` key used to store tokens.
1278
+ * Defaults to `'lw:tokens'`. Override this if you have multiple
1279
+ * LedeWire integrations on the same origin.
1280
+ *
1281
+ * @example
1282
+ * ```ts
1283
+ * import { init, localStorageAdapter } from '@ledewire/browser'
1284
+ *
1285
+ * const lw = init({
1286
+ * apiKey: 'your_api_key',
1287
+ * storage: localStorageAdapter(),
1288
+ * })
1289
+ * ```
1290
+ */
1291
+ export declare function localStorageAdapter(key?: string): TokenStorage;
1292
+
1293
+ /**
1294
+ * In-memory token storage (default for both packages).
1295
+ * Tokens are cleared when the page unloads or the process exits.
1296
+ * This is the most secure default for browser environments.
1297
+ */
1298
+ export declare class MemoryTokenStorage implements TokenStorage {
1299
+ private tokens;
1300
+ getTokens(): StoredTokens | null;
1301
+ setTokens(tokens: StoredTokens): void;
1302
+ clearTokens(): void;
1303
+ }
1304
+
1305
+ /** The next action a buyer must take in the checkout flow. */
1306
+ export declare type NextRequiredAction = ContentAccessInfo['next_required_action'];
1307
+
1308
+ /**
1309
+ * Thrown when the requested resource does not exist.
1310
+ */
1311
+ export declare class NotFoundError extends LedewireError {
1312
+ constructor(message: string, code?: number);
1313
+ }
1314
+
1315
+ /**
1316
+ * Converts an `expires_at` ISO 8601 string from an API auth response
1317
+ * into a Unix timestamp (milliseconds) for use in `StoredTokens.expiresAt`.
1318
+ *
1319
+ * @param expiresAt - ISO 8601 datetime string, e.g. `"2026-01-01T12:00:00Z"`
1320
+ * @returns Unix timestamp in milliseconds
1321
+ */
1322
+ export declare function parseExpiresAt(expiresAt: string): number;
1323
+
1324
+ /**
1325
+ * Platform-level public configuration returned by `GET /v1/config/public`.
1326
+ * No authentication required. Use this to get the Google OAuth client ID
1327
+ * before the user has signed in.
1328
+ */
1329
+ export declare type PublicConfigResponse = components['schemas']['PublicConfigResponse'];
1330
+
1331
+ /** Request body for creating a purchase. */
1332
+ export declare type PurchaseCreateRequest = components['schemas']['PurchaseCreateRequest'];
1333
+
1334
+ /**
1335
+ * Thrown when the purchase cannot be completed due to a validation
1336
+ * failure, such as a price mismatch or a duplicate purchase.
1337
+ */
1338
+ export declare class PurchaseError extends LedewireError {
1339
+ constructor(message: string, statusCode: number, code?: number);
1340
+ }
1341
+
1342
+ /** A purchase record. */
1343
+ export declare type PurchaseResponse = components['schemas']['PurchaseResponse'];
1344
+
1345
+ /** Internal representation of stored authentication tokens. */
1346
+ export declare interface StoredTokens {
1347
+ accessToken: string;
1348
+ refreshToken: string;
1349
+ /** Unix timestamp (ms) when the access token expires. */
1350
+ expiresAt: number;
1351
+ }
1352
+
1353
+ /**
1354
+ * Manages the JWT token lifecycle transparently.
1355
+ *
1356
+ * - Proactively refreshes the access token when it expires within 60 seconds
1357
+ * - Handles reactive refresh on 401 responses from the HTTP client
1358
+ * - Deduplicates concurrent refresh calls (only one in-flight refresh at a time)
1359
+ * - Fires `onAuthExpired` when refresh fails so the UI can prompt re-login
1360
+ *
1361
+ * This is an internal class - use the package-level client factories instead.
1362
+ */
1363
+ declare class TokenManager {
1364
+ private readonly storage;
1365
+ private readonly refreshFn;
1366
+ private readonly onTokenRefreshed;
1367
+ private readonly onAuthExpired;
1368
+ private refreshPromise;
1369
+ constructor(options: TokenManagerOptions);
1370
+ /**
1371
+ * Returns a valid access token, refreshing proactively if needed.
1372
+ * Returns `null` if no tokens are stored (user not authenticated).
1373
+ */
1374
+ getAccessToken(): Promise<string | null>;
1375
+ /**
1376
+ * Called by `HttpClient` when a 401 is received.
1377
+ * Attempts one refresh; returns the new access token or null.
1378
+ */
1379
+ handleUnauthorized(): Promise<string | null>;
1380
+ /** Store new tokens after a successful login or signup. */
1381
+ setTokens(tokens: StoredTokens): Promise<void>;
1382
+ /** Clear all stored tokens (call on logout). */
1383
+ clearTokens(): Promise<void>;
1384
+ private performRefresh;
1385
+ }
1386
+
1387
+ /**
1388
+ * Options for constructing a `TokenManager`.
1389
+ */
1390
+ declare interface TokenManagerOptions {
1391
+ storage: TokenStorage;
1392
+ /**
1393
+ * Exchanges a refresh token for a new token pair.
1394
+ * Implemented by each package's client factory using the
1395
+ * `/v1/auth/token/refresh` endpoint.
1396
+ */
1397
+ refreshFn: (refreshToken: string) => Promise<StoredTokens>;
1398
+ /**
1399
+ * Called after a successful token refresh.
1400
+ * Use in server environments to persist the new tokens to a database or cache.
1401
+ *
1402
+ * @example
1403
+ * ```ts
1404
+ * onTokenRefreshed: async (tokens) => {
1405
+ * await redis.set('session:tokens', JSON.stringify(tokens))
1406
+ * }
1407
+ * ```
1408
+ */
1409
+ onTokenRefreshed?: (tokens: StoredTokens) => void | Promise<void>;
1410
+ /**
1411
+ * Called when a refresh attempt fails and the user must re-authenticate.
1412
+ * Typically used to redirect to login or emit a UI event.
1413
+ *
1414
+ * @example
1415
+ * ```ts
1416
+ * onAuthExpired: () => { window.location.href = '/login' }
1417
+ * ```
1418
+ */
1419
+ onAuthExpired?: () => void | Promise<void>;
1420
+ }
1421
+
1422
+ /**
1423
+ * Interface for pluggable token storage adapters.
1424
+ * Implement this to persist tokens across page loads or in a server-side store.
1425
+ *
1426
+ * @example
1427
+ * ```ts
1428
+ * // Built-in localStorage adapter (browser only)
1429
+ * import { localStorageAdapter } from '@ledewire/browser'
1430
+ * const client = createBrowserClient({ apiKey, storage: localStorageAdapter() })
1431
+ * ```
1432
+ */
1433
+ export declare interface TokenStorage {
1434
+ /** Retrieve stored token data, or null if none. */
1435
+ getTokens(): StoredTokens | null | Promise<StoredTokens | null>;
1436
+ /** Persist token data. */
1437
+ setTokens(tokens: StoredTokens): void | Promise<void>;
1438
+ /** Clear all stored token data (called on logout). */
1439
+ clearTokens(): void | Promise<void>;
1440
+ }
1441
+
1442
+ /** Current wallet balance for the authenticated buyer. */
1443
+ export declare type WalletBalanceResponse = components['schemas']['WalletBalanceResponse'];
1444
+
1445
+ /** Request body for creating a wallet payment session. */
1446
+ export declare type WalletPaymentSessionRequest = components['schemas']['WalletPaymentSessionRequest'];
1447
+
1448
+ /** Response from creating a wallet payment session. */
1449
+ export declare type WalletPaymentSessionResponse = components['schemas']['WalletPaymentSessionResponse'];
1450
+
1451
+ /** Status of a wallet payment session. */
1452
+ export declare type WalletPaymentStatusResponse = components['schemas']['WalletPaymentStatusResponse'];
1453
+
1454
+ /** A single wallet transaction entry. */
1455
+ export declare type WalletTransactionItem = components['schemas']['WalletTransactionItem'];
1456
+
1457
+ export { }