-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase.ts
More file actions
189 lines (171 loc) · 5.28 KB
/
base.ts
File metadata and controls
189 lines (171 loc) · 5.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import { readFileSync } from "node:fs";
import http from "node:http";
import https from "node:https";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import axios, { AxiosInstance, AxiosResponse } from "axios";
import { parse as csvParse } from "csv-parse/sync";
import { z } from "zod";
import { createIterableConfig } from "../config.js";
import {
createIterableError,
IterableResponseValidationError,
} from "../errors.js";
import { logger } from "../logger.js";
import { IterableConfig } from "../types/common.js";
// Get package version for User-Agent header
const packageJson = JSON.parse(
readFileSync(
join(dirname(fileURLToPath(import.meta.url)), "..", "..", "package.json"),
"utf-8"
)
);
// Export User-Agent value for reuse in other clients (like MCP server)
export const DEFAULT_USER_AGENT = `iterable-api/${packageJson.version}`;
/**
* Base client with shared infrastructure for all Iterable API operations
*/
export class BaseIterableClient {
public client: AxiosInstance;
constructor(config?: IterableConfig, injectedClient?: AxiosInstance) {
const clientConfig = config || createIterableConfig();
if (injectedClient) {
this.client = injectedClient;
} else {
const defaultHeaders = {
"Api-Key": clientConfig.apiKey,
"Content-Type": "application/json",
"User-Agent": DEFAULT_USER_AGENT,
};
this.client = axios.create({
baseURL: clientConfig.baseUrl,
headers: {
...defaultHeaders,
...(clientConfig.customHeaders || {}),
},
timeout: clientConfig.timeout || 30000,
httpAgent: new http.Agent({
keepAlive: true,
keepAliveMsecs: 1000,
}),
httpsAgent: new https.Agent({
keepAlive: true,
keepAliveMsecs: 1000,
}),
maxRedirects: 5,
});
}
// Add error handling interceptor (always active)
if (!injectedClient) {
this.client.interceptors.response.use(
(response) => response,
(error) => {
return Promise.reject(createIterableError(error));
}
);
// Add debug logging interceptors (only when debug is enabled)
// WARNING: Never enable debug mode in production as it may log sensitive information
if (clientConfig.debug) {
const sanitizeHeaders = (headers: any) => {
if (!headers) return undefined;
const sensitive = [
"api-key",
"authorization",
"cookie",
"set-cookie",
];
const sanitized = { ...headers };
Object.keys(sanitized).forEach((key) => {
if (sensitive.includes(key.toLowerCase())) {
sanitized[key] = "[REDACTED]";
}
});
return sanitized;
};
this.client.interceptors.request.use((request) => {
logger.debug("API request", {
method: request.method?.toUpperCase(),
url: request.url,
headers: sanitizeHeaders(request.headers),
});
return request;
});
const createResponseLogData = (response: any, includeData = false) => ({
status: response.status,
url: response.config?.url,
...(includeData && { data: response.data }),
});
this.client.interceptors.response.use(
(response) => {
logger.debug(
"API response",
createResponseLogData(response, clientConfig.debugVerbose)
);
return response;
},
(error) => {
if (error.response) {
// CRITICAL: Only log response data if verbose debug is enabled to prevent PII leaks
logger.error(
"API error",
createResponseLogData(error.response, clientConfig.debugVerbose)
);
} else {
logger.error("Network error", { message: error.message });
}
return Promise.reject(error);
}
);
}
}
}
/**
* Clean up HTTP agents to prevent Jest from hanging
* Should be called when the client is no longer needed
*/
public destroy(): void {
this.client.defaults.httpAgent?.destroy();
this.client.defaults.httpsAgent?.destroy();
}
}
/**
* @throws IterableResponseValidationError if CSV parsing fails
*/
export function parseCsv(
response: AxiosResponse<string>
): Record<string, string>[] {
if (!response.data) {
return [];
}
try {
return csvParse(response.data, {
columns: true,
skip_empty_lines: true,
trim: true,
});
} catch (error) {
throw new IterableResponseValidationError(
200,
response.data,
`CSV parse error: ${error instanceof Error ? error.message : String(error)}`,
response.config?.url
);
}
}
export function validateResponse<T>(
response: { data: unknown; config?: { url?: string } },
schema: z.ZodSchema<T>
): T {
const result = schema.safeParse(response.data);
if (!result.success) {
throw new IterableResponseValidationError(
200,
response.data,
result.error.message,
response.config?.url
);
}
return result.data;
}
// Type helper for mixins
export type Constructor<T = object> = new (...args: any[]) => T;