@paid-ai/paid-node 0.4.0 → 0.5.0-alpha1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/dist/cjs/Client.js +2 -2
  2. package/dist/cjs/api/types/Signal.d.ts +5 -0
  3. package/dist/cjs/index.d.ts +1 -0
  4. package/dist/cjs/index.js +2 -1
  5. package/dist/cjs/integrations/adapters/nextjs/base-adapter.d.ts +10 -0
  6. package/dist/cjs/integrations/adapters/nextjs/base-adapter.js +58 -0
  7. package/dist/cjs/integrations/adapters/nextjs/index.d.ts +5 -0
  8. package/dist/cjs/integrations/adapters/nextjs/index.js +15 -0
  9. package/dist/cjs/integrations/adapters/nextjs/routes.d.ts +174 -0
  10. package/dist/cjs/integrations/adapters/nextjs/routes.js +192 -0
  11. package/dist/cjs/integrations/client.d.ts +49 -0
  12. package/dist/cjs/integrations/client.js +93 -0
  13. package/dist/cjs/integrations/controllers/billing.d.ts +113 -0
  14. package/dist/cjs/integrations/controllers/billing.js +164 -0
  15. package/dist/cjs/integrations/controllers/contacts.d.ts +66 -0
  16. package/dist/cjs/integrations/controllers/contacts.js +145 -0
  17. package/dist/cjs/integrations/controllers/customers.d.ts +63 -0
  18. package/dist/cjs/integrations/controllers/customers.js +150 -0
  19. package/dist/cjs/integrations/controllers/index.d.ts +6 -0
  20. package/dist/cjs/integrations/controllers/index.js +26 -0
  21. package/dist/cjs/integrations/controllers/invoices.d.ts +40 -0
  22. package/dist/cjs/integrations/controllers/invoices.js +72 -0
  23. package/dist/cjs/integrations/controllers/orders.d.ts +72 -0
  24. package/dist/cjs/integrations/controllers/orders.js +194 -0
  25. package/dist/cjs/integrations/controllers/provision-users.d.ts +62 -0
  26. package/dist/cjs/integrations/controllers/provision-users.js +130 -0
  27. package/dist/cjs/integrations/index.d.ts +29 -0
  28. package/dist/cjs/integrations/index.js +44 -0
  29. package/dist/cjs/integrations/types.d.ts +119 -0
  30. package/dist/cjs/integrations/types.js +2 -0
  31. package/dist/cjs/integrations/utils/api-fetch.d.ts +18 -0
  32. package/dist/cjs/integrations/utils/api-fetch.js +53 -0
  33. package/dist/cjs/integrations/utils/base-handler.d.ts +79 -0
  34. package/dist/cjs/integrations/utils/base-handler.js +168 -0
  35. package/dist/cjs/integrations/utils/create-adapter.d.ts +29 -0
  36. package/dist/cjs/integrations/utils/create-adapter.js +56 -0
  37. package/dist/cjs/version.d.ts +1 -1
  38. package/dist/cjs/version.js +1 -1
  39. package/dist/esm/Client.mjs +2 -2
  40. package/dist/esm/api/types/Signal.d.mts +5 -0
  41. package/dist/esm/index.d.mts +1 -0
  42. package/dist/esm/index.mjs +1 -0
  43. package/dist/esm/integrations/adapters/nextjs/base-adapter.d.mts +10 -0
  44. package/dist/esm/integrations/adapters/nextjs/base-adapter.mjs +55 -0
  45. package/dist/esm/integrations/adapters/nextjs/index.d.mts +5 -0
  46. package/dist/esm/integrations/adapters/nextjs/index.mjs +5 -0
  47. package/dist/esm/integrations/adapters/nextjs/routes.d.mts +174 -0
  48. package/dist/esm/integrations/adapters/nextjs/routes.mjs +183 -0
  49. package/dist/esm/integrations/client.d.mts +49 -0
  50. package/dist/esm/integrations/client.mjs +89 -0
  51. package/dist/esm/integrations/controllers/billing.d.mts +113 -0
  52. package/dist/esm/integrations/controllers/billing.mjs +158 -0
  53. package/dist/esm/integrations/controllers/contacts.d.mts +66 -0
  54. package/dist/esm/integrations/controllers/contacts.mjs +140 -0
  55. package/dist/esm/integrations/controllers/customers.d.mts +63 -0
  56. package/dist/esm/integrations/controllers/customers.mjs +145 -0
  57. package/dist/esm/integrations/controllers/index.d.mts +6 -0
  58. package/dist/esm/integrations/controllers/index.mjs +6 -0
  59. package/dist/esm/integrations/controllers/invoices.d.mts +40 -0
  60. package/dist/esm/integrations/controllers/invoices.mjs +68 -0
  61. package/dist/esm/integrations/controllers/orders.d.mts +72 -0
  62. package/dist/esm/integrations/controllers/orders.mjs +189 -0
  63. package/dist/esm/integrations/controllers/provision-users.d.mts +62 -0
  64. package/dist/esm/integrations/controllers/provision-users.mjs +126 -0
  65. package/dist/esm/integrations/index.d.mts +29 -0
  66. package/dist/esm/integrations/index.mjs +28 -0
  67. package/dist/esm/integrations/types.d.mts +119 -0
  68. package/dist/esm/integrations/types.mjs +1 -0
  69. package/dist/esm/integrations/utils/api-fetch.d.mts +18 -0
  70. package/dist/esm/integrations/utils/api-fetch.mjs +50 -0
  71. package/dist/esm/integrations/utils/base-handler.d.mts +79 -0
  72. package/dist/esm/integrations/utils/base-handler.mjs +164 -0
  73. package/dist/esm/integrations/utils/create-adapter.d.mts +29 -0
  74. package/dist/esm/integrations/utils/create-adapter.mjs +53 -0
  75. package/dist/esm/version.d.mts +1 -1
  76. package/dist/esm/version.mjs +1 -1
  77. package/package.json +32 -3
@@ -0,0 +1,130 @@
1
+ "use strict";
2
+ /**
3
+ * Provisioning helpers for Paid SDK
4
+ * Orchestrates customer + contact + order creation in one operation
5
+ */
6
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
7
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
8
+ return new (P || (P = Promise))(function (resolve, reject) {
9
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
10
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
12
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
13
+ });
14
+ };
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.provisionNewUser = provisionNewUser;
17
+ exports.createProvisioningHandler = createProvisioningHandler;
18
+ const customers_js_1 = require("./customers.js");
19
+ const contacts_js_1 = require("./contacts.js");
20
+ const orders_js_1 = require("./orders.js");
21
+ const base_handler_js_1 = require("../utils/base-handler.js");
22
+ /**
23
+ * Provision a new user with customer, contact, and optionally order
24
+ *
25
+ * This is a high-level helper that orchestrates the creation of all
26
+ * necessary Paid entities for a new user in one operation.
27
+ *
28
+ * @param client - PaidClient instance
29
+ * @param config - Provisioning configuration
30
+ * @returns Result with created customer, contact, and optional order
31
+ *
32
+ * @example
33
+ * ```typescript
34
+ * const result = await provisionNewUser(client, {
35
+ * customer: {
36
+ * externalId: 'user-123',
37
+ * email: 'user@example.com'
38
+ * },
39
+ * agentExternalId: 'agent-prod'
40
+ * });
41
+ * // Creates customer, contact, and order with defaults
42
+ * ```
43
+ */
44
+ function provisionNewUser(client, config) {
45
+ return __awaiter(this, void 0, void 0, function* () {
46
+ var _a, _b, _c, _d, _e, _f;
47
+ const customer = yield (0, customers_js_1.createCustomerWithDefaults)(client, config.customer);
48
+ const contactData = {
49
+ customerExternalId: config.customer.externalId,
50
+ email: ((_a = config.contact) === null || _a === void 0 ? void 0 : _a.email) || config.customer.email,
51
+ firstName: (_b = config.contact) === null || _b === void 0 ? void 0 : _b.firstName,
52
+ lastName: (_c = config.contact) === null || _c === void 0 ? void 0 : _c.lastName,
53
+ phone: (_d = config.contact) === null || _d === void 0 ? void 0 : _d.phone,
54
+ billingAddress: (_e = config.contact) === null || _e === void 0 ? void 0 : _e.billingAddress,
55
+ salutation: (_f = config.contact) === null || _f === void 0 ? void 0 : _f.salutation,
56
+ };
57
+ const contact = yield (0, contacts_js_1.createContactWithDefaults)(client, contactData);
58
+ let order;
59
+ if (config.agentExternalId) {
60
+ order = yield (0, orders_js_1.createOrderWithDefaults)(client, {
61
+ customerId: customer.id,
62
+ customerExternalId: config.customer.externalId,
63
+ agentExternalId: config.agentExternalId,
64
+ billingContactId: contact.id,
65
+ }, config.orderOptions);
66
+ }
67
+ return {
68
+ customer,
69
+ contact,
70
+ order,
71
+ };
72
+ });
73
+ }
74
+ /**
75
+ * Create a framework-agnostic handler for user provisioning
76
+ *
77
+ * This handler can be used with any framework adapter.
78
+ * Accepts partial provisioning configuration and fills in defaults for missing fields.
79
+ *
80
+ * @param orderOptions - Optional default order creation options
81
+ * @param defaultAgentExternalId - Optional default agent external ID
82
+ * @returns Handler function
83
+ *
84
+ * @example
85
+ * ```typescript
86
+ * // Minimal - just externalId and email
87
+ * {
88
+ * customer: { externalId: 'org-123', email: 'user@example.com' }
89
+ * }
90
+ *
91
+ * // With full customer data
92
+ * {
93
+ * customer: {
94
+ * externalId: 'org-123',
95
+ * email: 'user@example.com',
96
+ * name: 'Acme Corp',
97
+ * billingAddress: { line1: '123 Main St', city: 'NYC', ... }
98
+ * },
99
+ * contact: {
100
+ * firstName: 'John',
101
+ * lastName: 'Doe'
102
+ * }
103
+ * }
104
+ * ```
105
+ */
106
+ function createProvisioningHandler(orderOptions, defaultAgentExternalId) {
107
+ return (0, base_handler_js_1.createHandler)((client, body) => __awaiter(this, void 0, void 0, function* () {
108
+ if (!body.customer) {
109
+ return {
110
+ success: false,
111
+ error: "'customer' is required",
112
+ status: 400,
113
+ };
114
+ }
115
+ const effectiveAgentId = body.agentExternalId ||
116
+ defaultAgentExternalId ||
117
+ process.env.NEXT_PUBLIC_PAID_AGENT_ID ||
118
+ process.env.PAID_AGENT_ID;
119
+ const result = yield provisionNewUser(client, {
120
+ customer: body.customer,
121
+ contact: body.contact,
122
+ agentExternalId: effectiveAgentId,
123
+ orderOptions: body.orderOptions || orderOptions,
124
+ });
125
+ return {
126
+ success: true,
127
+ data: result,
128
+ };
129
+ }), { requiredFields: [] });
130
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Paid SDK Integrations
3
+ *
4
+ * This module provides simplified helpers for common Paid operations
5
+ * with defaults and reduced boilerplate.
6
+ *
7
+ * @module integrations
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * import { PaidClient } from '@paid-ai/paid-node';
12
+ * import { createCustomerWithDefaults, createOrderWithDefaults } from '@paid-ai/paid-node/integrations';
13
+ *
14
+ * const client = new PaidClient({ token: 'pk_xxx' });
15
+ *
16
+ * const customer = await createCustomerWithDefaults(client, {
17
+ * externalId: 'user-123',
18
+ * email: 'user@example.com'
19
+ * });
20
+ *
21
+ * const order = await createOrderWithDefaults(client, {
22
+ * customerId: customer.id,
23
+ * customerExternalId: 'user-123',
24
+ * agentExternalId: 'agent-prod'
25
+ * });
26
+ * ```
27
+ */
28
+ export * from "./controllers/index.js";
29
+ export type { Address, CustomerData, CompleteCustomerData, ContactData, OrderConfig, CompleteOrderConfig, OrderLineConfig, OrderOptions as HelperOptions, CustomerCreationResult, ContactCreationResult, OrderCreationResult, ProvisioningConfig, ProvisioningResult, } from "./types.js";
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ /**
3
+ * Paid SDK Integrations
4
+ *
5
+ * This module provides simplified helpers for common Paid operations
6
+ * with defaults and reduced boilerplate.
7
+ *
8
+ * @module integrations
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * import { PaidClient } from '@paid-ai/paid-node';
13
+ * import { createCustomerWithDefaults, createOrderWithDefaults } from '@paid-ai/paid-node/integrations';
14
+ *
15
+ * const client = new PaidClient({ token: 'pk_xxx' });
16
+ *
17
+ * const customer = await createCustomerWithDefaults(client, {
18
+ * externalId: 'user-123',
19
+ * email: 'user@example.com'
20
+ * });
21
+ *
22
+ * const order = await createOrderWithDefaults(client, {
23
+ * customerId: customer.id,
24
+ * customerExternalId: 'user-123',
25
+ * agentExternalId: 'agent-prod'
26
+ * });
27
+ * ```
28
+ */
29
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
30
+ if (k2 === undefined) k2 = k;
31
+ var desc = Object.getOwnPropertyDescriptor(m, k);
32
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
33
+ desc = { enumerable: true, get: function() { return m[k]; } };
34
+ }
35
+ Object.defineProperty(o, k2, desc);
36
+ }) : (function(o, m, k, k2) {
37
+ if (k2 === undefined) k2 = k;
38
+ o[k2] = m[k];
39
+ }));
40
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
41
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
42
+ };
43
+ Object.defineProperty(exports, "__esModule", { value: true });
44
+ __exportStar(require("./controllers/index.js"), exports);
@@ -0,0 +1,119 @@
1
+ export interface Address {
2
+ line1?: string;
3
+ line2?: string;
4
+ city?: string;
5
+ state?: string;
6
+ zipCode?: string;
7
+ country?: string;
8
+ }
9
+ export interface CustomerData {
10
+ externalId: string;
11
+ email?: string;
12
+ name?: string;
13
+ firstName?: string;
14
+ lastName?: string;
15
+ company?: string;
16
+ phone?: string;
17
+ billingAddress?: Address;
18
+ metadata?: Record<string, any>;
19
+ }
20
+ export interface CompleteCustomerData {
21
+ externalId: string;
22
+ email: string;
23
+ name: string;
24
+ firstName: string;
25
+ lastName: string;
26
+ company: string;
27
+ phone: string;
28
+ billingAddress: Required<Address>;
29
+ metadata: Record<string, any>;
30
+ }
31
+ export interface ContactData {
32
+ customerExternalId: string;
33
+ email?: string;
34
+ firstName?: string;
35
+ lastName?: string;
36
+ phone?: string;
37
+ billingAddress?: Address;
38
+ salutation?: "Mr" | "Mrs" | "Ms" | "Dr" | "Prof";
39
+ }
40
+ export interface OrderConfig {
41
+ customerId: string;
42
+ customerExternalId: string;
43
+ billingContactId?: string;
44
+ agentExternalId: string;
45
+ name?: string;
46
+ description?: string;
47
+ startDate?: string;
48
+ endDate?: string;
49
+ currency?: string;
50
+ orderLines?: OrderLineConfig[];
51
+ }
52
+ export interface OrderLineConfig {
53
+ agentExternalId: string;
54
+ name?: string;
55
+ description?: string;
56
+ }
57
+ /**
58
+ * Note: orderLines is not required because if agentExternalId is provided,
59
+ * order lines can be derived from that agent.
60
+ */
61
+ export interface CompleteOrderConfig {
62
+ customerId: string;
63
+ customerExternalId: string;
64
+ billingContactId?: string;
65
+ agentExternalId: string;
66
+ name: string;
67
+ description: string;
68
+ startDate: string;
69
+ endDate: string;
70
+ currency: string;
71
+ orderLines: OrderLineConfig[];
72
+ }
73
+ export interface OrderOptions {
74
+ /**
75
+ * Whether to auto-activate orders after creation
76
+ * @default true
77
+ */
78
+ autoActivate?: boolean;
79
+ /**
80
+ * Duration in days for order end date (if not specified)
81
+ * @default 365
82
+ */
83
+ defaultDurationDays?: number;
84
+ }
85
+ export interface CustomerCreationResult {
86
+ id: string;
87
+ externalId: string;
88
+ }
89
+ export interface ContactCreationResult {
90
+ id: string;
91
+ }
92
+ export interface OrderCreationResult {
93
+ id: string;
94
+ creationState?: string;
95
+ }
96
+ export interface ProvisioningConfig {
97
+ /**
98
+ * Customer data (externalId required)
99
+ */
100
+ customer: CustomerData;
101
+ /**
102
+ * Contact data (optional, will use customer email if not provided)
103
+ */
104
+ contact?: Partial<ContactData>;
105
+ /**
106
+ * Agent external ID for order creation (optional)
107
+ * If not provided, no order will be created
108
+ */
109
+ agentExternalId?: string;
110
+ /**
111
+ * Options for order creation
112
+ */
113
+ orderOptions?: OrderOptions;
114
+ }
115
+ export interface ProvisioningResult {
116
+ customer: CustomerCreationResult;
117
+ contact: ContactCreationResult;
118
+ order?: OrderCreationResult;
119
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,18 @@
1
+ export interface PaidApiConfig {
2
+ apiUrl: string;
3
+ apiKey: string;
4
+ organizationId: string;
5
+ }
6
+ /**
7
+ * Make a direct API call to ap-signals
8
+ *
9
+ * @param config - API configuration with organization context
10
+ * @param endpoint - API endpoint path (will be appended to apiUrl)
11
+ * @param options - Fetch options (method, body)
12
+ * @returns Parsed JSON response
13
+ * @throws Error if request fails
14
+ */
15
+ export declare function paidApiFetch<T = any>(config: PaidApiConfig, endpoint: string, options?: {
16
+ method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
17
+ body?: any;
18
+ }): Promise<T>;
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.paidApiFetch = paidApiFetch;
13
+ /**
14
+ * Make a direct API call to ap-signals
15
+ *
16
+ * @param config - API configuration with organization context
17
+ * @param endpoint - API endpoint path (will be appended to apiUrl)
18
+ * @param options - Fetch options (method, body)
19
+ * @returns Parsed JSON response
20
+ * @throws Error if request fails
21
+ */
22
+ function paidApiFetch(config, endpoint, options) {
23
+ return __awaiter(this, void 0, void 0, function* () {
24
+ if (!config.organizationId) {
25
+ throw new Error("organizationId is required");
26
+ }
27
+ if (!config.apiKey) {
28
+ throw new Error("apiKey is required");
29
+ }
30
+ if (!config.apiUrl) {
31
+ throw new Error("apiUrl is required");
32
+ }
33
+ try {
34
+ const response = yield fetch(`${config.apiUrl}${endpoint}`, {
35
+ method: (options === null || options === void 0 ? void 0 : options.method) || "GET",
36
+ headers: {
37
+ Authorization: `Bearer ${config.apiKey}`,
38
+ "Content-Type": "application/json",
39
+ },
40
+ body: (options === null || options === void 0 ? void 0 : options.body) ? JSON.stringify(options.body) : undefined,
41
+ });
42
+ if (!response.ok) {
43
+ const errorText = yield response.text();
44
+ throw new Error(`API request failed: ${errorText}`);
45
+ }
46
+ return yield response.json();
47
+ }
48
+ catch (error) {
49
+ console.error("Error making Paid API request:", error);
50
+ throw error;
51
+ }
52
+ });
53
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Framework-agnostic base handler for Paid SDK integrations
3
+ * Provides consistent request handling, validation, and error handling
4
+ */
5
+ import type { PaidClient } from "../../Client.js";
6
+ import { type PaidClientConfig } from "../client.js";
7
+ export interface BaseRequestContext<TBody = any, TParams = Record<string, string>> {
8
+ body: TBody;
9
+ headers: Record<string, string>;
10
+ method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
11
+ params?: TParams;
12
+ query?: Record<string, string>;
13
+ }
14
+ export interface BaseResponseContext {
15
+ json: (data: any, status?: number) => any;
16
+ error: (message: string, status: number) => any;
17
+ }
18
+ export interface BaseHandlerConfig extends PaidClientConfig {
19
+ validate?: (body: any) => Promise<void> | void;
20
+ transformRequest?: (body: any) => any;
21
+ transformResponse?: (data: any) => any;
22
+ }
23
+ export type HandlerFunction<TRequest, TResponse> = (client: PaidClient, request: TRequest, params?: Record<string, string>, organizationId?: string) => Promise<{
24
+ success: boolean;
25
+ data?: TResponse;
26
+ error?: string;
27
+ status?: number;
28
+ }>;
29
+ /**
30
+ * Creates a framework-agnostic handler with automatic client initialization,
31
+ * validation, and error handling
32
+ *
33
+ * @param handler - Business logic handler function
34
+ * @param options - Handler configuration options
35
+ * @returns Framework-agnostic handler function
36
+ *
37
+ * @example
38
+ * ```typescript
39
+ * const customersHandler = createHandler(
40
+ * async (client, body) => {
41
+ * const customer = await createCustomerWithDefaults(client, body);
42
+ * return { success: true, data: customer };
43
+ * },
44
+ * { requiredFields: ['externalId'] }
45
+ * );
46
+ * ```
47
+ */
48
+ export declare function createHandler<TRequest = any, TResponse = any>(handler: HandlerFunction<TRequest, TResponse>, options?: {
49
+ requiredFields?: (keyof TRequest)[];
50
+ allowedMethods?: Array<"GET" | "POST" | "PUT" | "DELETE" | "PATCH">;
51
+ requireOrganizationId?: boolean;
52
+ }): (request: BaseRequestContext<TRequest>, response: BaseResponseContext, config?: BaseHandlerConfig) => Promise<any>;
53
+ /**
54
+ * Helper to create a fetch-based handler for simple API calls
55
+ *
56
+ * @param endpoint - Function that generates the endpoint URL from org ID and request body
57
+ * @param options - Optional method, request/response transformations
58
+ * @returns Handler function that makes the API call
59
+ *
60
+ * @example
61
+ * ```typescript
62
+ * const activateHandler = createHandler(
63
+ * createFetchHandler(
64
+ * (orgId, req) => `/api/organizations/${orgId}/orders/${req.orderId}/activate-sync`,
65
+ * {
66
+ * method: "POST",
67
+ * transformRequest: (req) => ({ confirmationToken: req.confirmationToken }),
68
+ * transformResponse: (data) => ({ order: data.order, billing: data.billing })
69
+ * }
70
+ * ),
71
+ * { requireOrganizationId: true }
72
+ * );
73
+ * ```
74
+ */
75
+ export declare function createFetchHandler<TRequest, TResponse>(endpoint: (orgId: string, body: TRequest, params?: Record<string, string>) => string, options?: {
76
+ method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
77
+ transformRequest?: (body: TRequest) => any;
78
+ transformResponse?: (data: any) => TResponse;
79
+ }): HandlerFunction<TRequest, TResponse>;
@@ -0,0 +1,168 @@
1
+ "use strict";
2
+ /**
3
+ * Framework-agnostic base handler for Paid SDK integrations
4
+ * Provides consistent request handling, validation, and error handling
5
+ */
6
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
7
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
8
+ return new (P || (P = Promise))(function (resolve, reject) {
9
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
10
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
12
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
13
+ });
14
+ };
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.createHandler = createHandler;
17
+ exports.createFetchHandler = createFetchHandler;
18
+ const client_js_1 = require("../client.js");
19
+ /**
20
+ * Creates a framework-agnostic handler with automatic client initialization,
21
+ * validation, and error handling
22
+ *
23
+ * @param handler - Business logic handler function
24
+ * @param options - Handler configuration options
25
+ * @returns Framework-agnostic handler function
26
+ *
27
+ * @example
28
+ * ```typescript
29
+ * const customersHandler = createHandler(
30
+ * async (client, body) => {
31
+ * const customer = await createCustomerWithDefaults(client, body);
32
+ * return { success: true, data: customer };
33
+ * },
34
+ * { requiredFields: ['externalId'] }
35
+ * );
36
+ * ```
37
+ */
38
+ function createHandler(handler, options = {}) {
39
+ const { requiredFields = [], allowedMethods = ["POST"], requireOrganizationId = false } = options;
40
+ return function (request_1, response_1) {
41
+ return __awaiter(this, arguments, void 0, function* (request, response, config = {}) {
42
+ if (!allowedMethods.includes(request.method)) {
43
+ return response.error("Method not allowed", 405);
44
+ }
45
+ for (const field of requiredFields) {
46
+ if (!request.body[field]) {
47
+ return response.error(`${String(field)} is required`, 400);
48
+ }
49
+ }
50
+ if (config.validate) {
51
+ try {
52
+ yield config.validate(request.body);
53
+ }
54
+ catch (error) {
55
+ return response.error(error instanceof Error ? error.message : "Validation failed", 400);
56
+ }
57
+ }
58
+ try {
59
+ const client = (0, client_js_1.initializePaidClient)(config);
60
+ let organizationId;
61
+ if (requireOrganizationId) {
62
+ const orgId = yield (0, client_js_1.getOrganizationId)(config);
63
+ if (!orgId) {
64
+ return response.error("Organization not found", 500);
65
+ }
66
+ organizationId = orgId;
67
+ }
68
+ const requestData = config.transformRequest
69
+ ? config.transformRequest(request.body)
70
+ : request.body;
71
+ const result = yield handler(client, requestData, request.params, organizationId);
72
+ if (!result.success) {
73
+ return response.error(result.error || "Operation failed", result.status || 500);
74
+ }
75
+ const responseData = config.transformResponse
76
+ ? config.transformResponse(result.data)
77
+ : { data: result.data };
78
+ return response.json(responseData, 200);
79
+ }
80
+ catch (error) {
81
+ console.error("Handler error:", error);
82
+ if (error instanceof TypeError && error.message.includes("fetch")) {
83
+ return response.error("Network error: Unable to reach Paid API", 503);
84
+ }
85
+ return response.error(error instanceof Error ? error.message : "Internal server error", 500);
86
+ }
87
+ });
88
+ };
89
+ }
90
+ /**
91
+ * Helper to create a fetch-based handler for simple API calls
92
+ *
93
+ * @param endpoint - Function that generates the endpoint URL from org ID and request body
94
+ * @param options - Optional method, request/response transformations
95
+ * @returns Handler function that makes the API call
96
+ *
97
+ * @example
98
+ * ```typescript
99
+ * const activateHandler = createHandler(
100
+ * createFetchHandler(
101
+ * (orgId, req) => `/api/organizations/${orgId}/orders/${req.orderId}/activate-sync`,
102
+ * {
103
+ * method: "POST",
104
+ * transformRequest: (req) => ({ confirmationToken: req.confirmationToken }),
105
+ * transformResponse: (data) => ({ order: data.order, billing: data.billing })
106
+ * }
107
+ * ),
108
+ * { requireOrganizationId: true }
109
+ * );
110
+ * ```
111
+ */
112
+ function createFetchHandler(endpoint, options) {
113
+ return (client, requestBody, params, organizationId) => __awaiter(this, void 0, void 0, function* () {
114
+ var _a, _b;
115
+ if (!organizationId) {
116
+ return {
117
+ success: false,
118
+ error: "Organization ID is required for this operation",
119
+ status: 500,
120
+ };
121
+ }
122
+ try {
123
+ const url = endpoint(organizationId, requestBody, params);
124
+ const body = (options === null || options === void 0 ? void 0 : options.transformRequest)
125
+ ? options.transformRequest(requestBody)
126
+ : requestBody;
127
+ const baseUrl = ((_a = client._options) === null || _a === void 0 ? void 0 : _a.baseUrl) || "https://api.agentpaid.io/api/v1";
128
+ const apiKey = (_b = client._options) === null || _b === void 0 ? void 0 : _b.token;
129
+ if (!apiKey) {
130
+ return {
131
+ success: false,
132
+ error: "API key not found in client",
133
+ status: 500,
134
+ };
135
+ }
136
+ const fetchResponse = yield fetch(`${baseUrl}${url}`, {
137
+ method: (options === null || options === void 0 ? void 0 : options.method) || "POST",
138
+ headers: {
139
+ Authorization: `Bearer ${apiKey}`,
140
+ "Content-Type": "application/json",
141
+ },
142
+ body: (options === null || options === void 0 ? void 0 : options.method) !== "GET" ? JSON.stringify(body) : undefined,
143
+ });
144
+ if (!fetchResponse.ok) {
145
+ const errorText = yield fetchResponse.text();
146
+ console.error("API error:", errorText);
147
+ return {
148
+ success: false,
149
+ error: `API request failed: ${errorText}`,
150
+ status: fetchResponse.status,
151
+ };
152
+ }
153
+ const data = yield fetchResponse.json();
154
+ const transformedData = (options === null || options === void 0 ? void 0 : options.transformResponse)
155
+ ? options.transformResponse(data)
156
+ : data;
157
+ return { success: true, data: transformedData };
158
+ }
159
+ catch (error) {
160
+ console.error("Fetch error:", error);
161
+ return {
162
+ success: false,
163
+ error: error instanceof Error ? error.message : "Unknown error",
164
+ status: 500,
165
+ };
166
+ }
167
+ });
168
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Generic adapter factory - eliminates repetitive adapter code
3
+ * Works with any framework (Express, Fastify, Hono, Next.js, etc.)
4
+ */
5
+ /**
6
+ * Creates a framework adapter for any HTTP framework
7
+ * Automatically extracts headers and converts request/response
8
+ *
9
+ * @param extractors - Framework-specific extraction functions
10
+ * @returns Adapter function that wraps core handlers
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * const nextjsAdapter = createFrameworkAdapter({
15
+ * getBody: async (req) => await req.json(),
16
+ * getHeaders: (req) => Object.fromEntries(req.headers),
17
+ * getMethod: (req) => req.method || "GET",
18
+ * sendJson: (data, status) => NextResponse.json(data, { status })
19
+ * });
20
+ * ```
21
+ */
22
+ export declare function createFrameworkAdapter<TFrameworkReq = any, TFrameworkRes = any>(extractors: {
23
+ getBody: (req: TFrameworkReq) => any | Promise<any>;
24
+ getHeaders: (req: TFrameworkReq) => Record<string, string>;
25
+ getMethod: (req: TFrameworkReq) => string;
26
+ getParams?: (req: TFrameworkReq, context?: any) => Record<string, string> | Promise<Record<string, string>>;
27
+ getQuery?: (req: TFrameworkReq) => Record<string, string>;
28
+ sendJson: (data: any, status: number) => TFrameworkRes;
29
+ }): (innerHandler: Function) => (req: TFrameworkReq, context?: any, config?: any) => Promise<any>;