@solvapay/next 1.0.0-preview.10

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.
@@ -0,0 +1,406 @@
1
+ import { NextResponse, NextRequest } from 'next/server';
2
+ import * as _solvapay_server from '@solvapay/server';
3
+ import { AuthenticatedUser, SolvaPay } from '@solvapay/server';
4
+ import { AuthAdapter } from '@solvapay/auth';
5
+
6
+ /**
7
+ * Next.js Authentication Helpers
8
+ *
9
+ * Next.js-specific wrappers for authentication helpers.
10
+ */
11
+
12
+ /**
13
+ * Get authenticated user - Next.js wrapper
14
+ *
15
+ * @param request - Next.js request object
16
+ * @param options - Configuration options
17
+ * @returns Authenticated user info or NextResponse error
18
+ */
19
+ declare function getAuthenticatedUser(request: globalThis.Request, options?: {
20
+ includeEmail?: boolean;
21
+ includeName?: boolean;
22
+ }): Promise<AuthenticatedUser | NextResponse>;
23
+
24
+ /**
25
+ * Next.js Customer Helpers
26
+ *
27
+ * Next.js-specific wrappers for customer helpers.
28
+ */
29
+
30
+ /**
31
+ * Sync customer - Next.js wrapper
32
+ *
33
+ * @param request - Next.js request object
34
+ * @param options - Configuration options
35
+ * @returns Customer reference or NextResponse error
36
+ */
37
+ declare function syncCustomer(request: globalThis.Request, options?: {
38
+ solvaPay?: SolvaPay;
39
+ includeEmail?: boolean;
40
+ includeName?: boolean;
41
+ }): Promise<string | NextResponse>;
42
+
43
+ /**
44
+ * Create payment intent - Next.js wrapper
45
+ *
46
+ * @param request - Next.js request object
47
+ * @param body - Payment intent parameters
48
+ * @param options - Configuration options
49
+ * @returns Payment intent response or NextResponse error
50
+ */
51
+ declare function createPaymentIntent(request: globalThis.Request, body: {
52
+ planRef: string;
53
+ agentRef: string;
54
+ }, options?: {
55
+ solvaPay?: SolvaPay;
56
+ includeEmail?: boolean;
57
+ includeName?: boolean;
58
+ }): Promise<{
59
+ id: string;
60
+ clientSecret: string;
61
+ publishableKey: string;
62
+ accountId?: string;
63
+ customerRef: string;
64
+ } | NextResponse>;
65
+ /**
66
+ * Process payment - Next.js wrapper
67
+ *
68
+ * @param request - Next.js request object
69
+ * @param body - Payment processing parameters
70
+ * @param options - Configuration options
71
+ * @returns Process payment result or NextResponse error
72
+ */
73
+ declare function processPayment(request: globalThis.Request, body: {
74
+ paymentIntentId: string;
75
+ agentRef: string;
76
+ planRef?: string;
77
+ }, options?: {
78
+ solvaPay?: SolvaPay;
79
+ }): Promise<_solvapay_server.ProcessPaymentResult | NextResponse>;
80
+
81
+ /**
82
+ * Next.js Checkout Helpers
83
+ *
84
+ * Next.js-specific wrappers for checkout helpers.
85
+ */
86
+
87
+ /**
88
+ * Create checkout session - Next.js wrapper
89
+ *
90
+ * @param request - Next.js request object
91
+ * @param body - Checkout session parameters
92
+ * @param options - Configuration options
93
+ * @returns Checkout session response or NextResponse error
94
+ */
95
+ declare function createCheckoutSession(request: globalThis.Request, body: {
96
+ agentRef: string;
97
+ planRef?: string;
98
+ }, options?: {
99
+ solvaPay?: SolvaPay;
100
+ includeEmail?: boolean;
101
+ includeName?: boolean;
102
+ }): Promise<{
103
+ sessionId: string;
104
+ checkoutUrl: string;
105
+ } | NextResponse>;
106
+ /**
107
+ * Create customer session - Next.js wrapper
108
+ *
109
+ * @param request - Next.js request object
110
+ * @param options - Configuration options
111
+ * @returns Customer session response or NextResponse error
112
+ */
113
+ declare function createCustomerSession(request: globalThis.Request, options?: {
114
+ solvaPay?: SolvaPay;
115
+ includeEmail?: boolean;
116
+ includeName?: boolean;
117
+ }): Promise<{
118
+ sessionId: string;
119
+ customerUrl: string;
120
+ } | NextResponse>;
121
+
122
+ /**
123
+ * Next.js Subscription Helpers
124
+ *
125
+ * Next.js-specific wrappers for subscription helpers.
126
+ */
127
+
128
+ /**
129
+ * Cancel subscription - Next.js wrapper
130
+ *
131
+ * @param request - Next.js request object
132
+ * @param body - Cancellation parameters
133
+ * @param options - Configuration options
134
+ * @returns Cancelled subscription response or NextResponse error
135
+ */
136
+ declare function cancelSubscription(request: globalThis.Request, body: {
137
+ subscriptionRef: string;
138
+ reason?: string;
139
+ }, options?: {
140
+ solvaPay?: SolvaPay;
141
+ }): Promise<any | NextResponse>;
142
+
143
+ /**
144
+ * Next.js Plans Helper
145
+ *
146
+ * Next.js-specific wrapper for plans helper.
147
+ * This is a public route - no authentication required.
148
+ */
149
+
150
+ /**
151
+ * List plans - Next.js wrapper
152
+ *
153
+ * @param request - Next.js request object
154
+ * @returns Plans response or NextResponse error
155
+ */
156
+ declare function listPlans(request: globalThis.Request): Promise<{
157
+ plans: any[];
158
+ agentRef: string;
159
+ } | NextResponse>;
160
+
161
+ /**
162
+ * Next.js Middleware Helpers
163
+ *
164
+ * Helpers for creating authentication middleware in Next.js.
165
+ * Works with any AuthAdapter implementation (Supabase, custom, etc.)
166
+ */
167
+
168
+ /**
169
+ * Configuration options for authentication middleware
170
+ */
171
+ interface AuthMiddlewareOptions {
172
+ /**
173
+ * Auth adapter instance to use for extracting user IDs from requests
174
+ * You can use SupabaseAuthAdapter, MockAuthAdapter, or create your own
175
+ */
176
+ adapter: AuthAdapter;
177
+ /**
178
+ * Public routes that don't require authentication
179
+ * Routes are matched using pathname.startsWith()
180
+ */
181
+ publicRoutes?: string[];
182
+ /**
183
+ * Header name to store the user ID (default: 'x-user-id')
184
+ */
185
+ userIdHeader?: string;
186
+ }
187
+ /**
188
+ * Creates a Next.js middleware function for authentication
189
+ *
190
+ * This helper:
191
+ * 1. Uses the provided AuthAdapter to extract userId from requests
192
+ * 2. Handles public vs protected routes
193
+ * 3. Adds userId to request headers for downstream routes
194
+ * 4. Returns appropriate error responses for auth failures
195
+ *
196
+ * @param options - Configuration options
197
+ * @returns Next.js middleware function
198
+ *
199
+ * @example
200
+ * ```typescript
201
+ * import { createAuthMiddleware } from '@solvapay/next';
202
+ * import { SupabaseAuthAdapter } from '@solvapay/auth/supabase';
203
+ *
204
+ * const adapter = new SupabaseAuthAdapter({
205
+ * jwtSecret: process.env.SUPABASE_JWT_SECRET!,
206
+ * });
207
+ *
208
+ * export const middleware = createAuthMiddleware({
209
+ * adapter,
210
+ * publicRoutes: ['/api/list-plans'],
211
+ * });
212
+ *
213
+ * export const config = {
214
+ * matcher: ['/api/:path*'],
215
+ * };
216
+ * ```
217
+ *
218
+ * @example Custom adapter
219
+ * ```typescript
220
+ * import { createAuthMiddleware } from '@solvapay/next';
221
+ * import type { AuthAdapter } from '@solvapay/auth';
222
+ *
223
+ * const myAdapter: AuthAdapter = {
224
+ * async getUserIdFromRequest(req) {
225
+ * // Your custom auth logic
226
+ * return userId;
227
+ * },
228
+ * };
229
+ *
230
+ * export const middleware = createAuthMiddleware({
231
+ * adapter: myAdapter,
232
+ * });
233
+ * ```
234
+ */
235
+ declare function createAuthMiddleware(options: AuthMiddlewareOptions): (request: NextRequest) => Promise<NextResponse<unknown>>;
236
+ /**
237
+ * Configuration options for Supabase authentication middleware
238
+ */
239
+ interface SupabaseAuthMiddlewareOptions {
240
+ /**
241
+ * Supabase JWT secret (from Supabase dashboard: Settings → API → JWT Secret)
242
+ * If not provided, will use SUPABASE_JWT_SECRET environment variable
243
+ */
244
+ jwtSecret?: string;
245
+ /**
246
+ * Public routes that don't require authentication
247
+ * Routes are matched using pathname.startsWith()
248
+ */
249
+ publicRoutes?: string[];
250
+ /**
251
+ * Header name to store the user ID (default: 'x-user-id')
252
+ */
253
+ userIdHeader?: string;
254
+ }
255
+ /**
256
+ * Creates a Next.js middleware function for Supabase authentication
257
+ *
258
+ * Convenience function that creates a SupabaseAuthAdapter and wraps it with createAuthMiddleware.
259
+ * Only use this if you're using Supabase - otherwise use createAuthMiddleware with your own adapter.
260
+ *
261
+ * Uses dynamic import to avoid requiring Supabase as a dependency in @solvapay/next.
262
+ *
263
+ * @param options - Configuration options
264
+ * @returns Next.js middleware function
265
+ *
266
+ * @example
267
+ * ```typescript
268
+ * import { createSupabaseAuthMiddleware } from '@solvapay/next';
269
+ *
270
+ * export const middleware = createSupabaseAuthMiddleware({
271
+ * publicRoutes: ['/api/list-plans'],
272
+ * });
273
+ *
274
+ * export const config = {
275
+ * matcher: ['/api/:path*'],
276
+ * };
277
+ * ```
278
+ */
279
+ declare function createSupabaseAuthMiddleware(options?: SupabaseAuthMiddlewareOptions): (request: NextRequest) => Promise<NextResponse<unknown>>;
280
+
281
+ /**
282
+ * SolvaPay Next.js SDK
283
+ *
284
+ * Framework-specific helpers and utilities for Next.js API routes.
285
+ * These utilities provide common patterns with built-in optimizations
286
+ * like request deduplication and caching.
287
+ */
288
+
289
+ /**
290
+ * Request deduplication and caching options
291
+ */
292
+ interface RequestDeduplicationOptions {
293
+ /**
294
+ * Time-to-live for cached results in milliseconds (default: 2000)
295
+ * Set to 0 to disable caching (only deduplicate concurrent requests)
296
+ */
297
+ cacheTTL?: number;
298
+ /**
299
+ * Maximum cache size before cleanup (default: 1000)
300
+ * When exceeded, oldest entries are removed
301
+ */
302
+ maxCacheSize?: number;
303
+ /**
304
+ * Whether to cache error results (default: true)
305
+ * When false, only successful results are cached
306
+ */
307
+ cacheErrors?: boolean;
308
+ }
309
+ /**
310
+ * Subscription check result
311
+ */
312
+ interface SubscriptionCheckResult {
313
+ customerRef: string;
314
+ email?: string;
315
+ name?: string;
316
+ subscriptions: Array<{
317
+ reference: string;
318
+ planName?: string;
319
+ agentName?: string;
320
+ status?: string;
321
+ startDate?: string;
322
+ [key: string]: unknown;
323
+ }>;
324
+ }
325
+ /**
326
+ * Options for checking subscriptions
327
+ */
328
+ interface CheckSubscriptionOptions {
329
+ /**
330
+ * Request deduplication options
331
+ * Default: { cacheTTL: 2000, maxCacheSize: 1000, cacheErrors: true }
332
+ */
333
+ deduplication?: RequestDeduplicationOptions;
334
+ /**
335
+ * Custom SolvaPay instance (optional)
336
+ * If not provided, a new instance will be created
337
+ */
338
+ solvaPay?: SolvaPay;
339
+ /**
340
+ * Whether to include user email in customer data
341
+ * Default: true
342
+ */
343
+ includeEmail?: boolean;
344
+ /**
345
+ * Whether to include user name in customer data
346
+ * Default: true
347
+ */
348
+ includeName?: boolean;
349
+ }
350
+ /**
351
+ * Check user subscription status
352
+ *
353
+ * This helper function:
354
+ * 1. Extracts user ID from request (via requireUserId from @solvapay/auth)
355
+ * 2. Gets user email and name from Supabase JWT token
356
+ * 3. Ensures customer exists in SolvaPay
357
+ * 4. Returns customer subscription information
358
+ * 5. Handles deduplication automatically
359
+ *
360
+ * @param request - Next.js request object (NextRequest extends Request, so Request is accepted)
361
+ * @param options - Configuration options
362
+ * @returns Subscription check result or error response
363
+ *
364
+ * @example
365
+ * ```typescript
366
+ * import { NextRequest } from 'next/server';
367
+ * import { checkSubscription } from '@solvapay/next';
368
+ *
369
+ * export async function GET(request: NextRequest) {
370
+ * const result = await checkSubscription(request);
371
+ * if (result instanceof NextResponse) {
372
+ * return result; // Error response
373
+ * }
374
+ * return NextResponse.json(result);
375
+ * }
376
+ * ```
377
+ */
378
+ declare function checkSubscription(request: Request, options?: CheckSubscriptionOptions): Promise<SubscriptionCheckResult | NextResponse>;
379
+ /**
380
+ * Clear subscription cache for a specific user
381
+ *
382
+ * Useful when you know subscription status has changed
383
+ * (e.g., after a successful checkout or subscription update)
384
+ *
385
+ * @param userId - User ID to clear cache for
386
+ */
387
+ declare function clearSubscriptionCache(userId: string): void;
388
+ /**
389
+ * Clear all subscription cache entries
390
+ *
391
+ * Useful for testing or when you need to force fresh lookups
392
+ */
393
+ declare function clearAllSubscriptionCache(): void;
394
+ /**
395
+ * Get subscription cache statistics
396
+ *
397
+ * Useful for monitoring and debugging
398
+ *
399
+ * @returns Cache statistics
400
+ */
401
+ declare function getSubscriptionCacheStats(): {
402
+ inFlight: number;
403
+ cached: number;
404
+ };
405
+
406
+ export { type AuthMiddlewareOptions, type CheckSubscriptionOptions, type RequestDeduplicationOptions, type SubscriptionCheckResult, type SupabaseAuthMiddlewareOptions, cancelSubscription, checkSubscription, clearAllSubscriptionCache, clearSubscriptionCache, createAuthMiddleware, createCheckoutSession, createCustomerSession, createPaymentIntent, createSupabaseAuthMiddleware, getAuthenticatedUser, getSubscriptionCacheStats, listPlans, processPayment, syncCustomer };