-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathindex.ts
More file actions
283 lines (239 loc) · 8.3 KB
/
index.ts
File metadata and controls
283 lines (239 loc) · 8.3 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
/* Python/Django integration — auto-discovered by registry */
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import type { FrameworkConfig } from '../../lib/framework-config.js';
import type { InstallerOptions } from '../../utils/types.js';
import { enableDebugLogs } from '../../utils/debug.js';
import { analytics } from '../../utils/analytics.js';
import { INSTALLER_INTERACTION_EVENT_NAME } from '../../lib/constants.js';
import { parseEnvFile } from '../../utils/env-parser.js';
import { getReference } from '@workos/skills';
/**
* Detect which Python package manager the project uses.
*/
function detectPythonPackageManager(installDir: string): { name: string; installCmd: string } {
if (existsSync(join(installDir, 'uv.lock'))) {
return { name: 'uv', installCmd: 'uv add' };
}
if (existsSync(join(installDir, 'pyproject.toml'))) {
try {
const content = readFileSync(join(installDir, 'pyproject.toml'), 'utf-8');
if (content.includes('[tool.poetry]')) {
return { name: 'poetry', installCmd: 'poetry add' };
}
} catch {
/* ignore */
}
}
if (existsSync(join(installDir, 'Pipfile'))) {
return { name: 'pipenv', installCmd: 'pipenv install' };
}
return { name: 'pip', installCmd: 'pip install' };
}
/**
* Detect if this is a Django project.
*/
function isDjangoProject(installDir: string): boolean {
if (existsSync(join(installDir, 'manage.py'))) return true;
const pyprojectPath = join(installDir, 'pyproject.toml');
if (existsSync(pyprojectPath)) {
try {
const content = readFileSync(pyprojectPath, 'utf-8');
if (/django/i.test(content)) return true;
} catch {
/* ignore */
}
}
const reqPath = join(installDir, 'requirements.txt');
if (existsSync(reqPath)) {
try {
const content = readFileSync(reqPath, 'utf-8');
if (/^django/im.test(content)) return true;
} catch {
/* ignore */
}
}
return false;
}
/**
* Write .env file for Python projects (not .env.local).
* Merges with existing .env. No cookie password generation.
*/
function writeEnvFile(installDir: string, envVars: Record<string, string>): void {
const envPath = join(installDir, '.env');
let existingEnv: Record<string, string> = {};
if (existsSync(envPath)) {
try {
existingEnv = parseEnvFile(readFileSync(envPath, 'utf-8'));
} catch {
/* ignore */
}
}
const merged = { ...existingEnv, ...envVars };
const content = Object.entries(merged)
.map(([key, value]) => `${key}=${value}`)
.join('\n');
writeFileSync(envPath, content + '\n');
}
export const config: FrameworkConfig = {
metadata: {
name: 'Python (Django)',
integration: 'python',
docsUrl: 'https://workos.com/docs/user-management/authkit/vanilla/python',
skillName: 'workos-python',
language: 'python',
stability: 'experimental',
priority: 60,
packageManager: 'pip',
manifestFile: 'pyproject.toml',
detect: (options: Pick<InstallerOptions, 'installDir'>) => isDjangoProject(options.installDir),
gatherContext: async (options: InstallerOptions) => {
const pkgMgr = detectPythonPackageManager(options.installDir);
return {
packageManager: pkgMgr.name,
installCommand: pkgMgr.installCmd,
isDjango: isDjangoProject(options.installDir),
};
},
},
detection: {
// Dummy values for FrameworkDetection interface compat — Python doesn't use package.json
packageName: 'workos',
packageDisplayName: 'Python (Django)',
getVersion: () => undefined,
},
environment: {
uploadToHosting: false,
requiresApiKey: true,
getEnvVars: (apiKey: string, clientId: string) => ({
WORKOS_API_KEY: apiKey,
WORKOS_CLIENT_ID: clientId,
}),
},
analytics: {
getTags: (context: any) => ({
'python-package-manager': context?.packageManager || 'unknown',
'python-is-django': String(context?.isDjango ?? false),
}),
},
prompts: {
getAdditionalContextLines: (context: any) => {
const lines: string[] = [];
if (context?.packageManager) lines.push(`Package manager: ${context.packageManager}`);
if (context?.installCommand) lines.push(`Install command: ${context.installCommand}`);
if (context?.isDjango) lines.push('Framework: Django');
return lines;
},
},
ui: {
successMessage: 'WorkOS AuthKit integration complete',
getOutroChanges: () => [
'Analyzed your Python/Django project structure',
'Installed WorkOS Python SDK',
'Created authentication views (login, callback, logout)',
'Configured URL routing and environment variables',
],
getOutroNextSteps: () => [
'Run `python manage.py runserver` to test authentication',
'Visit http://localhost:8000/auth/login to test the login flow',
'Visit the WorkOS Dashboard to manage users and settings',
],
},
};
/**
* Build the agent prompt for Python/Django integration.
*/
async function buildPythonPrompt(frameworkContext: Record<string, any>): Promise<string> {
const contextLines = ['- Framework: Python (Django)'];
if (frameworkContext.packageManager) contextLines.push(`- Package manager: ${frameworkContext.packageManager}`);
if (frameworkContext.installCommand) contextLines.push(`- Install command: ${frameworkContext.installCommand}`);
const skillName = config.metadata.skillName!;
const refContent = await getReference(skillName);
return `You are integrating WorkOS AuthKit into this Python/Django application.
## Project Context
${contextLines.join('\n')}
## Environment
The following environment variables have been configured in .env:
- WORKOS_API_KEY
- WORKOS_CLIENT_ID
## Integration Instructions
${refContent}
Report your progress using [STATUS] prefixes.
Begin integration now.`;
}
/**
* Custom run function that bypasses runAgentInstaller.
* Calls initializeAgent + runAgent directly, handling Python-specific
* env writing and prompt building.
*/
export async function run(options: InstallerOptions): Promise<string> {
if (options.debug) {
enableDebugLogs();
}
options.emitter?.emit('status', {
message: 'Setting up WorkOS AuthKit for Python (Django)',
});
const apiKey = options.apiKey || '';
const clientId = options.clientId || '';
// Gather Python-specific context
const frameworkContext = config.metadata.gatherContext ? await config.metadata.gatherContext(options) : {};
analytics.capture(INSTALLER_INTERACTION_EVENT_NAME, {
action: 'started agent integration',
integration: 'python',
});
// Set analytics tags
const contextTags = config.analytics.getTags(frameworkContext);
for (const [key, value] of Object.entries(contextTags)) {
analytics.setTag(key, value);
}
// Write .env (not .env.local) with WorkOS credentials
writeEnvFile(options.installDir, {
...(apiKey ? { WORKOS_API_KEY: apiKey } : {}),
WORKOS_CLIENT_ID: clientId,
});
// Build Python-specific prompt
const prompt = await buildPythonPrompt(frameworkContext);
// Initialize and run agent directly (bypass runAgentInstaller)
const { initializeAgent, runAgent } = await import('../../lib/agent-interface.js');
const agentConfig = await initializeAgent(
{
workingDirectory: options.installDir,
workOSApiKey: apiKey,
workOSApiHost: 'https://api.workos.com',
},
options,
);
const result = await runAgent(
agentConfig,
prompt,
options,
{
spinnerMessage: 'Setting up WorkOS AuthKit for Python/Django...',
successMessage: config.ui.successMessage,
errorMessage: 'Python integration failed',
},
options.emitter,
);
if (result.error) {
await analytics.shutdown('error');
throw new Error(`Agent error: ${result.errorMessage || result.error}`);
}
// Build completion summary
const changes = config.ui.getOutroChanges({});
const nextSteps = config.ui.getOutroNextSteps({});
const lines: string[] = [
'Successfully installed WorkOS AuthKit!',
'',
'What the agent did:',
...changes.map((c) => `• ${c}`),
'',
'Next steps:',
...nextSteps.map((s) => `• ${s}`),
'',
`Learn more: ${config.metadata.docsUrl}`,
'',
'Note: This installer uses an LLM agent to analyze and modify your project. Please review the changes made.',
];
await analytics.shutdown('success');
return lines.join('\n');
}