@omnibase/core-js 0.4.2 → 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.
package/dist/index.d.cts CHANGED
@@ -1,10 +1,3 @@
1
- /**
2
- * Base API Response structure for API
3
- */
4
- type ApiResponse<T> = {
5
- data?: T;
6
- status: number;
7
- error?: string;
8
- };
9
-
10
- export type { ApiResponse };
1
+ export { i as OmnibaseClient, O as OmnibaseClientConfig } from './payments/index.cjs';
2
+ import './permissions/index.cjs';
3
+ import '@ory/client';
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- export * from "./auth/index";
2
- export * from "./database/index";
3
- export * from "./tenants/index";
1
+ export { i as OmnibaseClient, O as OmnibaseClientConfig } from './payments/index.js';
2
+ import './permissions/index.js';
3
+ import '@ory/client';
package/dist/index.js CHANGED
@@ -0,0 +1,51 @@
1
+ import {
2
+ PermissionsClient
3
+ } from "./chunk-DDFBRGMG.js";
4
+ import {
5
+ TenantHandler
6
+ } from "./chunk-LIS5WD3H.js";
7
+ import {
8
+ PaymentHandler
9
+ } from "./chunk-767PUXYD.js";
10
+
11
+ // src/client.ts
12
+ var OmnibaseClient = class {
13
+ constructor(config) {
14
+ this.config = config;
15
+ this.permissions = new PermissionsClient(this.config.api_url);
16
+ }
17
+ /**
18
+ * Main payment handler for all payment-related operations
19
+ *
20
+ * This class serves as the central coordinator for all payment functionality,
21
+ * providing access to checkout sessions, billing configuration, customer portals,
22
+ * and usage tracking. It handles the low-level HTTP communication with the
23
+ * payment API and delegates specific operations to specialized managers.
24
+ *
25
+ * The handler automatically manages authentication, request formatting, and
26
+ * provides a consistent interface across all payment operations.
27
+ *
28
+ * @example
29
+ * ```typescript
30
+ * // Create a checkout session
31
+ * const checkout = await omnibase.payments.checkout.createSession({
32
+ * price_id: 'price_123',
33
+ * mode: 'subscription',
34
+ * success_url: 'https://app.com/success',
35
+ * cancel_url: 'https://app.com/cancel'
36
+ * });
37
+ *
38
+ * // Get available products
39
+ * const products = await omnibase.payments.config.getAvailableProducts();
40
+ * ```
41
+ */
42
+ payments = new PaymentHandler(this);
43
+ tenants = new TenantHandler(this);
44
+ permissions;
45
+ async fetch(endpoint, options = {}) {
46
+ return await fetch(this.config.api_url + endpoint, options);
47
+ }
48
+ };
49
+ export {
50
+ OmnibaseClient
51
+ };
@@ -20,62 +20,218 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/payments/index.ts
21
21
  var payments_exports = {};
22
22
  __export(payments_exports, {
23
- createCheckout: () => createCheckout,
24
- createCustomerPortal: () => createCustomerPortal,
25
- getAvailableProducts: () => getAvailableProducts,
26
- getProduct: () => getProduct,
27
- getStripeConfig: () => getStripeConfig,
28
- recordUsage: () => recordUsage
23
+ CheckoutManager: () => CheckoutManager,
24
+ ConfigManager: () => ConfigManager,
25
+ PaymentHandler: () => PaymentHandler,
26
+ PortalManager: () => PortalManager,
27
+ UsageManager: () => UsageManager
29
28
  });
30
29
  module.exports = __toCommonJS(payments_exports);
31
30
 
32
- // src/payments/config.ts
33
- async function getStripeConfig() {
34
- const baseUrl = process.env.OMNIBASE_API_URL;
35
- if (!baseUrl) {
36
- throw new Error("OMNIBASE_API_URL is not configured");
37
- }
38
- try {
39
- const response = await fetch(`${baseUrl}/api/v1/stripe/config`, {
40
- method: "GET",
41
- headers: {
42
- "Content-Type": "application/json"
43
- },
44
- credentials: "include"
45
- });
31
+ // src/payments/checkout.ts
32
+ var CheckoutManager = class {
33
+ /**
34
+ * Initialize the checkout manager
35
+ *
36
+ * @param paymentHandler - Payment handler instance for API communication
37
+ *
38
+ * @group Checkout
39
+ */
40
+ constructor(omnibaseClient) {
41
+ this.omnibaseClient = omnibaseClient;
42
+ }
43
+ /**
44
+ * Create a new Stripe checkout session
45
+ *
46
+ * Creates a checkout session with the specified options and returns
47
+ * the session URL for redirecting the user to complete payment.
48
+ * The session will be configured for either one-time payment or
49
+ * subscription based on the mode parameter.
50
+ *
51
+ * @param options - Configuration options for the checkout session
52
+ * @param options.price_id - Stripe price ID for the product/service
53
+ * @param options.mode - Payment mode ('payment' for one-time, 'subscription' for recurring)
54
+ * @param options.success_url - URL to redirect after successful payment
55
+ * @param options.cancel_url - URL to redirect if user cancels
56
+ * @param options.customer_id - Optional existing Stripe customer ID
57
+ *
58
+ * @returns Promise resolving to checkout session response with URL and session ID
59
+ *
60
+ * @throws {Error} When the API request fails due to network issues
61
+ * @throws {Error} When the server returns an error response (invalid price_id, etc.)
62
+ * @throws {ValidationError} When required parameters are missing or invalid
63
+ *
64
+ * @example
65
+ * One-time payment checkout:
66
+ * ```typescript
67
+ * const session = await checkoutManager.createSession({
68
+ * price_id: 'price_one_time_product',
69
+ * mode: 'payment',
70
+ * success_url: 'https://app.com/success',
71
+ * cancel_url: 'https://app.com/cancel'
72
+ * });
73
+ *
74
+ * // Redirect to Stripe checkout
75
+ * window.location.href = session.data.url;
76
+ * ```
77
+ *
78
+ * @example
79
+ * Subscription checkout with existing customer:
80
+ * ```typescript
81
+ * const session = await checkoutManager.createSession({
82
+ * price_id: 'price_monthly_plan',
83
+ * mode: 'subscription',
84
+ * success_url: 'https://app.com/dashboard?welcome=true',
85
+ * cancel_url: 'https://app.com/pricing',
86
+ * customer_id: 'cus_12345'
87
+ * });
88
+ *
89
+ * console.log(`Session created: ${session.data.sessionId}`);
90
+ * ```
91
+ *
92
+ * @since 1.0.0
93
+ * @group Checkout
94
+ */
95
+ async createSession(options) {
96
+ const response = await this.omnibaseClient.fetch(
97
+ "/api/v1/payments/checkout",
98
+ {
99
+ method: "POST",
100
+ headers: {
101
+ "Content-Type": "application/json"
102
+ },
103
+ body: JSON.stringify(options)
104
+ }
105
+ );
46
106
  if (!response.ok) {
47
107
  const errorData = await response.text();
48
108
  throw new Error(
49
- `Failed to get Stripe config: ${response.status} - ${errorData}`
109
+ `Failed to create checkout session: ${response.status} - ${errorData}`
50
110
  );
51
111
  }
52
- const data = await response.json();
53
- return data;
54
- } catch (error) {
55
- console.error("Error getting Stripe config:", error);
56
- throw error;
112
+ const result = await response.json();
113
+ return result;
57
114
  }
58
- }
59
- async function getAvailableProducts() {
60
- const configResponse = await getStripeConfig();
61
- if (!configResponse.data?.config) {
62
- throw new Error("No Stripe configuration found");
63
- }
64
- const products = configResponse.data.config.products;
65
- return products.map(transformProductToUIReady).sort(
66
- (a, b) => a.pricing_display.sort_order - b.pricing_display.sort_order
67
- );
68
- }
69
- async function getProduct(productId) {
70
- const configResponse = await getStripeConfig();
71
- if (!configResponse.data?.config) {
72
- return null;
73
- }
74
- const product = configResponse.data.config.products.find(
75
- (p) => p.id === productId
76
- );
77
- return product || null;
78
- }
115
+ };
116
+
117
+ // src/payments/config.ts
118
+ var ConfigManager = class {
119
+ constructor(omnibaseClient) {
120
+ this.omnibaseClient = omnibaseClient;
121
+ }
122
+ /**
123
+ * Get the current Stripe configuration from the database
124
+ *
125
+ * Retrieves the latest Stripe configuration including products, prices,
126
+ * and UI customization data. This configuration represents the current
127
+ * active pricing structure with all UI elements for pricing table rendering.
128
+ *
129
+ * @returns Promise resolving to the current Stripe configuration
130
+ *
131
+ * @throws {Error} When the API request fails due to network issues
132
+ * @throws {Error} When the server returns an error response (4xx, 5xx status codes)
133
+ *
134
+ * @example
135
+ * Basic usage:
136
+ * ```typescript
137
+ * const config = await getStripeConfig();
138
+ * console.log(`Found ${config.data.config.products.length} products`);
139
+ *
140
+ * // Access product UI configuration
141
+ * config.data.config.products.forEach(product => {
142
+ * console.log(`${product.name}: ${product.ui?.tagline || 'No tagline'}`);
143
+ * });
144
+ * ```
145
+ */
146
+ async getStripeConfig() {
147
+ try {
148
+ const response = await this.omnibaseClient.fetch(
149
+ `/api/v1/stripe/config`,
150
+ {
151
+ method: "GET",
152
+ headers: {
153
+ "Content-Type": "application/json"
154
+ },
155
+ credentials: "include"
156
+ }
157
+ );
158
+ if (!response.ok) {
159
+ const errorData = await response.text();
160
+ throw new Error(
161
+ `Failed to get Stripe config: ${response.status} - ${errorData}`
162
+ );
163
+ }
164
+ const data = await response.json();
165
+ return data;
166
+ } catch (error) {
167
+ console.error("Error getting Stripe config:", error);
168
+ throw error;
169
+ }
170
+ }
171
+ /**
172
+ * Get available products with UI-ready pricing data
173
+ *
174
+ * Transforms the raw Stripe configuration into UI-ready format for pricing
175
+ * table rendering. Includes formatted pricing, features, limits, and all
176
+ * display customizations needed for marketing pages.
177
+ *
178
+ * @returns Promise resolving to products ready for UI consumption
179
+ *
180
+ * @throws {Error} When the API request fails or configuration is invalid
181
+ *
182
+ * @example
183
+ * Pricing table rendering:
184
+ * ```typescript
185
+ * const products = await getAvailableProducts();
186
+ *
187
+ * products.forEach(product => {
188
+ * const display = product.pricing_display;
189
+ * console.log(`${display.name} - ${display.tagline}`);
190
+ *
191
+ * display.prices.forEach(price => {
192
+ * console.log(` ${price.display_name}: ${price.formatted_price}`);
193
+ * });
194
+ * });
195
+ * ```
196
+ */
197
+ async getAvailableProducts() {
198
+ const configResponse = await this.getStripeConfig();
199
+ if (!configResponse.data?.config) {
200
+ throw new Error("No Stripe configuration found");
201
+ }
202
+ const products = configResponse.data.config.products;
203
+ return products.map(transformProductToUIReady).sort(
204
+ (a, b) => a.pricing_display.sort_order - b.pricing_display.sort_order
205
+ );
206
+ }
207
+ /**
208
+ * Get a specific product by ID
209
+ *
210
+ * Retrieves a single product configuration by its ID from the current
211
+ * Stripe configuration. Useful for product-specific operations.
212
+ *
213
+ * @param productId - The configuration product ID to retrieve
214
+ * @returns Promise resolving to the product or null if not found
215
+ *
216
+ * @example
217
+ * ```typescript
218
+ * const product = await getProduct('starter_plan');
219
+ * if (product) {
220
+ * console.log(`Found product: ${product.name}`);
221
+ * }
222
+ * ```
223
+ */
224
+ async getProduct(productId) {
225
+ const configResponse = await this.getStripeConfig();
226
+ if (!configResponse.data?.config) {
227
+ return null;
228
+ }
229
+ const product = configResponse.data.config.products.find(
230
+ (p) => p.id === productId
231
+ );
232
+ return product || null;
233
+ }
234
+ };
79
235
  function transformProductToUIReady(product) {
80
236
  const ui = product.ui || {};
81
237
  return {
@@ -149,47 +305,282 @@ function formatDefaultBillingPeriod(price) {
149
305
  return "one-time";
150
306
  }
151
307
 
152
- // src/payments/checkout.ts
153
- var API_URL = process.env.OMNIBASE_API_URL;
154
- if (!API_URL) throw new Error("must set OMNIBASE_API_URL in env variables");
155
- var createCheckout = async (options) => {
156
- const response = await fetch(API_URL + "/api/v1/payments/checkout", {
157
- method: "POST",
158
- body: JSON.stringify(options)
159
- });
160
- const result = await response.json();
161
- return result;
162
- };
163
-
164
308
  // src/payments/portal.ts
165
- var API_URL2 = process.env.OMNIBASE_API_URL;
166
- if (!API_URL2) throw new Error("must set OMNIBASE_API_URL in env variables");
167
- var createCustomerPortal = async (options) => {
168
- const response = await fetch(API_URL2 + "/api/v1/payments/portal", {
169
- method: "POST",
170
- body: JSON.stringify(options)
171
- });
172
- const result = await response.json();
173
- return result;
309
+ var PortalManager = class {
310
+ /**
311
+ * Initialize the portal manager
312
+ *
313
+ * @param paymentHandler - Payment handler instance for API communication
314
+ *
315
+ * @group Portal
316
+ */
317
+ constructor(omnibaseClient) {
318
+ this.omnibaseClient = omnibaseClient;
319
+ }
320
+ /**
321
+ * Create a new customer portal session
322
+ *
323
+ * Creates a portal session that allows the specified customer to
324
+ * manage their billing information, subscriptions, and payment methods.
325
+ * Returns a URL that the customer should be redirected to.
326
+ *
327
+ * The portal session is temporary and expires after a short period
328
+ * for security. Each access requires creating a new session.
329
+ *
330
+ * @param options - Configuration options for the portal session
331
+ * @param options.customer_id - Stripe customer ID for the user
332
+ * @param options.return_url - URL to redirect to when exiting the portal
333
+ *
334
+ * @returns Promise resolving to portal session response with access URL
335
+ *
336
+ * @throws {Error} When the API request fails due to network issues
337
+ * @throws {Error} When the server returns an error response (invalid customer_id, etc.)
338
+ * @throws {ValidationError} When required parameters are missing or invalid
339
+ *
340
+ * @example
341
+ * Basic portal creation:
342
+ * ```typescript
343
+ * const portal = await portalManager.create({
344
+ * customer_id: 'cus_abc123',
345
+ * return_url: 'https://myapp.com/account/billing'
346
+ * });
347
+ *
348
+ * // Redirect user to portal
349
+ * window.location.href = portal.data.url;
350
+ * ```
351
+ *
352
+ * @example
353
+ * With error handling:
354
+ * ```typescript
355
+ * try {
356
+ * const portal = await portalManager.create({
357
+ * customer_id: currentUser.stripeCustomerId,
358
+ * return_url: window.location.origin + '/billing'
359
+ * });
360
+ *
361
+ * window.location.href = portal.data.url;
362
+ * } catch (error) {
363
+ * console.error('Failed to create portal session:', error);
364
+ * showErrorMessage('Unable to access billing portal. Please try again.');
365
+ * }
366
+ * ```
367
+ *
368
+ * @since 1.0.0
369
+ * @group Portal
370
+ */
371
+ async create(options) {
372
+ const response = await this.omnibaseClient.fetch(
373
+ "/api/v1/payments/portal",
374
+ {
375
+ method: "POST",
376
+ headers: {
377
+ "Content-Type": "application/json"
378
+ },
379
+ body: JSON.stringify(options)
380
+ }
381
+ );
382
+ if (!response.ok) {
383
+ const errorData = await response.text();
384
+ throw new Error(
385
+ `Failed to create customer portal: ${response.status} - ${errorData}`
386
+ );
387
+ }
388
+ const result = await response.json();
389
+ return result;
390
+ }
174
391
  };
175
392
 
176
393
  // src/payments/usage.ts
177
- var API_URL3 = process.env.OMNIBASE_API_URL;
178
- if (!API_URL3) throw new Error("must set OMNIBASE_API_URL in env variables");
179
- var recordUsage = async (options) => {
180
- const response = await fetch(API_URL3 + "/api/v1/payments/usage", {
181
- method: "POST",
182
- body: JSON.stringify(options)
183
- });
184
- const result = await response.json();
185
- return result;
394
+ var UsageManager = class {
395
+ /**
396
+ * Initialize the usage manager
397
+ *
398
+ * @param paymentHandler - Payment handler instance for API communication
399
+ *
400
+ * @group Usage
401
+ */
402
+ constructor(omnibaseClient) {
403
+ this.omnibaseClient = omnibaseClient;
404
+ }
405
+ /**
406
+ * Record a usage event for metered billing
407
+ *
408
+ * Records a usage event against a specific meter for billing calculation.
409
+ * The event will be aggregated with other usage events for the billing period
410
+ * to determine the customer's charges for metered products.
411
+ *
412
+ * Usage events should be recorded in real-time or as close to real-time as
413
+ * possible to ensure accurate billing and provide up-to-date usage visibility
414
+ * to customers.
415
+ *
416
+ * @param options - Usage recording options
417
+ * @param options.meter_event_name - Name of the meter to record against
418
+ * @param options.customer_id - Stripe customer ID
419
+ * @param options.value - Usage quantity as string
420
+ *
421
+ * @returns Promise resolving to API response confirmation
422
+ *
423
+ * @throws {Error} When the API request fails due to network issues
424
+ * @throws {Error} When the server returns an error response (invalid meter name, customer, etc.)
425
+ * @throws {ValidationError} When required parameters are missing or invalid
426
+ *
427
+ * @example
428
+ * API call tracking:
429
+ * ```typescript
430
+ * // Record each API call
431
+ * await usageManager.recordUsage({
432
+ * meter_event_name: 'api_requests',
433
+ * customer_id: user.stripeCustomerId,
434
+ * value: '1'
435
+ * });
436
+ * ```
437
+ *
438
+ * @example
439
+ * Batch usage recording:
440
+ * ```typescript
441
+ * // Record multiple operations at once
442
+ * const usageEvents = [
443
+ * { meter_event_name: 'compute_hours', customer_id: 'cus_123', value: '0.5' },
444
+ * { meter_event_name: 'storage_gb', customer_id: 'cus_123', value: '10' },
445
+ * { meter_event_name: 'api_calls', customer_id: 'cus_123', value: '50' }
446
+ * ];
447
+ *
448
+ * for (const event of usageEvents) {
449
+ * await usageManager.recordUsage(event);
450
+ * }
451
+ * ```
452
+ *
453
+ * @example
454
+ * With error handling:
455
+ * ```typescript
456
+ * try {
457
+ * await usageManager.recordUsage({
458
+ * meter_event_name: 'file_uploads',
459
+ * customer_id: currentUser.stripeCustomerId,
460
+ * value: String(uploadedFiles.length)
461
+ * });
462
+ * } catch (error) {
463
+ * console.error('Failed to record usage:', error);
464
+ * // Usage recording failure shouldn't block user operations
465
+ * // but should be logged for billing accuracy
466
+ * }
467
+ * ```
468
+ *
469
+ * @since 1.0.0
470
+ * @group Usage
471
+ */
472
+ async recordUsage(options) {
473
+ const response = await this.omnibaseClient.fetch("/api/v1/payments/usage", {
474
+ method: "POST",
475
+ headers: {
476
+ "Content-Type": "application/json"
477
+ },
478
+ body: JSON.stringify(options)
479
+ });
480
+ if (!response.ok) {
481
+ const errorData = await response.text();
482
+ throw new Error(
483
+ `Failed to record usage: ${response.status} - ${errorData}`
484
+ );
485
+ }
486
+ const result = await response.json();
487
+ return result;
488
+ }
489
+ };
490
+
491
+ // src/payments/handler.ts
492
+ var PaymentHandler = class {
493
+ /**
494
+ * Initialize the payment handler with API configuration
495
+ *
496
+ * Creates a new payment handler instance that will communicate with
497
+ * the specified API endpoint. The handler automatically handles
498
+ * request formatting and authentication headers.
499
+ *
500
+ * @param apiUrl - Base URL for the payment API endpoint
501
+ *
502
+ * @example
503
+ * ```typescript
504
+ * const paymentHandler = new PaymentHandler('https://api.myapp.com');
505
+ * ```
506
+ *
507
+ * @since 1.0.0
508
+ * @group Client
509
+ */
510
+ constructor(omnibaseClient) {
511
+ this.omnibaseClient = omnibaseClient;
512
+ this.checkout = new CheckoutManager(this.omnibaseClient);
513
+ this.config = new ConfigManager(this.omnibaseClient);
514
+ this.portal = new PortalManager(this.omnibaseClient);
515
+ this.usage = new UsageManager(this.omnibaseClient);
516
+ }
517
+ /**
518
+ * Checkout session management
519
+ *
520
+ * Provides functionality for creating and managing Stripe checkout sessions
521
+ * for both one-time payments and subscription billing.
522
+ *
523
+ * @example
524
+ * ```typescript
525
+ * const session = await paymentHandler.checkout.createSession({
526
+ * price_id: 'price_monthly',
527
+ * mode: 'subscription',
528
+ * success_url: window.location.origin + '/success',
529
+ * cancel_url: window.location.origin + '/pricing'
530
+ * });
531
+ * ```
532
+ */
533
+ checkout;
534
+ /**
535
+ * Stripe configuration management
536
+ *
537
+ * Handles retrieval and processing of database-backed Stripe configurations,
538
+ * providing UI-ready product and pricing data for rendering pricing tables.
539
+ *
540
+ * @example
541
+ * ```typescript
542
+ * const products = await paymentHandler.config.getAvailableProducts();
543
+ * const config = await paymentHandler.config.getStripeConfig();
544
+ * ```
545
+ */
546
+ config;
547
+ /**
548
+ * Customer portal management
549
+ *
550
+ * Creates customer portal sessions for subscription management,
551
+ * billing history, and payment method updates.
552
+ *
553
+ * @example
554
+ * ```typescript
555
+ * const portal = await paymentHandler.portal.create({
556
+ * customer_id: 'cus_123',
557
+ * return_url: 'https://app.com/billing'
558
+ * });
559
+ * ```
560
+ */
561
+ portal;
562
+ /**
563
+ * Usage tracking and metered billing
564
+ *
565
+ * Records usage events for metered billing products and manages
566
+ * usage-based pricing calculations.
567
+ *
568
+ * @example
569
+ * ```typescript
570
+ * await paymentHandler.usage.recordUsage({
571
+ * meter_event_name: 'api_calls',
572
+ * customer_id: 'cus_123',
573
+ * value: '1'
574
+ * });
575
+ * ```
576
+ */
577
+ usage;
186
578
  };
187
579
  // Annotate the CommonJS export names for ESM import in node:
188
580
  0 && (module.exports = {
189
- createCheckout,
190
- createCustomerPortal,
191
- getAvailableProducts,
192
- getProduct,
193
- getStripeConfig,
194
- recordUsage
581
+ CheckoutManager,
582
+ ConfigManager,
583
+ PaymentHandler,
584
+ PortalManager,
585
+ UsageManager
195
586
  });