@nordsym/apiclaw 1.5.13 → 1.5.14

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 (68) hide show
  1. package/dist/bin.js +1 -1
  2. package/dist/cli/index.js +7 -0
  3. package/dist/convex/adminActivate.js +46 -0
  4. package/dist/convex/adminStats.js +41 -0
  5. package/dist/convex/agents.js +498 -0
  6. package/dist/convex/analytics.js +165 -0
  7. package/dist/convex/billing.js +654 -0
  8. package/dist/convex/capabilities.js +144 -0
  9. package/dist/convex/chains.js +1041 -0
  10. package/dist/convex/credits.js +185 -0
  11. package/dist/convex/crons.js +16 -0
  12. package/dist/convex/directCall.js +626 -0
  13. package/dist/convex/earnProgress.js +648 -0
  14. package/dist/convex/email.js +299 -0
  15. package/dist/convex/feedback.js +226 -0
  16. package/dist/convex/http.js +909 -0
  17. package/dist/convex/logs.js +486 -0
  18. package/dist/convex/mou.js +81 -0
  19. package/dist/convex/providerKeys.js +256 -0
  20. package/dist/convex/providers.js +755 -0
  21. package/dist/convex/purchases.js +156 -0
  22. package/dist/convex/ratelimit.js +90 -0
  23. package/dist/convex/schema.js +709 -0
  24. package/dist/convex/searchLogs.js +128 -0
  25. package/dist/convex/spendAlerts.js +379 -0
  26. package/dist/convex/stripeActions.js +410 -0
  27. package/dist/convex/teams.js +214 -0
  28. package/dist/convex/telemetry.js +73 -0
  29. package/dist/convex/usage.js +228 -0
  30. package/dist/convex/waitlist.js +48 -0
  31. package/dist/convex/webhooks.js +409 -0
  32. package/dist/convex/workspaces.js +879 -0
  33. package/dist/src/analytics.js +129 -0
  34. package/dist/src/bin.js +17 -0
  35. package/dist/src/capability-router.js +240 -0
  36. package/dist/src/chainExecutor.js +451 -0
  37. package/dist/src/chainResolver.js +518 -0
  38. package/dist/src/cli/commands/doctor.js +324 -0
  39. package/dist/src/cli/commands/mcp-install.js +255 -0
  40. package/dist/src/cli/commands/restore.js +259 -0
  41. package/dist/src/cli/commands/setup.js +205 -0
  42. package/dist/src/cli/commands/uninstall.js +188 -0
  43. package/dist/src/cli/index.js +111 -0
  44. package/dist/src/cli.js +302 -0
  45. package/dist/src/confirmation.js +240 -0
  46. package/dist/src/credentials.js +357 -0
  47. package/dist/src/credits.js +260 -0
  48. package/dist/src/crypto.js +66 -0
  49. package/dist/src/discovery.js +504 -0
  50. package/dist/src/enterprise/env.js +123 -0
  51. package/dist/src/enterprise/script-generator.js +460 -0
  52. package/dist/src/execute-dynamic.js +473 -0
  53. package/dist/src/execute.js +1727 -0
  54. package/dist/src/index.js +2062 -0
  55. package/dist/src/metered.js +80 -0
  56. package/dist/src/open-apis.js +276 -0
  57. package/dist/src/proxy.js +28 -0
  58. package/dist/src/session.js +86 -0
  59. package/dist/src/stripe.js +407 -0
  60. package/dist/src/telemetry.js +49 -0
  61. package/dist/src/types.js +2 -0
  62. package/dist/src/utils/backup.js +181 -0
  63. package/dist/src/utils/config.js +220 -0
  64. package/dist/src/utils/os.js +105 -0
  65. package/dist/src/utils/paths.js +159 -0
  66. package/package.json +1 -1
  67. package/src/bin.ts +1 -1
  68. package/src/cli/index.ts +8 -0
@@ -0,0 +1,111 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * APIClaw MCP Auto-Setup CLI
4
+ * Enterprise-grade, platform-agnostic configuration tool
5
+ */
6
+ import { Command } from 'commander';
7
+ import { writeFileSync } from 'fs';
8
+ import { setupCommand } from './commands/setup.js';
9
+ import { mcpInstallCommand } from './commands/mcp-install.js';
10
+ import { doctorCommand } from './commands/doctor.js';
11
+ import { restoreCommand } from './commands/restore.js';
12
+ import { uninstallCommand } from './commands/uninstall.js';
13
+ import { generateScript } from '../enterprise/script-generator.js';
14
+ const VERSION = '1.0.0';
15
+ const program = new Command();
16
+ program
17
+ .name('apiclaw')
18
+ .description('APIClaw MCP Auto-Setup - Configure APIClaw across all your AI coding assistants')
19
+ .version(VERSION);
20
+ // Setup command - main entry point
21
+ program
22
+ .command('setup')
23
+ .description('Configure APIClaw for MCP clients')
24
+ .option('-c, --client <client>', 'Target specific client (claude-desktop, cursor, windsurf, cline, continue)')
25
+ .option('--config <path>', 'Custom config file path')
26
+ .option('-w, --workspace <id>', 'Pre-link APIClaw workspace ID')
27
+ .option('--dry-run', 'Show what would happen without making changes')
28
+ .option('-f, --force', 'Overwrite existing APIClaw configuration')
29
+ .option('--wizard', 'Interactive setup wizard')
30
+ .option('--all', 'Configure all detected clients')
31
+ .option('-v, --verbose', 'Verbose output')
32
+ .option('--enterprise', 'Generate enterprise deployment script')
33
+ .option('--output <file>', 'Output file for enterprise script')
34
+ .option('--script-type <type>', 'Script type: bash or powershell (default: auto)')
35
+ .action(async (options) => {
36
+ // Enterprise script generation mode
37
+ if (options.enterprise) {
38
+ const scriptType = options.scriptType || 'auto';
39
+ const result = generateScript(scriptType, {
40
+ workspace: options.workspace,
41
+ verbose: options.verbose,
42
+ });
43
+ if (options.output) {
44
+ writeFileSync(options.output, result.script);
45
+ console.log(`\n✓ Enterprise script written to: ${options.output}`);
46
+ console.log(` Type: ${result.platform}`);
47
+ console.log(`\nUsage:`);
48
+ if (result.platform === 'bash') {
49
+ console.log(` chmod +x ${options.output}`);
50
+ console.log(` ./${options.output}`);
51
+ }
52
+ else {
53
+ console.log(` powershell -ExecutionPolicy Bypass -File ${options.output}`);
54
+ }
55
+ console.log('');
56
+ }
57
+ else {
58
+ console.log(result.script);
59
+ }
60
+ return;
61
+ }
62
+ // Normal setup
63
+ await setupCommand(options);
64
+ });
65
+ // MCP Install command - simple focused installation
66
+ program
67
+ .command('mcp-install')
68
+ .description('Install APIClaw into Claude Desktop or Claude Code MCP config')
69
+ .option('-c, --client <client>', 'Target specific client (claude-desktop, claude-code)')
70
+ .option('--dry-run', 'Show what would happen without making changes')
71
+ .action(mcpInstallCommand);
72
+ // Doctor command - health check
73
+ program
74
+ .command('doctor')
75
+ .description('Diagnose APIClaw setup and connectivity')
76
+ .option('--server-name <name>', 'Server name to check (default: apiclaw)')
77
+ .option('--json', 'Output as JSON')
78
+ .action(doctorCommand);
79
+ // Restore command - rollback from backup
80
+ program
81
+ .command('restore')
82
+ .description('Restore config from backup')
83
+ .option('-c, --client <client>', 'Target specific client')
84
+ .option('-l, --list', 'List available backups')
85
+ .option('-b, --backup <file>', 'Specific backup file to restore')
86
+ .option('--dry-run', 'Show what would be done without making changes')
87
+ .action(restoreCommand);
88
+ // Uninstall command - remove APIClaw
89
+ program
90
+ .command('uninstall')
91
+ .description('Remove APIClaw from all configured clients')
92
+ .option('-c, --client <client>', 'Target specific client')
93
+ .option('--all', 'Remove from all clients')
94
+ .option('--server-name <name>', 'Server name to remove (default: apiclaw)')
95
+ .option('--no-backup', 'Skip backup creation')
96
+ .option('--dry-run', 'Show what would be done without making changes')
97
+ .option('-f, --force', 'Remove even if not configured')
98
+ .action(uninstallCommand);
99
+ // MCP Uninstall alias - same as uninstall but for consistency with mcp-install
100
+ program
101
+ .command('mcp-uninstall')
102
+ .description('Remove APIClaw from Claude Desktop or Claude Code MCP config')
103
+ .option('-c, --client <client>', 'Target specific client (claude-desktop, claude-code)')
104
+ .option('--dry-run', 'Show what would be done without making changes')
105
+ .action(uninstallCommand);
106
+ // Parse and execute
107
+ program.parse();
108
+ // Show help if no command provided
109
+ if (!process.argv.slice(2).length) {
110
+ program.outputHelp();
111
+ }
@@ -0,0 +1,302 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * APIClaw Interactive CLI
4
+ * Run with: npx @nordsym/apiclaw --cli
5
+ */
6
+ import * as readline from 'readline';
7
+ import { ConvexHttpClient } from 'convex/browser';
8
+ import { discoverAPIs } from './discovery.js';
9
+ import { executeAPICall, getConnectedProviders } from './execute.js';
10
+ import { readSession, writeSession, clearSession, getMachineFingerprint } from './session.js';
11
+ const CONVEX_URL = process.env.CONVEX_URL || 'https://adventurous-avocet-799.convex.cloud';
12
+ const convex = new ConvexHttpClient(CONVEX_URL);
13
+ // Colors for terminal
14
+ const colors = {
15
+ reset: '\x1b[0m',
16
+ bright: '\x1b[1m',
17
+ red: '\x1b[31m',
18
+ green: '\x1b[32m',
19
+ yellow: '\x1b[33m',
20
+ blue: '\x1b[34m',
21
+ magenta: '\x1b[35m',
22
+ cyan: '\x1b[36m',
23
+ };
24
+ function log(msg) {
25
+ console.log(msg);
26
+ }
27
+ function success(msg) {
28
+ console.log(`${colors.green}✓${colors.reset} ${msg}`);
29
+ }
30
+ function error(msg) {
31
+ console.log(`${colors.red}✗${colors.reset} ${msg}`);
32
+ }
33
+ function info(msg) {
34
+ console.log(`${colors.cyan}ℹ${colors.reset} ${msg}`);
35
+ }
36
+ let workspaceContext = null;
37
+ async function validateSession() {
38
+ const session = readSession();
39
+ if (!session)
40
+ return false;
41
+ try {
42
+ const result = await convex.query("workspaces:getWorkspaceStatus", {
43
+ sessionToken: session.sessionToken,
44
+ });
45
+ if (!result?.authenticated || result?.status !== 'active') {
46
+ clearSession();
47
+ return false;
48
+ }
49
+ workspaceContext = {
50
+ sessionToken: session.sessionToken,
51
+ workspaceId: session.workspaceId,
52
+ email: result.email ?? '',
53
+ tier: result.tier ?? 'free',
54
+ usageRemaining: result.usageRemaining ?? 0,
55
+ };
56
+ return true;
57
+ }
58
+ catch {
59
+ return false;
60
+ }
61
+ }
62
+ async function registerOwner(email) {
63
+ info(`Sending magic link to ${email}...`);
64
+ try {
65
+ const fingerprint = getMachineFingerprint();
66
+ // Use HTTP endpoint for magic link
67
+ const response = await fetch(`${CONVEX_URL.replace('.cloud', '.site')}/workspace/magic-link`, {
68
+ method: 'POST',
69
+ headers: { 'Content-Type': 'application/json' },
70
+ body: JSON.stringify({ email, fingerprint }),
71
+ });
72
+ const result = await response.json();
73
+ if (result?.success && result?.token) {
74
+ success(`Magic link sent to ${email}`);
75
+ log(`\n📧 Check your email and click the link to authenticate.`);
76
+ // Start polling for verification
77
+ log(`\n⏳ Waiting for you to click the link...`);
78
+ log(` (Press Ctrl+C to cancel)\n`);
79
+ await pollForVerification(result.token, fingerprint);
80
+ }
81
+ else {
82
+ error(`Failed: ${result?.error || 'Unknown error'}`);
83
+ }
84
+ }
85
+ catch (err) {
86
+ error(`Failed: ${err instanceof Error ? err.message : 'Unknown error'}`);
87
+ }
88
+ }
89
+ async function pollForVerification(token, fingerprint) {
90
+ const maxAttempts = 60; // 5 minutes
91
+ for (let i = 0; i < maxAttempts; i++) {
92
+ await new Promise(r => setTimeout(r, 5000)); // Poll every 5 seconds
93
+ try {
94
+ const response = await fetch(`${CONVEX_URL.replace('.cloud', '.site')}/workspace/poll?token=${token}`);
95
+ const result = await response.json();
96
+ if (result?.verified && result?.sessionToken) {
97
+ // Save the real session
98
+ writeSession(result.sessionToken, result.workspaceId || '', result.email || '');
99
+ success(`Authenticated as ${result.email}!`);
100
+ // Reload workspace context
101
+ await validateSession();
102
+ return;
103
+ }
104
+ }
105
+ catch {
106
+ // Continue polling
107
+ }
108
+ // Show progress dot
109
+ process.stdout.write('.');
110
+ }
111
+ log('\n');
112
+ error('Verification timed out. Please try again.');
113
+ }
114
+ async function showStatus() {
115
+ const valid = await validateSession();
116
+ log(`\n${colors.bright}APIClaw Status${colors.reset}`);
117
+ log(`${'─'.repeat(40)}`);
118
+ if (valid && workspaceContext) {
119
+ success(`Authenticated as ${workspaceContext.email}`);
120
+ log(` Tier: ${workspaceContext.tier}`);
121
+ log(` Remaining calls: ${workspaceContext.usageRemaining}`);
122
+ }
123
+ else {
124
+ error(`Not authenticated`);
125
+ log(` Run: ${colors.cyan}register <email>${colors.reset}`);
126
+ }
127
+ log('');
128
+ }
129
+ async function discover(query) {
130
+ info(`Searching for: "${query}"`);
131
+ try {
132
+ const results = discoverAPIs(query, { maxResults: 5 });
133
+ if (!results || results.length === 0) {
134
+ log(`No APIs found for "${query}"`);
135
+ return;
136
+ }
137
+ log(`\n${colors.bright}Found ${results.length} APIs:${colors.reset}\n`);
138
+ // Get connected providers for Direct Call detection
139
+ const connected = getConnectedProviders().map(p => p.provider.toLowerCase());
140
+ for (const result of results) {
141
+ const api = result.provider;
142
+ const isDirectCall = connected.includes(api.id?.toLowerCase() || api.name.toLowerCase().replace(/\s+/g, '_'));
143
+ const directCallBadge = isDirectCall ? `${colors.green}[Direct Call]${colors.reset}` : '';
144
+ log(`${colors.cyan}${api.name}${colors.reset} ${directCallBadge}`);
145
+ log(` ${api.description}`);
146
+ log(` Category: ${api.category}`);
147
+ log(` Pricing: ${api.pricing?.model || 'See docs'}`);
148
+ log('');
149
+ }
150
+ }
151
+ catch (err) {
152
+ error(`Search failed: ${err instanceof Error ? err.message : 'Unknown error'}`);
153
+ }
154
+ }
155
+ async function listConnected() {
156
+ try {
157
+ const providers = getConnectedProviders();
158
+ log(`\n${colors.bright}Direct Call Providers (no API key needed):${colors.reset}\n`);
159
+ for (const p of providers) {
160
+ log(`${colors.cyan}${p.provider}${colors.reset}`);
161
+ log(` Actions: ${p.actions?.join(', ') || 'See docs'}`);
162
+ log('');
163
+ }
164
+ }
165
+ catch (err) {
166
+ error(`Failed: ${err instanceof Error ? err.message : 'Unknown error'}`);
167
+ }
168
+ }
169
+ async function callApi(provider, action, params) {
170
+ if (!workspaceContext) {
171
+ error('Not authenticated. Run: register <email>');
172
+ return;
173
+ }
174
+ info(`Calling ${provider}.${action}...`);
175
+ try {
176
+ const result = await executeAPICall(provider, action, params, workspaceContext.workspaceId);
177
+ log(`\n${colors.bright}Result:${colors.reset}\n`);
178
+ log(JSON.stringify(result, null, 2));
179
+ log('');
180
+ }
181
+ catch (err) {
182
+ error(`Call failed: ${err instanceof Error ? err.message : 'Unknown error'}`);
183
+ }
184
+ }
185
+ function showHelp() {
186
+ log(`
187
+ ${colors.bright}🦞 APIClaw CLI${colors.reset}
188
+
189
+ ${colors.cyan}Commands:${colors.reset}
190
+ register <email> Send magic link to authenticate
191
+ status Check authentication status
192
+ discover <query> Search for APIs by capability
193
+ list Show Direct Call providers
194
+ call <provider> <action> <json-params>
195
+ Call an API (e.g., call brave_search search {"q":"test"})
196
+ help Show this help
197
+ exit Quit
198
+
199
+ ${colors.cyan}Examples:${colors.reset}
200
+ discover send SMS
201
+ discover image generation
202
+ list
203
+ call brave_search search {"q":"hello world"}
204
+ `);
205
+ }
206
+ function parseCallCommand(args) {
207
+ // Format: provider action {json}
208
+ const match = args.match(/^(\S+)\s+(\S+)\s+(.+)$/);
209
+ if (!match)
210
+ return null;
211
+ try {
212
+ const params = JSON.parse(match[3]);
213
+ return { provider: match[1], action: match[2], params };
214
+ }
215
+ catch {
216
+ return null;
217
+ }
218
+ }
219
+ export async function startCLI() {
220
+ log(`
221
+ ${colors.bright}🦞 APIClaw CLI v1.1.5${colors.reset}
222
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
223
+
224
+ Type ${colors.cyan}help${colors.reset} for commands, ${colors.cyan}exit${colors.reset} to quit.
225
+ `);
226
+ // Check session on startup
227
+ const valid = await validateSession();
228
+ if (valid && workspaceContext) {
229
+ success(`Authenticated as ${workspaceContext.email}`);
230
+ }
231
+ else {
232
+ info(`Not authenticated. Run: ${colors.cyan}register <email>${colors.reset}`);
233
+ }
234
+ log('');
235
+ const rl = readline.createInterface({
236
+ input: process.stdin,
237
+ output: process.stdout,
238
+ prompt: `${colors.red}apiclaw${colors.reset}> `,
239
+ });
240
+ rl.prompt();
241
+ rl.on('line', async (line) => {
242
+ const input = line.trim();
243
+ const [cmd, ...args] = input.split(/\s+/);
244
+ const argsStr = args.join(' ');
245
+ switch (cmd.toLowerCase()) {
246
+ case '':
247
+ break;
248
+ case 'help':
249
+ case '?':
250
+ showHelp();
251
+ break;
252
+ case 'exit':
253
+ case 'quit':
254
+ case 'q':
255
+ log('Bye! 🦞');
256
+ process.exit(0);
257
+ break;
258
+ case 'register':
259
+ if (!argsStr) {
260
+ error('Usage: register <email>');
261
+ }
262
+ else {
263
+ await registerOwner(argsStr);
264
+ }
265
+ break;
266
+ case 'status':
267
+ await showStatus();
268
+ break;
269
+ case 'discover':
270
+ case 'search':
271
+ if (!argsStr) {
272
+ error('Usage: discover <query>');
273
+ }
274
+ else {
275
+ await discover(argsStr);
276
+ }
277
+ break;
278
+ case 'list':
279
+ case 'connected':
280
+ await listConnected();
281
+ break;
282
+ case 'call':
283
+ const parsed = parseCallCommand(argsStr);
284
+ if (!parsed) {
285
+ error('Usage: call <provider> <action> {"param":"value"}');
286
+ log('Example: call brave_search search {"q":"hello"}');
287
+ }
288
+ else {
289
+ await callApi(parsed.provider, parsed.action, parsed.params);
290
+ }
291
+ break;
292
+ default:
293
+ error(`Unknown command: ${cmd}`);
294
+ log(`Type ${colors.cyan}help${colors.reset} for available commands.`);
295
+ }
296
+ rl.prompt();
297
+ });
298
+ rl.on('close', () => {
299
+ log('\nBye! 🦞');
300
+ process.exit(0);
301
+ });
302
+ }
@@ -0,0 +1,240 @@
1
+ /**
2
+ * APIClaw Confirmation System
3
+ * For actions that cost money or have side effects
4
+ *
5
+ * Flow:
6
+ * 1. Agent calls action → gets preview + token
7
+ * 2. Agent shows preview to user
8
+ * 3. User confirms → agent calls confirm with token
9
+ * 4. APIClaw executes the actual action
10
+ */
11
+ import { randomBytes } from 'crypto';
12
+ // In-memory store for pending confirmations (in production, use Redis)
13
+ const pendingActions = new Map();
14
+ // Actions that require confirmation before execution
15
+ export const CONFIRMATION_REQUIRED = {
16
+ // Invoicing - costs money per send
17
+ coaccept: ['send_invoice', 'send_reminder'],
18
+ // SMS - costs money per message
19
+ '46elks': ['send_sms'],
20
+ twilio: ['send_sms'],
21
+ // Email sends (less critical but still good to confirm)
22
+ resend: ['send_email'],
23
+ };
24
+ // Token expiry time (5 minutes)
25
+ const TOKEN_EXPIRY_MS = 5 * 60 * 1000;
26
+ /**
27
+ * Check if an action requires confirmation (hardcoded list only)
28
+ * For dynamic providers, use requiresConfirmationAsync
29
+ */
30
+ export function requiresConfirmation(provider, action) {
31
+ const actions = CONFIRMATION_REQUIRED[provider];
32
+ return actions?.includes(action) ?? false;
33
+ }
34
+ /**
35
+ * Check if a dynamic provider action requires confirmation
36
+ * This is imported dynamically to avoid circular deps
37
+ */
38
+ export async function requiresConfirmationAsync(provider, action) {
39
+ // First check hardcoded list
40
+ if (requiresConfirmation(provider, action)) {
41
+ return { required: true, isDynamic: false };
42
+ }
43
+ // Then check dynamic provider config
44
+ try {
45
+ const { getDynamicConfirmationConfig } = await import('./execute-dynamic.js');
46
+ const config = await getDynamicConfirmationConfig(provider, action);
47
+ if (config.required) {
48
+ return {
49
+ required: true,
50
+ estimatedCost: config.estimatedCost,
51
+ isDynamic: true
52
+ };
53
+ }
54
+ }
55
+ catch (e) {
56
+ // Dynamic config not available, that's ok
57
+ }
58
+ return { required: false };
59
+ }
60
+ /**
61
+ * Generate a confirmation token and store the pending action
62
+ */
63
+ export function createPendingAction(provider, action, params, preview, userId) {
64
+ // Clean up expired tokens
65
+ cleanupExpired();
66
+ const token = randomBytes(16).toString('hex');
67
+ const now = Date.now();
68
+ const pending = {
69
+ token,
70
+ provider,
71
+ action,
72
+ params,
73
+ preview,
74
+ createdAt: now,
75
+ expiresAt: now + TOKEN_EXPIRY_MS,
76
+ userId,
77
+ };
78
+ pendingActions.set(token, pending);
79
+ return pending;
80
+ }
81
+ /**
82
+ * Get a pending action by token (and validate it)
83
+ */
84
+ export function getPendingAction(token) {
85
+ const pending = pendingActions.get(token);
86
+ if (!pending) {
87
+ return null;
88
+ }
89
+ if (Date.now() > pending.expiresAt) {
90
+ pendingActions.delete(token);
91
+ return null;
92
+ }
93
+ return pending;
94
+ }
95
+ /**
96
+ * Consume a pending action (use it and remove from store)
97
+ */
98
+ export function consumePendingAction(token) {
99
+ const pending = getPendingAction(token);
100
+ if (pending) {
101
+ pendingActions.delete(token);
102
+ }
103
+ return pending;
104
+ }
105
+ /**
106
+ * Clean up expired tokens
107
+ */
108
+ function cleanupExpired() {
109
+ const now = Date.now();
110
+ for (const [token, pending] of pendingActions.entries()) {
111
+ if (now > pending.expiresAt) {
112
+ pendingActions.delete(token);
113
+ }
114
+ }
115
+ }
116
+ /**
117
+ * Generate a human-readable preview for an action
118
+ */
119
+ export function generatePreview(provider, action, params) {
120
+ // Provider-specific preview generators
121
+ switch (provider) {
122
+ case 'coaccept':
123
+ return generateCoAcceptPreview(action, params);
124
+ case '46elks':
125
+ case 'twilio':
126
+ return generateSMSPreview(params);
127
+ case 'resend':
128
+ return generateEmailPreview(params);
129
+ default:
130
+ return { action, params };
131
+ }
132
+ }
133
+ function generateCoAcceptPreview(action, params) {
134
+ if (action === 'send_invoice') {
135
+ const items = params.items || [];
136
+ const totalAmount = items.reduce((sum, item) => sum + (item.amount || 0), 0);
137
+ return {
138
+ type: 'invoice',
139
+ recipient: {
140
+ name: params.recipient_name,
141
+ email: params.recipient_email,
142
+ org_number: params.recipient_org_nr,
143
+ },
144
+ amount: {
145
+ subtotal: totalAmount,
146
+ vat_rate: params.vat_rate || 25,
147
+ vat_amount: totalAmount * ((params.vat_rate || 25) / 100),
148
+ total: totalAmount * (1 + (params.vat_rate || 25) / 100),
149
+ currency: params.currency || 'SEK',
150
+ },
151
+ due_date: params.due_date,
152
+ items: items.map((item) => ({
153
+ description: item.description,
154
+ quantity: item.quantity || 1,
155
+ unit_price: item.unit_price || item.amount,
156
+ amount: item.amount,
157
+ })),
158
+ payment_method: 'SMS + Swish/Card (CoAccept)',
159
+ estimated_cost: '~2-5 SEK per invoice',
160
+ };
161
+ }
162
+ return { action, params };
163
+ }
164
+ function generateSMSPreview(params) {
165
+ const messageLength = (params.message || '').length;
166
+ const segments = Math.ceil(messageLength / 160);
167
+ return {
168
+ type: 'sms',
169
+ to: params.to,
170
+ from: params.from || 'NordSym',
171
+ message: params.message,
172
+ message_length: messageLength,
173
+ segments,
174
+ estimated_cost: `~${(segments * 0.35).toFixed(2)} SEK`,
175
+ };
176
+ }
177
+ function generateEmailPreview(params) {
178
+ return {
179
+ type: 'email',
180
+ to: params.to,
181
+ from: params.from || 'noreply@nordsym.com',
182
+ subject: params.subject,
183
+ preview: (params.message || params.html || '').substring(0, 200) + '...',
184
+ };
185
+ }
186
+ /**
187
+ * Validate params before creating preview
188
+ * Returns { valid: true } or { valid: false, errors: [...] }
189
+ */
190
+ export function validateParams(provider, action, params) {
191
+ const errors = [];
192
+ switch (provider) {
193
+ case 'coaccept':
194
+ if (action === 'send_invoice') {
195
+ if (!params.recipient_name)
196
+ errors.push('Missing: recipient_name');
197
+ if (!params.recipient_email)
198
+ errors.push('Missing: recipient_email');
199
+ if (!params.items || !Array.isArray(params.items) || params.items.length === 0) {
200
+ errors.push('Missing: items (at least one invoice item required)');
201
+ }
202
+ if (!params.due_date)
203
+ errors.push('Missing: due_date (YYYY-MM-DD)');
204
+ // Validate email format
205
+ if (params.recipient_email && !params.recipient_email.includes('@')) {
206
+ errors.push('Invalid: recipient_email format');
207
+ }
208
+ // Validate due date is not in past
209
+ if (params.due_date) {
210
+ const dueDate = new Date(params.due_date);
211
+ const today = new Date();
212
+ today.setHours(0, 0, 0, 0);
213
+ if (dueDate < today) {
214
+ errors.push('Invalid: due_date cannot be in the past');
215
+ }
216
+ }
217
+ }
218
+ break;
219
+ case '46elks':
220
+ case 'twilio':
221
+ if (!params.to)
222
+ errors.push('Missing: to (phone number)');
223
+ if (!params.message)
224
+ errors.push('Missing: message');
225
+ // Validate phone format (basic check)
226
+ if (params.to && !params.to.startsWith('+')) {
227
+ errors.push('Invalid: phone number must start with + (e.g., +46701234567)');
228
+ }
229
+ break;
230
+ case 'resend':
231
+ if (!params.to)
232
+ errors.push('Missing: to (email address)');
233
+ if (!params.subject)
234
+ errors.push('Missing: subject');
235
+ if (!params.message && !params.html)
236
+ errors.push('Missing: message or html content');
237
+ break;
238
+ }
239
+ return errors.length > 0 ? { valid: false, errors } : { valid: true };
240
+ }