@omnibase/core-js 0.5.0 → 0.5.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.
@@ -1,1987 +1,3 @@
1
- import { PermissionsClient } from '../permissions/index.js';
1
+ export { A as AcceptTenantInviteRequest, a as AcceptTenantInviteResponse, g as CreateTenantRequest, e as CreateTenantResponse, c as CreateTenantUserInviteRequest, C as CreateTenantUserInviteResponse, D as DeleteTenantResponse, S as SwitchActiveTenantResponse, f as Tenant, T as TenantHandler, b as TenantInvite, d as TenantInviteManager, h as TenantManger } from '../payments/index.js';
2
+ import '../permissions/index.js';
2
3
  import '@ory/client';
3
-
4
- /**
5
- * Base API Response structure for all operations
6
- *
7
- * This generic type defines the standard response format returned by all
8
- * API endpoints. It provides a consistent structure for
9
- * handling both successful responses and error conditions across the SDK.
10
- *
11
- * @template T - The type of the response data payload
12
- *
13
- * @example
14
- * Successful response:
15
- * ```typescript
16
- * const response: ApiResponse<{ tenant: Tenant }> = {
17
- * data: { tenant: { id: '123', name: 'My Company' } },
18
- * status: 200
19
- * };
20
- * ```
21
- *
22
- * @example
23
- * Error response:
24
- * ```typescript
25
- * const response: ApiResponse<never> = {
26
- * status: 400,
27
- * error: 'Invalid tenant name provided'
28
- * };
29
- * ```
30
- *
31
- * @since 1.0.0
32
- * @public
33
- */
34
- type ApiResponse<T> = {
35
- /**
36
- * Response data payload (present only on successful operations)
37
- * Contains the actual data returned by the API endpoint
38
- */
39
- data?: T;
40
- /**
41
- * HTTP status code indicating the result of the operation
42
- * @example 200 for success, 400 for client errors, 500 for server errors
43
- */
44
- status: number;
45
- /**
46
- * Error message (present only when operation fails)
47
- * Provides human-readable description of what went wrong
48
- */
49
- error?: string;
50
- };
51
-
52
- /**
53
- * Request data for accepting a tenant invitation
54
- *
55
- * Contains the secure token that was provided in the invitation.
56
- * This token is validated server-side to ensure the invitation
57
- * is legitimate, not expired, and hasn't been used before.
58
- *
59
- * @example
60
- * ```typescript
61
- * const acceptData: AcceptTenantInviteRequest = {
62
- * token: 'inv_secure_token_abc123xyz'
63
- * };
64
- * ```
65
- *
66
- * @since 1.0.0
67
- * @public
68
- * @group User Management
69
- */
70
- type AcceptTenantInviteRequest = {
71
- /** Secure invitation token from the email invitation */
72
- token: string;
73
- };
74
- /**
75
- * Response structure for accepting a tenant invitation
76
- *
77
- * Contains the ID of the tenant that the user has successfully joined
78
- * along with a confirmation message. After accepting an invitation,
79
- * the user becomes a member of the tenant with the role specified
80
- * in the original invitation.
81
- *
82
- * @example
83
- * ```typescript
84
- * const response: AcceptTenantInviteResponse = {
85
- * data: {
86
- * tenant_id: 'tenant_abc123',
87
- * message: 'Successfully joined tenant'
88
- * },
89
- * status: 200
90
- * };
91
- * ```
92
- *
93
- * @since 1.0.0
94
- * @public
95
- * @group User Management
96
- */
97
- type AcceptTenantInviteResponse = ApiResponse<{
98
- /** ID of the tenant the user has joined */
99
- tenant_id: string;
100
- /** Success message confirming the invitation acceptance */
101
- message: string;
102
- /** JWT token for postgrest RLS */
103
- token: string;
104
- }>;
105
- /**
106
- * Response structure for tenant user invite creation
107
- *
108
- * Contains the newly created invite information including the secure token
109
- * that will be sent to the invitee. The invite has an expiration time and
110
- * can only be used once to join the specified tenant.
111
- *
112
- * @example
113
- * ```typescript
114
- * const response: CreateTenantUserInviteResponse = {
115
- * data: {
116
- * invite: {
117
- * id: 'invite_123',
118
- * tenant_id: 'tenant_abc',
119
- * email: 'colleague@company.com',
120
- * role: 'member',
121
- * token: 'inv_secure_token_xyz',
122
- * expires_at: '2024-02-15T10:30:00Z'
123
- * },
124
- * message: 'Invite created successfully'
125
- * },
126
- * status: 201
127
- * };
128
- * ```
129
- *
130
- * @since 1.0.0
131
- * @public
132
- * @group User Management
133
- */
134
- type CreateTenantUserInviteResponse = ApiResponse<{
135
- /** The newly created tenant invite */
136
- invite: TenantInvite;
137
- /** Success message confirming invite creation */
138
- message: string;
139
- }>;
140
- /**
141
- * Tenant invitation entity structure
142
- *
143
- * Represents a pending invitation for a user to join a specific tenant
144
- * with a defined role. The invite contains a secure token that expires
145
- * after a certain time period and can only be used once.
146
- *
147
- * @example
148
- * ```typescript
149
- * const invite: TenantInvite = {
150
- * id: 'invite_abc123',
151
- * tenant_id: 'tenant_xyz789',
152
- * email: 'newuser@company.com',
153
- * role: 'member',
154
- * token: 'inv_secure_abc123xyz',
155
- * inviter_id: 'user_owner123',
156
- * expires_at: '2024-02-01T12:00:00Z',
157
- * created_at: '2024-01-25T12:00:00Z',
158
- * used_at: undefined // null until invite is accepted
159
- * };
160
- * ```
161
- *
162
- * @since 1.0.0
163
- * @public
164
- * @group User Management
165
- */
166
- type TenantInvite = {
167
- /** Unique identifier for the invitation */
168
- id: string;
169
- /** ID of the tenant the user is being invited to */
170
- tenant_id: string;
171
- /** Email address of the invited user */
172
- email: string;
173
- /** Role the user will have in the tenant (e.g., 'owner', 'admin', 'member') */
174
- role: string;
175
- /** Secure token used to accept the invitation */
176
- token: string;
177
- /** ID of the user who created this invitation */
178
- inviter_id: string;
179
- /** ISO 8601 timestamp when the invitation expires */
180
- expires_at: string;
181
- /** ISO 8601 timestamp when the invitation was created */
182
- created_at: string;
183
- /** ISO 8601 timestamp when the invitation was accepted (null if unused) */
184
- used_at?: string;
185
- };
186
- /**
187
- * Required data for creating a tenant user invitation
188
- *
189
- * Specifies the email address of the user to invite and their intended
190
- * role within the tenant. The role determines what permissions the user
191
- * will have once they accept the invitation.
192
- *
193
- * @example
194
- * ```typescript
195
- * const inviteData: CreateTenantUserInviteRequest = {
196
- * email: 'developer@company.com',
197
- * role: 'admin'
198
- * };
199
- * ```
200
- *
201
- * @since 1.0.0
202
- * @public
203
- * @group User Management
204
- */
205
- type CreateTenantUserInviteRequest = {
206
- /** Email address of the user to invite */
207
- email: string;
208
- /** Role the invited user will have in the tenant */
209
- role: string;
210
- };
211
- /**
212
- * Tenant invitation management handler
213
- *
214
- * This class handles all tenant invitation operations including creating
215
- * invitations for new users and processing invitation acceptances. It provides
216
- * a secure, email-based invitation workflow with role-based access control
217
- * and token-based security.
218
- *
219
- * The manager handles:
220
- * - Creating secure invitations with time-limited tokens
221
- * - Processing invitation acceptances with validation
222
- * - Email workflow integration (server-side)
223
- * - Role assignment and permission setup
224
- * - Security validation and anti-abuse measures
225
- *
226
- * All invitation operations respect tenant permissions and ensure that only
227
- * authorized users can invite others to their tenants.
228
- *
229
- * @example
230
- * ```typescript
231
- * const inviteManager = new TenantInviteManager(omnibaseClient);
232
- *
233
- * // Create an invitation
234
- * const invite = await inviteManager.create('tenant_123', {
235
- * email: 'colleague@company.com',
236
- * role: 'member'
237
- * });
238
- *
239
- * // Accept an invitation (from the invited user's session)
240
- * const result = await inviteManager.accept('invite_token_xyz');
241
- * console.log(`Joined tenant: ${result.data.tenant_id}`);
242
- * ```
243
- *
244
- * @since 1.0.0
245
- * @public
246
- * @group Tenant Invitations
247
- */
248
- declare class TenantInviteManager {
249
- private omnibaseClient;
250
- /**
251
- * Creates a new TenantInviteManager instance
252
- *
253
- * Initializes the manager with the provided Omnibase client for making
254
- * authenticated API requests to tenant invitation endpoints.
255
- *
256
- * @param omnibaseClient - Configured Omnibase client instance
257
- *
258
- * @group Tenant Invitations
259
- */
260
- constructor(omnibaseClient: OmnibaseClient);
261
- /**
262
- * Accepts a tenant invitation using a secure token
263
- *
264
- * Processes a tenant invitation by validating the provided token and
265
- * adding the authenticated user to the specified tenant. The invitation
266
- * token is consumed during this process and cannot be used again.
267
- *
268
- * The function performs several validations:
269
- * - Verifies the token exists and is valid
270
- * - Checks that the invitation hasn't expired
271
- * - Ensures the invitation hasn't already been used
272
- * - Confirms the user is authenticated via session cookies
273
- *
274
- * Upon successful acceptance, the user is granted access to the tenant
275
- * with the role specified in the original invitation. The invitation
276
- * record is marked as used and cannot be accepted again.
277
- *
278
- * @param token - The secure invitation token from the email invitation
279
- *
280
- * @returns Promise resolving to the tenant ID and success confirmation
281
- *
282
- * @throws {Error} When the token parameter is missing or empty
283
- * @throws {Error} When the invitation token is invalid or expired
284
- * @throws {Error} When the invitation has already been accepted
285
- * @throws {Error} When the user is not authenticated
286
- * @throws {Error} When the API request fails due to network issues
287
- * @throws {Error} When the server returns an error response (4xx, 5xx status codes)
288
- *
289
- * @example
290
- * Basic invitation acceptance:
291
- * ```typescript
292
- * const result = await acceptTenantInvite('inv_secure_token_abc123');
293
- *
294
- * console.log(`Successfully joined tenant: ${result.data.tenant_id}`);
295
- * // User can now access tenant resources
296
- * await switchActiveTenant(result.data.tenant_id);
297
- * ```
298
- *
299
- * @example
300
- * Handling the invitation flow:
301
- * ```typescript
302
- * // Typically called from an invitation link like:
303
- * // https://app.com/accept-invite?token=inv_secure_token_abc123
304
- *
305
- * const urlParams = new URLSearchParams(window.location.search);
306
- * const inviteToken = urlParams.get('token');
307
- *
308
- * if (inviteToken) {
309
- * try {
310
- * const result = await acceptTenantInvite(inviteToken);
311
- *
312
- * // Success - redirect to tenant dashboard
313
- * window.location.href = `/dashboard?tenant=${result.data.tenant_id}`;
314
- * } catch (error) {
315
- * console.error('Failed to accept invitation:', error.message);
316
- * // Show error to user
317
- * }
318
- * }
319
- * ```
320
- *
321
- *
322
- * @since 1.0.0
323
- * @public
324
- * @group User Management
325
- */
326
- accept(token: string): Promise<AcceptTenantInviteResponse>;
327
- /**
328
- * Creates a new user invitation for a specific tenant
329
- *
330
- * Generates a secure invitation that allows a user to join the specified
331
- * tenant with the defined role. The invitation is sent to the provided
332
- * email address and includes a time-limited token for security.
333
- *
334
- * The function creates the invitation record in the database and can
335
- * trigger email notifications (depending on server configuration).
336
- * The invitation expires after a predefined time period and can only
337
- * be used once.
338
- *
339
- * Only existing tenant members with appropriate permissions can create
340
- * invitations. The inviter's authentication is validated via HTTP-only
341
- * cookies sent with the request.
342
- *
343
- * @param tenantId - Unique identifier of the tenant to invite the user to
344
- * @param inviteData - Configuration object for the invitation
345
- * @param inviteData.email - Email address of the user to invite
346
- * @param inviteData.role - Role the user will have after joining (e.g., 'member', 'admin')
347
- *
348
- * @returns Promise resolving to the created invitation with secure token
349
- *
350
- * @throws {Error} When tenantId parameter is missing or empty
351
- * @throws {Error} When required fields (email, role) are missing or empty
352
- * @throws {Error} When the API request fails due to network issues
353
- * @throws {Error} When the server returns an error response (4xx, 5xx status codes)
354
- *
355
- * @example
356
- * Basic invitation creation:
357
- * ```typescript
358
- * const invite = await createTenantUserInvite('tenant_123', {
359
- * email: 'colleague@company.com',
360
- * role: 'member'
361
- * });
362
- *
363
- * console.log(`Invite sent to: ${invite.data.invite.email}`);
364
- * // The invite token can be used to generate invitation links
365
- * const inviteLink = `https://app.com/accept-invite?token=${invite.data.invite.token}`;
366
- * ```
367
- *
368
- * @example
369
- * Creating admin invitation:
370
- * ```typescript
371
- * const adminInvite = await createTenantUserInvite('tenant_456', {
372
- * email: 'admin@company.com',
373
- * role: 'admin'
374
- * });
375
- *
376
- * // Admin users get elevated permissions
377
- * console.log(`Admin invite created with ID: ${adminInvite.data.invite.id}`);
378
- * ```
379
- *
380
- *
381
- * @since 1.0.0
382
- * @public
383
- * @group User Management
384
- */
385
- create(tenantId: string, inviteData: CreateTenantUserInviteRequest): Promise<CreateTenantUserInviteResponse>;
386
- }
387
-
388
- /**
389
- * Response structure for switching the active tenant
390
- *
391
- * Contains a new JWT token that includes the updated tenant context
392
- * and a confirmation message. The new token should replace the previous
393
- * token for all subsequent API calls to ensure requests are made within
394
- * the context of the newly active tenant.
395
- *
396
- * The token includes updated tenant-specific claims and permissions,
397
- * ensuring that row-level security policies are enforced correctly
398
- * for the new active tenant context.
399
- *
400
- * @example
401
- * ```typescript
402
- * const response: SwitchActiveTenantResponse = {
403
- * data: {
404
- * token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
405
- * message: 'Active tenant switched successfully'
406
- * },
407
- * status: 200
408
- * };
409
- * ```
410
- *
411
- * @since 1.0.0
412
- * @public
413
- * @group Tenant Management
414
- */
415
- type SwitchActiveTenantResponse = ApiResponse<{
416
- /** New JWT token with updated tenant context */
417
- token: string;
418
- /** Success message confirming the tenant switch */
419
- message: string;
420
- }>;
421
- /**
422
- * Response structure for deleting a tenant
423
- *
424
- * Contains a confirmation message indicating successful tenant deletion.
425
- * This response is only returned after the tenant and all associated data
426
- * have been permanently removed from the system.
427
- *
428
- * @example
429
- * ```typescript
430
- * const response: DeleteTenantResponse = {
431
- * data: {
432
- * message: 'Tenant deleted successfully'
433
- * },
434
- * status: 200
435
- * };
436
- * ```
437
- *
438
- * @since 1.0.0
439
- * @public
440
- * @group Tenant Management
441
- */
442
- type DeleteTenantResponse = ApiResponse<{
443
- /** Confirmation message indicating successful deletion */
444
- message: string;
445
- }>;
446
- /**
447
- * Response structure for tenant creation operations
448
- *
449
- * Contains the newly created tenant information along with an authentication
450
- * token that provides Row-Level Security (RLS) access to the tenant's data.
451
- * The token should be stored securely and used for subsequent API calls
452
- * that require tenant-specific access.
453
- *
454
- * @example
455
- * ```typescript
456
- * const response: CreateTenantResponse = {
457
- * data: {
458
- * tenant: {
459
- * id: 'tenant_123',
460
- * name: 'My Company',
461
- * stripe_customer_id: 'cus_abc123'
462
- * },
463
- * message: 'Tenant created successfully',
464
- * token: 'eyJhbGciOiJIUzI1NiIs...'
465
- * },
466
- * status: 201
467
- * };
468
- * ```
469
- *
470
- * @since 1.0.0
471
- * @public
472
- * @group Tenant Management
473
- */
474
- type CreateTenantResponse = ApiResponse<{
475
- /** The newly created tenant object */
476
- tenant: Tenant;
477
- /** Success message confirming tenant creation */
478
- message: string;
479
- /** JWT token for RLS policies specific to the active tenant */
480
- token: string;
481
- }>;
482
- /**
483
- * Tenant entity structure that maps to the database schema
484
- *
485
- * Represents a tenant in the multi-tenant system with billing integration
486
- * via Stripe. Each tenant can have multiple users with different roles
487
- * and maintains its own isolated data through RLS policies.
488
- *
489
- * @example
490
- * ```typescript
491
- * const tenant: Tenant = {
492
- * id: 'tenant_abc123',
493
- * name: 'Acme Corporation',
494
- * stripe_customer_id: 'cus_stripe123',
495
- * type: 'business',
496
- * created_at: '2024-01-15T10:30:00Z',
497
- * updated_at: '2024-01-15T10:30:00Z'
498
- * };
499
- * ```
500
- *
501
- * @since 1.0.0
502
- * @public
503
- * @group Tenant Management
504
- */
505
- type Tenant = {
506
- /** Unique identifier for the tenant */
507
- id: string;
508
- /** Display name of the tenant organization */
509
- name: string;
510
- /** Associated Stripe customer ID for billing */
511
- stripe_customer_id: string;
512
- /** Type of tenant (e.g., 'individual', 'organization') */
513
- type: string;
514
- /** ISO 8601 timestamp when the tenant was created */
515
- created_at: string;
516
- /** ISO 8601 timestamp when the tenant was last updated */
517
- updated_at: string;
518
- };
519
- /**
520
- * Required data for creating a new tenant
521
- *
522
- * Contains the essential information needed to establish a new tenant
523
- * in the system, including billing setup and initial user assignment.
524
- *
525
- * @example
526
- * ```typescript
527
- * const tenantData: CreateTenantRequest = {
528
- * name: 'My New Company',
529
- * billing_email: 'billing@mynewcompany.com',
530
- * user_id: 'user_abc123'
531
- * };
532
- * ```
533
- *
534
- * @since 1.0.0
535
- * @public
536
- * @group Tenant Management
537
- */
538
- type CreateTenantRequest = {
539
- /** Name of the tenant organization */
540
- name: string;
541
- /** Email address for billing notifications */
542
- billing_email: string;
543
- /** ID of the user who will own the tenant */
544
- user_id: string;
545
- };
546
- /**
547
- * Tenant management operations handler
548
- *
549
- * This class provides core tenant lifecycle management operations including
550
- * creation, deletion, and active tenant switching. It handles all the fundamental
551
- * operations needed to manage tenants in a multi-tenant application with
552
- * integrated billing and row-level security.
553
- *
554
- * The manager handles:
555
- * - Tenant creation with Stripe billing integration
556
- * - Secure tenant deletion with data cleanup
557
- * - Active tenant switching with JWT token management
558
- * - User permission validation for all operations
559
- *
560
- * All operations are performed within the authenticated user context and
561
- * respect tenant ownership and permission rules.
562
- *
563
- * @example
564
- * ```typescript
565
- * const tenantManager = new TenantManger(omnibaseClient);
566
- *
567
- * // Create a new tenant
568
- * const tenant = await tenantManager.createTenant({
569
- * name: 'Acme Corp',
570
- * billing_email: 'billing@acme.com',
571
- * user_id: 'user_123'
572
- * });
573
- *
574
- * // Switch to the new tenant
575
- * await tenantManager.switchActiveTenant(tenant.data.tenant.id);
576
- *
577
- * // Delete tenant (owner only)
578
- * await tenantManager.deleteTenant(tenant.data.tenant.id);
579
- * ```
580
- *
581
- * @since 1.0.0
582
- * @public
583
- * @group Tenant Management
584
- */
585
- declare class TenantManger {
586
- private omnibaseClient;
587
- /**
588
- * Creates a new TenantManger instance
589
- *
590
- * Initializes the manager with the provided Omnibase client for making
591
- * authenticated API requests to tenant management endpoints.
592
- *
593
- * @param omnibaseClient - Configured Omnibase client instance
594
- *
595
- * @group Tenant Management
596
- */
597
- constructor(omnibaseClient: OmnibaseClient);
598
- /**
599
- * Creates a new tenant in the multi-tenant system
600
- *
601
- * Establishes a new tenant with integrated Stripe billing setup and assigns
602
- * the specified user as the tenant owner. The operation creates the necessary
603
- * database records and returns a JWT token that enables Row-Level Security
604
- * access to the tenant's isolated data.
605
- *
606
- * The function automatically handles Stripe customer creation for billing
607
- * integration and sets up the initial tenant configuration. The returned
608
- * token should be stored securely for subsequent API calls.
609
- *
610
- * @param tenantData - Configuration object for the new tenant
611
- * @param tenantData.name - Display name for the tenant organization
612
- * @param tenantData.billing_email - Email address for Stripe billing notifications
613
- * @param tenantData.user_id - Unique identifier of the user who will own this tenant
614
- *
615
- * @returns Promise resolving to the created tenant with authentication token
616
- *
617
- * @throws {Error} When required fields (name, user_id) are missing or empty
618
- * @throws {Error} When the API request fails due to network issues
619
- * @throws {Error} When the server returns an error response (4xx, 5xx status codes)
620
- *
621
- * @example
622
- * Basic tenant creation:
623
- * ```typescript
624
- * const newTenant = await createTenant({
625
- * name: 'Acme Corporation',
626
- * billing_email: 'billing@acme.com',
627
- * user_id: 'user_123'
628
- * });
629
- *
630
- * console.log(`Created tenant: ${newTenant.data.tenant.name}`);
631
- * // Store the token for authenticated requests
632
- * localStorage.setItem('tenant_token', newTenant.data.token);
633
- * ```
634
- *
635
- *
636
- * @since 1.0.0
637
- * @public
638
- * @group Tenant Management
639
- */
640
- createTenant(tenantData: CreateTenantRequest): Promise<CreateTenantResponse>;
641
- /**
642
- * Permanently deletes a tenant and all associated data
643
- *
644
- * ⚠️ **WARNING: This operation is irreversible and will permanently delete:**
645
- * - The tenant record and all metadata
646
- * - All user memberships and invitations for this tenant
647
- * - All tenant-specific data protected by row-level security
648
- * - Any tenant-related billing information
649
- * - All tenant configuration and settings
650
- *
651
- * **Access Control:**
652
- * Only tenant owners can delete a tenant. This operation requires:
653
- * - User must be authenticated
654
- * - User must have 'owner' role for the specified tenant
655
- * - Tenant must exist and be accessible to the user
656
- *
657
- * **Security Considerations:**
658
- * - All tenant data is immediately and permanently removed
659
- * - Other tenant members lose access immediately
660
- * - Any active sessions for this tenant are invalidated
661
- * - Billing subscriptions are cancelled (if applicable)
662
- * - Audit logs for deletion are maintained for compliance
663
- *
664
- * @param tenantId - The unique identifier of the tenant to delete
665
- *
666
- * @returns Promise resolving to a confirmation message
667
- *
668
- * @throws {Error} When the tenantId parameter is missing or empty
669
- * @throws {Error} When the user is not authenticated
670
- * @throws {Error} When the user is not an owner of the specified tenant
671
- * @throws {Error} When the tenant doesn't exist or is not accessible
672
- * @throws {Error} When the API request fails due to network issues
673
- * @throws {Error} When the server returns an error response (4xx, 5xx status codes)
674
- *
675
- * @example
676
- * Basic tenant deletion with confirmation:
677
- * ```typescript
678
- * const tenantToDelete = 'tenant_abc123';
679
- *
680
- * // Always confirm before deleting
681
- * const userConfirmed = confirm(
682
- * 'Are you sure you want to delete this tenant? This action cannot be undone.'
683
- * );
684
- *
685
- * if (userConfirmed) {
686
- * try {
687
- * const result = await deleteTenant(tenantToDelete);
688
- * console.log(result.data.message); // "Tenant deleted successfully"
689
- *
690
- * // Redirect user away from deleted tenant
691
- * window.location.href = '/dashboard';
692
- * } catch (error) {
693
- * console.error('Failed to delete tenant:', error);
694
- * }
695
- * }
696
- * ```
697
- *
698
- * @since 1.0.0
699
- * @public
700
- * @group Tenant Management
701
- */
702
- deleteTenant(tenantId: string): Promise<DeleteTenantResponse>;
703
- /**
704
- * Switches the user's active tenant context
705
- *
706
- * Changes the user's active tenant to the specified tenant ID, updating
707
- * their authentication context and permissions. This function is essential
708
- * for multi-tenant applications where users belong to multiple tenants
709
- * and need to switch between them.
710
- *
711
- * The function performs several operations:
712
- * - Validates that the user has access to the specified tenant
713
- * - Updates the user's active tenant in their session
714
- * - Generates a new JWT token with updated tenant claims
715
- * - Updates any cached tenant-specific data
716
- *
717
- * After switching tenants, all subsequent API calls will be made within
718
- * the context of the new active tenant, with row-level security policies
719
- * applied accordingly. The new JWT token should be used for all future
720
- * authenticated requests.
721
- *
722
- * @param tenantId - The ID of the tenant to switch to (must be a tenant the user belongs to)
723
- *
724
- * @returns Promise resolving to a new JWT token and success confirmation
725
- *
726
- * @throws {Error} When the tenantId parameter is missing or empty
727
- * @throws {Error} When the user doesn't have access to the specified tenant
728
- * @throws {Error} When the user is not authenticated
729
- * @throws {Error} When the specified tenant doesn't exist
730
- * @throws {Error} When the API request fails due to network issues
731
- * @throws {Error} When the server returns an error response (4xx, 5xx status codes)
732
- *
733
- * @example
734
- * Basic tenant switching:
735
- * ```typescript
736
- * const result = await switchActiveTenant('tenant_xyz789');
737
- *
738
- * // Now all API calls will be in the context of tenant_xyz789
739
- * const tenantData = await getCurrentTenantData();
740
- * ```
741
- *
742
- * @example
743
- * Using with tenant-aware data fetching:
744
- * ```typescript
745
- * // Switch tenant and immediately fetch tenant-specific data
746
- * const switchAndLoadTenant = async (tenantId: string) => {
747
- * try {
748
- * // Switch to new tenant context
749
- * const switchResult = await switchActiveTenant(tenantId);
750
- *
751
- * // Update authentication token
752
- * setAuthToken(switchResult.data.token);
753
- *
754
- * // Fetch data in new tenant context
755
- * const [tenantInfo, userPermissions, tenantSettings] = await Promise.all([
756
- * getTenantInfo(),
757
- * getUserPermissions(),
758
- * getTenantSettings()
759
- * ]);
760
- *
761
- * return {
762
- * tenant: tenantInfo,
763
- * permissions: userPermissions,
764
- * settings: tenantSettings
765
- * };
766
- * } catch (error) {
767
- * console.error('Failed to switch tenant and load data:', error);
768
- * throw error;
769
- * }
770
- * };
771
- * ```
772
- *
773
- * @since 1.0.0
774
- * @public
775
- * @group Tenant Management
776
- */
777
- switchActiveTenant(tenantId: string): Promise<SwitchActiveTenantResponse>;
778
- }
779
-
780
- /**
781
- * Main tenant management handler
782
- *
783
- * This is the primary entry point for all tenant-related operations in the
784
- * Omnibase SDK. It provides a unified interface to both tenant management
785
- * and invitation functionality through dedicated manager instances.
786
- *
787
- * The handler follows the composition pattern, combining specialized managers
788
- * for different aspects of tenant functionality:
789
- * - `tenants`: Core tenant operations (create, delete, switch)
790
- * - `invites`: User invitation management (create, accept)
791
- *
792
- * All operations are performed within the context of the authenticated user
793
- * and respect tenant-level permissions and row-level security policies.
794
- *
795
- * @example
796
- * ```typescript
797
- * import { OmnibaseClient } from '@omnibase/core-js';
798
- * import { TenantHandler } from '@omnibase/core-js/tenants';
799
- *
800
- * const client = new OmnibaseClient({ apiKey: 'your-api-key' });
801
- * const tenantHandler = new TenantHandler(client);
802
- *
803
- * // Create a new tenant
804
- * const tenant = await tenantHandler.tenants.createTenant({
805
- * name: 'My Company',
806
- * billing_email: 'billing@company.com',
807
- * user_id: 'user_123'
808
- * });
809
- *
810
- * // Invite users to the tenant
811
- * const invite = await tenantHandler.invites.create(tenant.data.tenant.id, {
812
- * email: 'colleague@company.com',
813
- * role: 'member'
814
- * });
815
- *
816
- * // Switch to the new tenant
817
- * await tenantHandler.tenants.switchActiveTenant(tenant.data.tenant.id);
818
- * ```
819
- *
820
- * @since 1.0.0
821
- * @public
822
- * @group Tenant Management
823
- */
824
- declare class TenantHandler {
825
- private omnibaseClient;
826
- /**
827
- * Creates a new TenantHandler instance
828
- *
829
- * Initializes the handler with the provided Omnibase client and sets up
830
- * the specialized manager instances for tenant and invitation operations.
831
- * The client is used for all underlying HTTP requests and authentication.
832
- *
833
- * @param omnibaseClient - Configured Omnibase client instance
834
- *
835
- * @example
836
- * ```typescript
837
- * const client = new OmnibaseClient({
838
- * apiKey: 'your-api-key',
839
- * baseURL: 'https://api.yourapp.com'
840
- * });
841
- * const tenantHandler = new TenantHandler(client);
842
- * ```
843
- *
844
- * @group Tenant Management
845
- */
846
- constructor(omnibaseClient: OmnibaseClient);
847
- /**
848
- * Core tenant management operations
849
- *
850
- * Provides access to tenant lifecycle operations including creation,
851
- * deletion, and active tenant switching. All operations respect user
852
- * permissions and tenant ownership rules.
853
- *
854
- * @example
855
- * ```typescript
856
- * // Create a new tenant
857
- * const tenant = await tenantHandler.tenants.createTenant({
858
- * name: 'New Company',
859
- * billing_email: 'billing@newcompany.com',
860
- * user_id: 'user_456'
861
- * });
862
- *
863
- * // Switch to the tenant
864
- * await tenantHandler.tenants.switchActiveTenant(tenant.data.tenant.id);
865
- *
866
- * // Delete the tenant (owner only)
867
- * await tenantHandler.tenants.deleteTenant(tenant.data.tenant.id);
868
- * ```
869
- */
870
- readonly tenants: TenantManger;
871
- /**
872
- * Tenant invitation management operations
873
- *
874
- * Provides access to user invitation functionality including creating
875
- * invitations for new users and accepting existing invitations.
876
- * Supports role-based access control and secure token-based workflows.
877
- *
878
- * @example
879
- * ```typescript
880
- * // Create an invitation
881
- * const invite = await tenantHandler.invites.create('tenant_123', {
882
- * email: 'newuser@company.com',
883
- * role: 'admin'
884
- * });
885
- *
886
- * // Accept an invitation (from the invited user's session)
887
- * const result = await tenantHandler.invites.accept('invite_token_xyz');
888
- * ```
889
- */
890
- readonly invites: TenantInviteManager;
891
- }
892
-
893
- type OmnibaseClientConfig = {
894
- api_url: string;
895
- };
896
- declare class OmnibaseClient {
897
- private config;
898
- constructor(config: OmnibaseClientConfig);
899
- /**
900
- * Main payment handler for all payment-related operations
901
- *
902
- * This class serves as the central coordinator for all payment functionality,
903
- * providing access to checkout sessions, billing configuration, customer portals,
904
- * and usage tracking. It handles the low-level HTTP communication with the
905
- * payment API and delegates specific operations to specialized managers.
906
- *
907
- * The handler automatically manages authentication, request formatting, and
908
- * provides a consistent interface across all payment operations.
909
- *
910
- * @example
911
- * ```typescript
912
- * // Create a checkout session
913
- * const checkout = await omnibase.payments.checkout.createSession({
914
- * price_id: 'price_123',
915
- * mode: 'subscription',
916
- * success_url: 'https://app.com/success',
917
- * cancel_url: 'https://app.com/cancel'
918
- * });
919
- *
920
- * // Get available products
921
- * const products = await omnibase.payments.config.getAvailableProducts();
922
- * ```
923
- */
924
- readonly payments: PaymentHandler;
925
- readonly tenants: TenantHandler;
926
- readonly permissions: PermissionsClient;
927
- fetch(endpoint: string, options?: RequestInit): Promise<Response>;
928
- }
929
-
930
- /**
931
- * Configuration options for creating a Stripe checkout session
932
- *
933
- * Defines all parameters needed to create a checkout session for either
934
- * one-time payments or subscription billing. The session will redirect
935
- * users to Stripe's hosted checkout page.
936
- *
937
- * @example
938
- * ```typescript
939
- * const options: CheckoutOptions = {
940
- * price_id: 'price_1234567890',
941
- * mode: 'subscription',
942
- * success_url: 'https://app.com/success?session_id={CHECKOUT_SESSION_ID}',
943
- * cancel_url: 'https://app.com/pricing',
944
- * customer_id: 'cus_1234567890'
945
- * };
946
- * ```
947
- *
948
- * @since 1.0.0
949
- * @public
950
- * @group Checkout
951
- */
952
- type CheckoutOptions = {
953
- /** Stripe price ID for the product/service being purchased */
954
- price_id: string;
955
- /**
956
- * Checkout mode determining the type of transaction
957
- * - 'payment': One-time payment
958
- * - 'subscription': Recurring subscription
959
- */
960
- mode: "payment" | "subscription";
961
- /**
962
- * URL to redirect to after successful payment
963
- * Can include {CHECKOUT_SESSION_ID} placeholder for session tracking
964
- */
965
- success_url: string;
966
- /** URL to redirect to if the user cancels the checkout */
967
- cancel_url: string;
968
- /**
969
- * Optional Stripe customer ID to associate with this checkout
970
- * If not provided, a new customer will be created
971
- */
972
- customer_id?: string;
973
- };
974
- /**
975
- * Response from creating a checkout session
976
- *
977
- * Contains the checkout session URL and ID for redirecting users
978
- * to Stripe's hosted checkout page and tracking the session.
979
- *
980
- * @since 1.0.0
981
- * @public
982
- * @group Checkout
983
- */
984
- type CreateCheckoutResponse = ApiResponse<{
985
- /** URL to redirect the user to for completing payment */
986
- url: string;
987
- /** Unique identifier for the checkout session */
988
- sessionId: string;
989
- }>;
990
- /**
991
- * Manager for Stripe checkout session operations
992
- *
993
- * Handles creation and management of Stripe checkout sessions for both
994
- * one-time payments and subscription billing. Provides a simple interface
995
- * for redirecting users to Stripe's hosted checkout experience.
996
- *
997
- * Checkout sessions are the recommended way to accept payments as they
998
- * provide a secure, PCI-compliant payment flow without requiring
999
- * sensitive payment data to touch your servers.
1000
- *
1001
- * @example
1002
- * Creating a subscription checkout:
1003
- * ```typescript
1004
- * const checkoutManager = new CheckoutManager(paymentHandler);
1005
- *
1006
- * const session = await checkoutManager.createSession({
1007
- * price_id: 'price_monthly_pro',
1008
- * mode: 'subscription',
1009
- * success_url: 'https://app.com/welcome?session_id={CHECKOUT_SESSION_ID}',
1010
- * cancel_url: 'https://app.com/pricing',
1011
- * customer_id: 'cus_existing_customer'
1012
- * });
1013
- *
1014
- * // Redirect user to checkout
1015
- * window.location.href = session.data.url;
1016
- * ```
1017
- *
1018
- * @since 1.0.0
1019
- * @public
1020
- * @group Checkout
1021
- */
1022
- declare class CheckoutManager {
1023
- private omnibaseClient;
1024
- /**
1025
- * Initialize the checkout manager
1026
- *
1027
- * @param paymentHandler - Payment handler instance for API communication
1028
- *
1029
- * @group Checkout
1030
- */
1031
- constructor(omnibaseClient: OmnibaseClient);
1032
- /**
1033
- * Create a new Stripe checkout session
1034
- *
1035
- * Creates a checkout session with the specified options and returns
1036
- * the session URL for redirecting the user to complete payment.
1037
- * The session will be configured for either one-time payment or
1038
- * subscription based on the mode parameter.
1039
- *
1040
- * @param options - Configuration options for the checkout session
1041
- * @param options.price_id - Stripe price ID for the product/service
1042
- * @param options.mode - Payment mode ('payment' for one-time, 'subscription' for recurring)
1043
- * @param options.success_url - URL to redirect after successful payment
1044
- * @param options.cancel_url - URL to redirect if user cancels
1045
- * @param options.customer_id - Optional existing Stripe customer ID
1046
- *
1047
- * @returns Promise resolving to checkout session response with URL and session ID
1048
- *
1049
- * @throws {Error} When the API request fails due to network issues
1050
- * @throws {Error} When the server returns an error response (invalid price_id, etc.)
1051
- * @throws {ValidationError} When required parameters are missing or invalid
1052
- *
1053
- * @example
1054
- * One-time payment checkout:
1055
- * ```typescript
1056
- * const session = await checkoutManager.createSession({
1057
- * price_id: 'price_one_time_product',
1058
- * mode: 'payment',
1059
- * success_url: 'https://app.com/success',
1060
- * cancel_url: 'https://app.com/cancel'
1061
- * });
1062
- *
1063
- * // Redirect to Stripe checkout
1064
- * window.location.href = session.data.url;
1065
- * ```
1066
- *
1067
- * @example
1068
- * Subscription checkout with existing customer:
1069
- * ```typescript
1070
- * const session = await checkoutManager.createSession({
1071
- * price_id: 'price_monthly_plan',
1072
- * mode: 'subscription',
1073
- * success_url: 'https://app.com/dashboard?welcome=true',
1074
- * cancel_url: 'https://app.com/pricing',
1075
- * customer_id: 'cus_12345'
1076
- * });
1077
- *
1078
- * console.log(`Session created: ${session.data.sessionId}`);
1079
- * ```
1080
- *
1081
- * @since 1.0.0
1082
- * @group Checkout
1083
- */
1084
- createSession(options: CheckoutOptions): Promise<CreateCheckoutResponse>;
1085
- }
1086
-
1087
- /**
1088
- * Response from Stripe configuration API endpoints
1089
- *
1090
- * Contains the current Stripe configuration including products, prices,
1091
- * and UI customization settings. This represents the complete billing
1092
- * configuration loaded from the database.
1093
- *
1094
- * @since 1.0.0
1095
- * @public
1096
- * @group Configuration
1097
- */
1098
- type StripeConfigResponse = ApiResponse<{
1099
- /** The complete Stripe configuration object */
1100
- config: StripeConfiguration;
1101
- /** Optional message from the API response */
1102
- message?: string;
1103
- }>;
1104
- /**
1105
- * Complete Stripe billing configuration
1106
- *
1107
- * Represents a versioned Stripe configuration containing all products,
1108
- * prices, and UI customizations. This configuration is stored in the
1109
- * database and enables safe deployment and rollback of pricing changes.
1110
- *
1111
- * @example
1112
- * ```typescript
1113
- * const config: StripeConfiguration = {
1114
- * version: "v1.2.0",
1115
- * products: [
1116
- * {
1117
- * id: "starter_plan",
1118
- * name: "Starter Plan",
1119
- * description: "Perfect for individuals and small teams",
1120
- * type: "service",
1121
- * prices: [...]
1122
- * }
1123
- * ]
1124
- * };
1125
- * ```
1126
- *
1127
- * @since 1.0.0
1128
- * @public
1129
- * @group Configuration
1130
- */
1131
- interface StripeConfiguration {
1132
- /** Version identifier for this configuration */
1133
- version: string;
1134
- /** Array of all products in this configuration */
1135
- products: Product[];
1136
- }
1137
- /**
1138
- * Product definition in Stripe configuration
1139
- *
1140
- * Represents a billable product or service with associated pricing options
1141
- * and UI customizations. Products can be services, physical goods, or
1142
- * metered usage products.
1143
- *
1144
- * @example
1145
- * ```typescript
1146
- * const product: Product = {
1147
- * id: "pro_plan",
1148
- * name: "Professional Plan",
1149
- * description: "Advanced features for growing businesses",
1150
- * type: "service",
1151
- * prices: [
1152
- * { id: "monthly", amount: 2900, currency: "usd", interval: "month" },
1153
- * { id: "yearly", amount: 29000, currency: "usd", interval: "year" }
1154
- * ],
1155
- * ui: {
1156
- * display_name: "Pro",
1157
- * tagline: "Most Popular",
1158
- * features: ["Unlimited projects", "24/7 support"],
1159
- * highlighted: true
1160
- * }
1161
- * };
1162
- * ```
1163
- *
1164
- * @since 1.0.0
1165
- * @public
1166
- * @group Configuration
1167
- */
1168
- interface Product {
1169
- /** Unique identifier for this product */
1170
- id: string;
1171
- /** Display name for the product */
1172
- name: string;
1173
- /** Optional detailed description */
1174
- description?: string;
1175
- /**
1176
- * Product type affecting billing behavior
1177
- * - 'service': Subscription services
1178
- * - 'good': Physical or digital goods
1179
- * - 'metered': Usage-based billing
1180
- */
1181
- type?: "service" | "good" | "metered";
1182
- /** Array of pricing options for this product */
1183
- prices: Price[];
1184
- /** Optional UI customization settings */
1185
- ui?: ProductUI;
1186
- }
1187
- /**
1188
- * Price definition for a product
1189
- *
1190
- * Defines a specific pricing option including amount, currency, billing
1191
- * frequency, and advanced pricing features like tiered billing. Supports
1192
- * both fixed and usage-based pricing models.
1193
- *
1194
- * @example
1195
- * Simple monthly pricing:
1196
- * ```typescript
1197
- * const monthlyPrice: Price = {
1198
- * id: "monthly_standard",
1199
- * amount: 1999, // $19.99 in cents
1200
- * currency: "usd",
1201
- * interval: "month",
1202
- * usage_type: "licensed"
1203
- * };
1204
- * ```
1205
- *
1206
- * @example
1207
- * Tiered usage pricing:
1208
- * ```typescript
1209
- * const tieredPrice: Price = {
1210
- * id: "api_calls_tiered",
1211
- * currency: "usd",
1212
- * usage_type: "metered",
1213
- * billing_scheme: "tiered",
1214
- * tiers_mode: "graduated",
1215
- * tiers: [
1216
- * { up_to: 1000, unit_amount: 10 }, // First 1000 calls at $0.10 each
1217
- * { up_to: "inf", unit_amount: 5 } // Additional calls at $0.05 each
1218
- * ]
1219
- * };
1220
- * ```
1221
- *
1222
- * @since 1.0.0
1223
- * @public
1224
- * @group Configuration
1225
- */
1226
- interface Price {
1227
- /** Unique identifier for this price */
1228
- id: string;
1229
- /**
1230
- * Price amount in smallest currency unit (e.g., cents for USD)
1231
- * Omitted for usage-based pricing with tiers
1232
- */
1233
- amount?: number;
1234
- /** Currency code (ISO 4217) */
1235
- currency: string;
1236
- /**
1237
- * Billing interval for recurring prices
1238
- * - 'month': Monthly billing
1239
- * - 'year': Annual billing
1240
- * - 'week': Weekly billing
1241
- * - 'day': Daily billing
1242
- */
1243
- interval?: "month" | "year" | "week" | "day";
1244
- /**
1245
- * Number of intervals between billings
1246
- * @defaultValue 1
1247
- */
1248
- interval_count?: number;
1249
- /**
1250
- * Usage type determining billing model
1251
- * - 'licensed': Fixed recurring pricing
1252
- * - 'metered': Usage-based pricing
1253
- */
1254
- usage_type?: "licensed" | "metered";
1255
- /**
1256
- * Billing scheme for complex pricing
1257
- * - 'per_unit': Simple per-unit pricing
1258
- * - 'tiered': Graduated or volume-based tiers
1259
- */
1260
- billing_scheme?: "per_unit" | "tiered";
1261
- /**
1262
- * Tier calculation mode (when billing_scheme is 'tiered')
1263
- * - 'graduated': Each tier applies to usage within that tier
1264
- * - 'volume': Entire usage charged at the tier rate
1265
- */
1266
- tiers_mode?: "graduated" | "volume";
1267
- /** Pricing tiers for tiered billing */
1268
- tiers?: Tier[];
1269
- /** Optional UI customization settings */
1270
- ui?: PriceUI;
1271
- }
1272
- /**
1273
- * Pricing tier definition for tiered billing
1274
- *
1275
- * Defines a usage range and associated pricing for tiered billing models.
1276
- * Enables graduated pricing where different usage levels have different rates.
1277
- *
1278
- * @example
1279
- * ```typescript
1280
- * const tiers: Tier[] = [
1281
- * { up_to: 100, flat_amount: 0, unit_amount: 10 }, // First 100 free, then $0.10 each
1282
- * { up_to: 1000, unit_amount: 5 }, // Next 900 at $0.05 each
1283
- * { up_to: "inf", unit_amount: 2 } // Beyond 1000 at $0.02 each
1284
- * ];
1285
- * ```
1286
- *
1287
- * @since 1.0.0
1288
- * @public
1289
- * @group Configuration
1290
- */
1291
- interface Tier {
1292
- /**
1293
- * Upper bound for this tier
1294
- * Use "inf" for the highest tier with no upper limit
1295
- */
1296
- up_to: number | "inf";
1297
- /**
1298
- * Fixed amount charged for this tier (in cents)
1299
- * Used for flat fees at tier boundaries
1300
- */
1301
- flat_amount?: number;
1302
- /**
1303
- * Per-unit amount for usage within this tier (in cents)
1304
- * Applied to each unit of usage in this tier range
1305
- */
1306
- unit_amount?: number;
1307
- }
1308
- /**
1309
- * UI customization settings for products
1310
- *
1311
- * Controls how products are displayed in pricing tables and marketing pages.
1312
- * Provides extensive customization options for branding and presentation.
1313
- *
1314
- * @example
1315
- * ```typescript
1316
- * const productUI: ProductUI = {
1317
- * display_name: "Enterprise",
1318
- * tagline: "For large organizations",
1319
- * features: ["SSO integration", "Advanced analytics", "Priority support"],
1320
- * badge: "Most Popular",
1321
- * cta_text: "Contact Sales",
1322
- * highlighted: true,
1323
- * sort_order: 3
1324
- * };
1325
- * ```
1326
- *
1327
- * @since 1.0.0
1328
- * @public
1329
- * @group UI Configuration
1330
- */
1331
- interface ProductUI {
1332
- /** Custom display name (overrides product.name) */
1333
- display_name?: string;
1334
- /** Marketing tagline or subtitle */
1335
- tagline?: string;
1336
- /** List of key features to highlight */
1337
- features?: string[];
1338
- /** Optional badge text (e.g., "Popular", "Best Value") */
1339
- badge?: string;
1340
- /** Custom call-to-action button text */
1341
- cta_text?: string;
1342
- /** Whether to visually highlight this product */
1343
- highlighted?: boolean;
1344
- /** Sort order for display (lower numbers first) */
1345
- sort_order?: number;
1346
- }
1347
- /**
1348
- * UI customization settings for prices
1349
- *
1350
- * Controls how individual price options are displayed within products.
1351
- * Enables custom formatting, feature lists, and usage limits display.
1352
- *
1353
- * @example
1354
- * ```typescript
1355
- * const priceUI: PriceUI = {
1356
- * display_name: "Annual Billing",
1357
- * price_display: {
1358
- * custom_text: "$99/year",
1359
- * suffix: "billed annually"
1360
- * },
1361
- * billing_period: "per year",
1362
- * features: ["2 months free", "Priority support"],
1363
- * limits: [
1364
- * { text: "Up to 10 users", value: 10, unit: "users" },
1365
- * { text: "100GB storage", value: 100, unit: "GB" }
1366
- * ]
1367
- * };
1368
- * ```
1369
- *
1370
- * @since 1.0.0
1371
- * @public
1372
- * @group UI Configuration
1373
- */
1374
- interface PriceUI {
1375
- /** Custom display name for this price option */
1376
- display_name?: string;
1377
- /** Custom price display formatting */
1378
- price_display?: PriceDisplay;
1379
- /** Custom billing period description */
1380
- billing_period?: string;
1381
- /** Price-specific features to highlight */
1382
- features?: string[];
1383
- /** Usage limits and quotas for this price */
1384
- limits?: PriceLimit[];
1385
- }
1386
- /**
1387
- * Custom price display formatting options
1388
- *
1389
- * Provides fine-grained control over how prices are formatted and displayed,
1390
- * including custom text, currency symbols, and suffixes.
1391
- *
1392
- * @example
1393
- * ```typescript
1394
- * const priceDisplay: PriceDisplay = {
1395
- * custom_text: "Contact us for pricing",
1396
- * show_currency: false,
1397
- * suffix: "per month"
1398
- * };
1399
- * ```
1400
- *
1401
- * @since 1.0.0
1402
- * @public
1403
- * @group UI Configuration
1404
- */
1405
- interface PriceDisplay {
1406
- /**
1407
- * Custom text to display instead of calculated price
1408
- * Useful for "Contact us" or "Free" pricing
1409
- */
1410
- custom_text?: string;
1411
- /**
1412
- * Whether to show currency symbol
1413
- * @defaultValue true
1414
- */
1415
- show_currency?: boolean;
1416
- /** Additional text to append after the price */
1417
- suffix?: string;
1418
- }
1419
- /**
1420
- * Usage limit or quota definition
1421
- *
1422
- * Represents a specific limit or quota associated with a price tier,
1423
- * such as user limits, storage quotas, or API call allowances.
1424
- *
1425
- * @example
1426
- * ```typescript
1427
- * const limits: PriceLimit[] = [
1428
- * { text: "Up to 5 team members", value: 5, unit: "users" },
1429
- * { text: "50GB storage included", value: 50, unit: "GB" },
1430
- * { text: "Unlimited API calls" } // No value/unit for unlimited
1431
- * ];
1432
- * ```
1433
- *
1434
- * @since 1.0.0
1435
- * @public
1436
- * @group UI Configuration
1437
- */
1438
- interface PriceLimit {
1439
- /** Human-readable description of the limit */
1440
- text: string;
1441
- /** Numeric value of the limit (omit for unlimited) */
1442
- value?: number;
1443
- /** Unit of measurement for the limit */
1444
- unit?: string;
1445
- }
1446
- /**
1447
- * UI-ready product data structure for pricing tables
1448
- *
1449
- * Extended product interface that includes pre-processed display data
1450
- * optimized for rendering pricing tables and marketing pages. Contains
1451
- * formatted prices, organized features, and display-ready content.
1452
- *
1453
- * This interface is returned by [`getAvailableProducts()`](config.ts) and provides
1454
- * everything needed to render a complete pricing table without additional
1455
- * data processing.
1456
- *
1457
- * @example
1458
- * ```typescript
1459
- * const products: ProductWithPricingUI[] = await configManager.getAvailableProducts();
1460
- *
1461
- * products.forEach(product => {
1462
- * const display = product.pricing_display;
1463
- * console.log(`${display.name}: ${display.tagline}`);
1464
- *
1465
- * display.prices.forEach(price => {
1466
- * console.log(` ${price.display_name}: ${price.formatted_price}`);
1467
- * });
1468
- * });
1469
- * ```
1470
- *
1471
- * @since 1.0.0
1472
- * @public
1473
- * @group UI Configuration
1474
- */
1475
- interface ProductWithPricingUI extends Product {
1476
- /** Pre-processed display data for UI rendering */
1477
- pricing_display: {
1478
- /** Display name for the product */
1479
- name: string;
1480
- /** Marketing tagline or subtitle */
1481
- tagline?: string;
1482
- /** Key features to highlight */
1483
- features: string[];
1484
- /** Optional badge text */
1485
- badge?: string;
1486
- /** Call-to-action button text */
1487
- cta_text: string;
1488
- /** Whether this product should be visually highlighted */
1489
- highlighted: boolean;
1490
- /** Sort order for display */
1491
- sort_order: number;
1492
- /** UI-ready price information */
1493
- prices: Array<{
1494
- /** Price identifier */
1495
- id: string;
1496
- /** Display name for this price option */
1497
- display_name: string;
1498
- /** Formatted price string ready for display */
1499
- formatted_price: string;
1500
- /** Billing period description */
1501
- billing_period: string;
1502
- /** Price-specific features */
1503
- features: string[];
1504
- /** Usage limits and quotas */
1505
- limits: Array<{
1506
- /** Limit description */
1507
- text: string;
1508
- /** Numeric value (if applicable) */
1509
- value?: number;
1510
- /** Unit of measurement */
1511
- unit?: string;
1512
- }>;
1513
- }>;
1514
- };
1515
- }
1516
-
1517
- declare class ConfigManager {
1518
- private omnibaseClient;
1519
- constructor(omnibaseClient: OmnibaseClient);
1520
- /**
1521
- * Get the current Stripe configuration from the database
1522
- *
1523
- * Retrieves the latest Stripe configuration including products, prices,
1524
- * and UI customization data. This configuration represents the current
1525
- * active pricing structure with all UI elements for pricing table rendering.
1526
- *
1527
- * @returns Promise resolving to the current Stripe configuration
1528
- *
1529
- * @throws {Error} When the API request fails due to network issues
1530
- * @throws {Error} When the server returns an error response (4xx, 5xx status codes)
1531
- *
1532
- * @example
1533
- * Basic usage:
1534
- * ```typescript
1535
- * const config = await getStripeConfig();
1536
- * console.log(`Found ${config.data.config.products.length} products`);
1537
- *
1538
- * // Access product UI configuration
1539
- * config.data.config.products.forEach(product => {
1540
- * console.log(`${product.name}: ${product.ui?.tagline || 'No tagline'}`);
1541
- * });
1542
- * ```
1543
- */
1544
- getStripeConfig(): Promise<StripeConfigResponse>;
1545
- /**
1546
- * Get available products with UI-ready pricing data
1547
- *
1548
- * Transforms the raw Stripe configuration into UI-ready format for pricing
1549
- * table rendering. Includes formatted pricing, features, limits, and all
1550
- * display customizations needed for marketing pages.
1551
- *
1552
- * @returns Promise resolving to products ready for UI consumption
1553
- *
1554
- * @throws {Error} When the API request fails or configuration is invalid
1555
- *
1556
- * @example
1557
- * Pricing table rendering:
1558
- * ```typescript
1559
- * const products = await getAvailableProducts();
1560
- *
1561
- * products.forEach(product => {
1562
- * const display = product.pricing_display;
1563
- * console.log(`${display.name} - ${display.tagline}`);
1564
- *
1565
- * display.prices.forEach(price => {
1566
- * console.log(` ${price.display_name}: ${price.formatted_price}`);
1567
- * });
1568
- * });
1569
- * ```
1570
- */
1571
- getAvailableProducts(): Promise<ProductWithPricingUI[]>;
1572
- /**
1573
- * Get a specific product by ID
1574
- *
1575
- * Retrieves a single product configuration by its ID from the current
1576
- * Stripe configuration. Useful for product-specific operations.
1577
- *
1578
- * @param productId - The configuration product ID to retrieve
1579
- * @returns Promise resolving to the product or null if not found
1580
- *
1581
- * @example
1582
- * ```typescript
1583
- * const product = await getProduct('starter_plan');
1584
- * if (product) {
1585
- * console.log(`Found product: ${product.name}`);
1586
- * }
1587
- * ```
1588
- */
1589
- getProduct(productId: string): Promise<Product | null>;
1590
- }
1591
-
1592
- /**
1593
- * Configuration options for creating a Stripe customer portal session
1594
- *
1595
- * Defines the parameters needed to create a customer portal session
1596
- * that allows customers to manage their subscription, payment methods,
1597
- * billing history, and other account settings.
1598
- *
1599
- * @example
1600
- * ```typescript
1601
- * const options: PortalOptions = {
1602
- * customer_id: 'cus_1234567890',
1603
- * return_url: 'https://app.com/billing'
1604
- * };
1605
- * ```
1606
- *
1607
- * @since 1.0.0
1608
- * @public
1609
- * @group Portal
1610
- */
1611
- type PortalOptions = {
1612
- /** Stripe customer ID for the user accessing the portal */
1613
- customer_id: string;
1614
- /** URL to redirect the customer to when they exit the portal */
1615
- return_url: string;
1616
- };
1617
- /**
1618
- * Response from creating a customer portal session
1619
- *
1620
- * Contains the portal session URL for redirecting customers to
1621
- * Stripe's hosted customer portal where they can manage their
1622
- * billing and subscription settings.
1623
- *
1624
- * @since 1.0.0
1625
- * @public
1626
- * @group Portal
1627
- */
1628
- type CreateCustomerPortalResponse = ApiResponse<{
1629
- /** URL to redirect the customer to for accessing their portal */
1630
- url: string;
1631
- }>;
1632
- /**
1633
- * Manager for Stripe customer portal operations
1634
- *
1635
- * Handles creation of customer portal sessions that allow customers
1636
- * to manage their own billing information, subscriptions, payment methods,
1637
- * and download invoices through Stripe's hosted portal interface.
1638
- *
1639
- * The customer portal provides a secure, self-service interface that
1640
- * reduces support burden by allowing customers to handle common
1641
- * billing tasks independently.
1642
- *
1643
- * @example
1644
- * Creating a customer portal session:
1645
- * ```typescript
1646
- * const portalManager = new PortalManager(paymentHandler);
1647
- *
1648
- * const portal = await portalManager.create({
1649
- * customer_id: 'cus_customer123',
1650
- * return_url: 'https://app.com/billing'
1651
- * });
1652
- *
1653
- * // Redirect customer to portal
1654
- * window.location.href = portal.data.url;
1655
- * ```
1656
- *
1657
- * @since 1.0.0
1658
- * @public
1659
- * @group Portal
1660
- */
1661
- declare class PortalManager {
1662
- private omnibaseClient;
1663
- /**
1664
- * Initialize the portal manager
1665
- *
1666
- * @param paymentHandler - Payment handler instance for API communication
1667
- *
1668
- * @group Portal
1669
- */
1670
- constructor(omnibaseClient: OmnibaseClient);
1671
- /**
1672
- * Create a new customer portal session
1673
- *
1674
- * Creates a portal session that allows the specified customer to
1675
- * manage their billing information, subscriptions, and payment methods.
1676
- * Returns a URL that the customer should be redirected to.
1677
- *
1678
- * The portal session is temporary and expires after a short period
1679
- * for security. Each access requires creating a new session.
1680
- *
1681
- * @param options - Configuration options for the portal session
1682
- * @param options.customer_id - Stripe customer ID for the user
1683
- * @param options.return_url - URL to redirect to when exiting the portal
1684
- *
1685
- * @returns Promise resolving to portal session response with access URL
1686
- *
1687
- * @throws {Error} When the API request fails due to network issues
1688
- * @throws {Error} When the server returns an error response (invalid customer_id, etc.)
1689
- * @throws {ValidationError} When required parameters are missing or invalid
1690
- *
1691
- * @example
1692
- * Basic portal creation:
1693
- * ```typescript
1694
- * const portal = await portalManager.create({
1695
- * customer_id: 'cus_abc123',
1696
- * return_url: 'https://myapp.com/account/billing'
1697
- * });
1698
- *
1699
- * // Redirect user to portal
1700
- * window.location.href = portal.data.url;
1701
- * ```
1702
- *
1703
- * @example
1704
- * With error handling:
1705
- * ```typescript
1706
- * try {
1707
- * const portal = await portalManager.create({
1708
- * customer_id: currentUser.stripeCustomerId,
1709
- * return_url: window.location.origin + '/billing'
1710
- * });
1711
- *
1712
- * window.location.href = portal.data.url;
1713
- * } catch (error) {
1714
- * console.error('Failed to create portal session:', error);
1715
- * showErrorMessage('Unable to access billing portal. Please try again.');
1716
- * }
1717
- * ```
1718
- *
1719
- * @since 1.0.0
1720
- * @group Portal
1721
- */
1722
- create(options: PortalOptions): Promise<CreateCustomerPortalResponse>;
1723
- }
1724
-
1725
- /**
1726
- * Configuration options for recording usage events
1727
- *
1728
- * Defines the parameters needed to record a usage event for metered billing.
1729
- * Usage events are used to track consumption of metered products and calculate
1730
- * charges based on actual usage rather than fixed pricing.
1731
- *
1732
- * @example
1733
- * ```typescript
1734
- * const options: UsageOptions = {
1735
- * meter_event_name: 'api_calls',
1736
- * customer_id: 'cus_1234567890',
1737
- * value: '1'
1738
- * };
1739
- * ```
1740
- *
1741
- * @since 1.0.0
1742
- * @public
1743
- * @group Usage
1744
- */
1745
- type UsageOptions = {
1746
- /**
1747
- * Name of the meter event to record usage for
1748
- * Must match a meter configured in your Stripe billing configuration
1749
- */
1750
- meter_event_name: string;
1751
- /** Stripe customer ID to record usage for */
1752
- customer_id: string;
1753
- /**
1754
- * Usage value to record as a string
1755
- * Typically represents quantity consumed (e.g., "1" for single API call, "250" for MB of storage)
1756
- */
1757
- value: string;
1758
- };
1759
- /**
1760
- * Manager for usage tracking and metered billing operations
1761
- *
1762
- * Handles recording of usage events for metered billing products. Usage events
1763
- * are used by Stripe to calculate charges for products with usage-based pricing,
1764
- * such as API calls, data transfer, or storage consumption.
1765
- *
1766
- * Usage tracking is essential for accurate metered billing and provides
1767
- * transparency to customers about their consumption patterns.
1768
- *
1769
- * @example
1770
- * Recording API usage:
1771
- * ```typescript
1772
- * const usageManager = new UsageManager(paymentHandler);
1773
- *
1774
- * // Record a single API call
1775
- * await usageManager.recordUsage({
1776
- * meter_event_name: 'api_calls',
1777
- * customer_id: 'cus_customer123',
1778
- * value: '1'
1779
- * });
1780
- *
1781
- * // Record bulk data transfer
1782
- * await usageManager.recordUsage({
1783
- * meter_event_name: 'data_transfer_gb',
1784
- * customer_id: 'cus_customer123',
1785
- * value: '2.5'
1786
- * });
1787
- * ```
1788
- *
1789
- * @since 1.0.0
1790
- * @public
1791
- * @group Usage
1792
- */
1793
- declare class UsageManager {
1794
- private omnibaseClient;
1795
- /**
1796
- * Initialize the usage manager
1797
- *
1798
- * @param paymentHandler - Payment handler instance for API communication
1799
- *
1800
- * @group Usage
1801
- */
1802
- constructor(omnibaseClient: OmnibaseClient);
1803
- /**
1804
- * Record a usage event for metered billing
1805
- *
1806
- * Records a usage event against a specific meter for billing calculation.
1807
- * The event will be aggregated with other usage events for the billing period
1808
- * to determine the customer's charges for metered products.
1809
- *
1810
- * Usage events should be recorded in real-time or as close to real-time as
1811
- * possible to ensure accurate billing and provide up-to-date usage visibility
1812
- * to customers.
1813
- *
1814
- * @param options - Usage recording options
1815
- * @param options.meter_event_name - Name of the meter to record against
1816
- * @param options.customer_id - Stripe customer ID
1817
- * @param options.value - Usage quantity as string
1818
- *
1819
- * @returns Promise resolving to API response confirmation
1820
- *
1821
- * @throws {Error} When the API request fails due to network issues
1822
- * @throws {Error} When the server returns an error response (invalid meter name, customer, etc.)
1823
- * @throws {ValidationError} When required parameters are missing or invalid
1824
- *
1825
- * @example
1826
- * API call tracking:
1827
- * ```typescript
1828
- * // Record each API call
1829
- * await usageManager.recordUsage({
1830
- * meter_event_name: 'api_requests',
1831
- * customer_id: user.stripeCustomerId,
1832
- * value: '1'
1833
- * });
1834
- * ```
1835
- *
1836
- * @example
1837
- * Batch usage recording:
1838
- * ```typescript
1839
- * // Record multiple operations at once
1840
- * const usageEvents = [
1841
- * { meter_event_name: 'compute_hours', customer_id: 'cus_123', value: '0.5' },
1842
- * { meter_event_name: 'storage_gb', customer_id: 'cus_123', value: '10' },
1843
- * { meter_event_name: 'api_calls', customer_id: 'cus_123', value: '50' }
1844
- * ];
1845
- *
1846
- * for (const event of usageEvents) {
1847
- * await usageManager.recordUsage(event);
1848
- * }
1849
- * ```
1850
- *
1851
- * @example
1852
- * With error handling:
1853
- * ```typescript
1854
- * try {
1855
- * await usageManager.recordUsage({
1856
- * meter_event_name: 'file_uploads',
1857
- * customer_id: currentUser.stripeCustomerId,
1858
- * value: String(uploadedFiles.length)
1859
- * });
1860
- * } catch (error) {
1861
- * console.error('Failed to record usage:', error);
1862
- * // Usage recording failure shouldn't block user operations
1863
- * // but should be logged for billing accuracy
1864
- * }
1865
- * ```
1866
- *
1867
- * @since 1.0.0
1868
- * @group Usage
1869
- */
1870
- recordUsage(options: UsageOptions): Promise<ApiResponse<"">>;
1871
- }
1872
-
1873
- /**
1874
- * Main payment handler for all payment-related operations
1875
- *
1876
- * This class serves as the central coordinator for all payment functionality,
1877
- * providing access to checkout sessions, billing configuration, customer portals,
1878
- * and usage tracking. It handles the low-level HTTP communication with the
1879
- * payment API and delegates specific operations to specialized managers.
1880
- *
1881
- * The handler automatically manages authentication, request formatting, and
1882
- * provides a consistent interface across all payment operations.
1883
- *
1884
- * @example
1885
- * ```typescript
1886
- * const paymentHandler = new PaymentHandler('https://api.example.com');
1887
- *
1888
- * // Create a checkout session
1889
- * const checkout = await paymentHandler.checkout.createSession({
1890
- * price_id: 'price_123',
1891
- * mode: 'subscription',
1892
- * success_url: 'https://app.com/success',
1893
- * cancel_url: 'https://app.com/cancel'
1894
- * });
1895
- *
1896
- * // Get available products
1897
- * const products = await paymentHandler.config.getAvailableProducts();
1898
- * ```
1899
- *
1900
- * @since 1.0.0
1901
- * @public
1902
- * @group Client
1903
- */
1904
- declare class PaymentHandler {
1905
- private omnibaseClient;
1906
- /**
1907
- * Initialize the payment handler with API configuration
1908
- *
1909
- * Creates a new payment handler instance that will communicate with
1910
- * the specified API endpoint. The handler automatically handles
1911
- * request formatting and authentication headers.
1912
- *
1913
- * @param apiUrl - Base URL for the payment API endpoint
1914
- *
1915
- * @example
1916
- * ```typescript
1917
- * const paymentHandler = new PaymentHandler('https://api.myapp.com');
1918
- * ```
1919
- *
1920
- * @since 1.0.0
1921
- * @group Client
1922
- */
1923
- constructor(omnibaseClient: OmnibaseClient);
1924
- /**
1925
- * Checkout session management
1926
- *
1927
- * Provides functionality for creating and managing Stripe checkout sessions
1928
- * for both one-time payments and subscription billing.
1929
- *
1930
- * @example
1931
- * ```typescript
1932
- * const session = await paymentHandler.checkout.createSession({
1933
- * price_id: 'price_monthly',
1934
- * mode: 'subscription',
1935
- * success_url: window.location.origin + '/success',
1936
- * cancel_url: window.location.origin + '/pricing'
1937
- * });
1938
- * ```
1939
- */
1940
- readonly checkout: CheckoutManager;
1941
- /**
1942
- * Stripe configuration management
1943
- *
1944
- * Handles retrieval and processing of database-backed Stripe configurations,
1945
- * providing UI-ready product and pricing data for rendering pricing tables.
1946
- *
1947
- * @example
1948
- * ```typescript
1949
- * const products = await paymentHandler.config.getAvailableProducts();
1950
- * const config = await paymentHandler.config.getStripeConfig();
1951
- * ```
1952
- */
1953
- readonly config: ConfigManager;
1954
- /**
1955
- * Customer portal management
1956
- *
1957
- * Creates customer portal sessions for subscription management,
1958
- * billing history, and payment method updates.
1959
- *
1960
- * @example
1961
- * ```typescript
1962
- * const portal = await paymentHandler.portal.create({
1963
- * customer_id: 'cus_123',
1964
- * return_url: 'https://app.com/billing'
1965
- * });
1966
- * ```
1967
- */
1968
- readonly portal: PortalManager;
1969
- /**
1970
- * Usage tracking and metered billing
1971
- *
1972
- * Records usage events for metered billing products and manages
1973
- * usage-based pricing calculations.
1974
- *
1975
- * @example
1976
- * ```typescript
1977
- * await paymentHandler.usage.recordUsage({
1978
- * meter_event_name: 'api_calls',
1979
- * customer_id: 'cus_123',
1980
- * value: '1'
1981
- * });
1982
- * ```
1983
- */
1984
- readonly usage: UsageManager;
1985
- }
1986
-
1987
- export { type AcceptTenantInviteRequest, type AcceptTenantInviteResponse, ConfigManager as C, type CreateTenantRequest, type CreateTenantResponse, type CreateTenantUserInviteRequest, type CreateTenantUserInviteResponse, type DeleteTenantResponse, PaymentHandler as P, type StripeConfigResponse as S, type SwitchActiveTenantResponse, type Tier as T, type Tenant, TenantHandler, type TenantInvite, TenantInviteManager, TenantManger, type UsageOptions as U, type StripeConfiguration as a, type Product as b, type Price as c, type ProductUI as d, type PriceUI as e, type PriceDisplay as f, type PriceLimit as g, type ProductWithPricingUI as h, type CheckoutOptions as i, type CreateCheckoutResponse as j, CheckoutManager as k, type PortalOptions as l, type CreateCustomerPortalResponse as m, PortalManager as n, UsageManager as o };