-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-code-tools.ts
More file actions
345 lines (293 loc) · 12.7 KB
/
Copy pathgenerate-code-tools.ts
File metadata and controls
345 lines (293 loc) · 12.7 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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
import { readFileSync, writeFileSync, mkdirSync } from "fs";
import { join } from "path";
// Load the spec
const specPath = join(process.cwd(), "data", "spec3.clean.json");
const spec = JSON.parse(readFileSync(specPath, "utf-8"));
// Constants for path matching (same as server.ts)
const topLevelRegex = /^\/v1\/[^\/]+$/;
const detailLevelRegex = /^\/v1\/[^\/]+\/\{[^}]+\}$/;
const httpMethods = ["get", "post", "put", "patch", "delete"];
interface Operation {
operationId: string;
description: string;
path: string;
method: string;
parameters: any[];
requestBody: any;
}
// Helper to list all operations from the spec
function listAllOperations(): Operation[] {
const operations: Operation[] = [];
for (const [path, pathItem] of Object.entries(spec.paths || {})) {
if (!topLevelRegex.test(path) && !detailLevelRegex.test(path)) continue;
for (const method of httpMethods) {
const operation = (pathItem as any)[method];
if (operation && operation.operationId) {
operations.push({
operationId: operation.operationId,
description: operation.description || "",
path,
method,
parameters: operation.parameters || [],
requestBody: operation.requestBody || null,
});
}
}
}
return operations;
}
// Helper to convert path to Stripe SDK resource name
function pathToResourceName(path: string): string {
// Extract resource name from path: /v1/resource_name or /v1/resource_name/{id}
const match = path.match(/^\/v1\/([^/]+)/);
if (!match) return "";
const pathResource = match[1];
// Convert snake_case to camelCase
const camelCase = pathResource.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
return camelCase;
}
// Helper to get the Stripe SDK type name for an operation
function getStripeTypeName(mainResource: string, method: string, isDetailPath: boolean, isSingleton: boolean): string {
// Convert resource name to singular, PascalCase for type name
const httpMethod = method.toLowerCase();
// Determine the operation type
let operationType = "";
if (httpMethod === "get") {
if (isSingleton || isDetailPath) {
operationType = "Retrieve";
} else {
operationType = "List";
}
} else if (httpMethod === "post") {
if (isDetailPath) {
operationType = "Update";
} else {
operationType = "Create";
}
} else if (httpMethod === "delete") {
// Special case: subscriptions use "Cancel" instead of "Delete"
if (mainResource === "subscriptions") {
operationType = "Cancel";
} else {
operationType = "Delete";
}
} else if (httpMethod === "patch" || httpMethod === "put") {
operationType = "Update";
}
// Convert resource to singular PascalCase
let resourceTypeName = mainResource;
// Handle camelCase to PascalCase
resourceTypeName = resourceTypeName.charAt(0).toUpperCase() + resourceTypeName.slice(1);
// Remove trailing 's' for singular
if (resourceTypeName.endsWith("s")) {
// Check if it's a simple plural
if (resourceTypeName.endsWith("ies")) {
resourceTypeName = resourceTypeName.slice(0, -3) + "y";
} else if (resourceTypeName.endsWith("ses")) {
resourceTypeName = resourceTypeName.slice(0, -2);
} else if (resourceTypeName.endsWith("xes")) {
resourceTypeName = resourceTypeName.slice(0, -2);
} else if (!resourceTypeName.endsWith("ss") && resourceTypeName.endsWith("s")) {
// Special handling for compound words
// balanceTransactions -> BalanceTransaction
// paymentIntents -> PaymentIntent
// setupIntents -> SetupIntent
// paymentMethods -> PaymentMethod
// ephemeralKeys -> EphemeralKey
resourceTypeName = resourceTypeName.slice(0, -1);
}
}
return `Stripe.${resourceTypeName}${operationType}Params`;
}
// Helper to generate TypeScript interface from OpenAPI parameters
function generateInlineParamsType(operation: Operation, typeName: string): string {
const { parameters, requestBody } = operation;
const properties: string[] = [];
// Add path parameters
if (parameters) {
for (const param of parameters) {
if (param.schema) {
const required = param.required ? "" : "?";
let type = "any";
if (param.schema.type === "string") type = "string";
else if (param.schema.type === "integer" || param.schema.type === "number") type = "number";
else if (param.schema.type === "boolean") type = "boolean";
else if (param.schema.type === "array") type = "any[]";
const description = param.description ? ` /** ${param.description} */\n` : "";
properties.push(`${description} ${param.name}${required}: ${type};`);
}
}
}
// Add request body parameters
if (requestBody?.content) {
const formContent = requestBody.content["application/x-www-form-urlencoded"];
if (formContent?.schema?.properties) {
for (const [propName, propSchema] of Object.entries(formContent.schema.properties)) {
const schema = propSchema as any;
const required = formContent.schema.required?.includes(propName) ? "" : "?";
let type = "any";
if (schema.type === "string") type = "string";
else if (schema.type === "number" || schema.type === "integer") type = "number";
else if (schema.type === "boolean") type = "boolean";
else if (schema.type === "array") type = "any[]";
else if (schema.type === "object") type = "Record<string, any>";
const description = schema.description ? ` /** ${schema.description.replace(/\*\//g, '*\\/')} */\n` : "";
properties.push(`${description} ${propName}${required}: ${type};`);
}
}
}
if (properties.length === 0) {
return `interface ${typeName} {\n [key: string]: any;\n}`;
}
return `interface ${typeName} {\n${properties.join("\n")}\n}`;
}
// Generate wrapper function code for an operation
function generateOperationWrapper(operation: Operation): string {
const { operationId, description, method, parameters, path } = operation;
// Check if this is a detail path (has {param})
const isDetailPath = path.includes("{");
// Extract resource name from the path (most reliable method)
let mainResource = pathToResourceName(path);
// Special case mappings for resources that don't match exactly
const specialCases: Record<string, string> = {
'invoiceitems': 'invoiceItems',
'account': method.toLowerCase() === 'get' && !isDetailPath ? 'accounts' : 'account',
'linkAccountSessions': 'accountSessions',
'linkedAccounts': 'accounts', // linkedAccounts maps to accounts
'externalAccounts': 'accounts.externalAccounts', // external accounts is a nested resource
};
if (specialCases[mainResource]) {
mainResource = specialCases[mainResource];
}
// Check if this is a singleton resource
const singletonResources = ["balance", "account"];
const isSingleton = singletonResources.includes(mainResource) ||
(mainResource === "accounts" && method.toLowerCase() === "get" && !isDetailPath && operationId === "GetAccount");
// Extract path parameter name
let pathParamName: string | null = null;
if (parameters) {
const pathParam = parameters.find((p: any) => p.in === "path");
if (pathParam) {
pathParamName = pathParam.name;
}
}
// Get the Stripe SDK type name
let paramsType = getStripeTypeName(mainResource, method, isDetailPath, isSingleton);
// For detail operations, we need to add the ID field to the params type
if (isDetailPath) {
const idParam = pathParamName || "id";
paramsType = `${paramsType} & { ${idParam}: string }`;
}
// Special handling for operations that don't follow standard patterns
const specialImplementations: Record<string, string> = {
'GetBalanceSettings': ` // Note: balanceSettings doesn't have a standard list method
// Use retrieve instead
return await stripe.balanceSettings.retrieve(params as any);`,
'PostBalanceSettings': ` // Note: balanceSettings doesn't have a standard create method
// This endpoint updates balance settings
return await stripe.balanceSettings.update(params as any);`,
'GetLinkAccountSessionsSession': ` // Note: Link account sessions don't have standard retrieve method
// This endpoint may require special handling
const session = (params as any).session;
const { session: _, ...options } = params as any;
return await (stripe as any).accountSessions.retrieve(session, options);`,
'PostExternalAccountsId': ` // Note: External accounts are nested under accounts
const id = (params as any).id;
const accountId = (params as any).account || (params as any).accountId;
const { id: _id, account: _account, accountId: _accountId, ...options } = params as any;
return await stripe.accounts.updateExternalAccount(accountId, id, options as any);`,
};
// Generate the function implementation
let implementation = "";
if (specialImplementations[operationId]) {
implementation = specialImplementations[operationId];
} else {
const httpMethod = method.toLowerCase();
if (httpMethod === "get") {
if (isSingleton) {
implementation = ` return await stripe.${mainResource}.retrieve(params as any);`;
} else if (isDetailPath) {
const idParam = pathParamName || "id";
implementation = ` const ${idParam} = (params as any).${idParam};
const { ${idParam}: _, ...options } = params as any;
return await stripe.${mainResource}.retrieve(${idParam}, options as any);`;
} else {
implementation = ` return await stripe.${mainResource}.list(params as any);`;
}
} else if (httpMethod === "post") {
if (isDetailPath) {
const idParam = pathParamName || "id";
implementation = ` const ${idParam} = (params as any).${idParam};
const { ${idParam}: _, ...options } = params as any;
return await stripe.${mainResource}.update(${idParam}, options as any);`;
} else {
implementation = ` return await stripe.${mainResource}.create(params as any);`;
}
} else if (httpMethod === "delete") {
const idParam = pathParamName || "id";
if (mainResource === 'subscriptions') {
implementation = ` const ${idParam} = (params as any).${idParam};
const { ${idParam}: _, ...options } = params as any;
return await stripe.${mainResource}.cancel(${idParam}, options as any);`;
} else {
implementation = ` const ${idParam} = (params as any).${idParam};
const { ${idParam}: _, ...options } = params as any;
return await stripe.${mainResource}.del(${idParam}, options as any);`;
}
} else if (httpMethod === "patch" || httpMethod === "put") {
const idParam = pathParamName || "id";
implementation = ` const ${idParam} = (params as any).${idParam};
const { ${idParam}: _, ...options } = params as any;
return await stripe.${mainResource}.update(${idParam}, options as any);`;
}
}
const escapedDescription = description.replace(/\*\//g, '*\\/');
// Generate inline type definition
const paramsTypeName = `${operationId}Params`;
const inlineType = generateInlineParamsType(operation, paramsTypeName);
return `import Stripe from "stripe";
${inlineType}
/**
* ${escapedDescription}
*
* @param stripe - Stripe client instance
* @param params - Parameters for the operation
* @returns Promise resolving to the API response
*/
export async function ${operationId}(
stripe: Stripe,
params: ${paramsTypeName} = {} as ${paramsTypeName}
): Promise<any> {
${implementation}
}
`;
}
// Main generation logic
function main() {
console.log("Generating code tools...");
const operations = listAllOperations();
console.log(`Found ${operations.length} operations`);
// Create code_tools directory
const codeToolsDir = join(process.cwd(), "mock_sandbox","code_tools");
mkdirSync(codeToolsDir, { recursive: true });
// Generate a file for each operation
const exportStatements: string[] = [];
for (const operation of operations) {
const fileName = `${operation.operationId}.ts`;
const filePath = join(codeToolsDir, fileName);
const code = generateOperationWrapper(operation);
writeFileSync(filePath, code, "utf-8");
exportStatements.push(`export { ${operation.operationId} } from "./${operation.operationId}.js";`);
}
// Generate simple index.ts that just exports all operations
const indexPath = join(codeToolsDir, "index.ts");
const indexContent = `// Export all operation functions
// Each file is self-contained with its own inline type definitions
${exportStatements.sort().join("\n")}
`;
writeFileSync(indexPath, indexContent, "utf-8");
console.log(`✓ Generated ${operations.length} self-contained operation wrappers`);
console.log(`✓ Created index.ts with all exports`);
console.log(`✓ Code tools available in ${codeToolsDir}`);
}
main();