@l4yercak3/cli 1.0.0

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 (61) hide show
  1. package/.claude/settings.local.json +18 -0
  2. package/.cursor/rules.md +203 -0
  3. package/.eslintrc.js +31 -0
  4. package/README.md +227 -0
  5. package/bin/cli.js +61 -0
  6. package/docs/ADDING_NEW_PROJECT_TYPE.md +156 -0
  7. package/docs/ARCHITECTURE_RELATIONSHIPS.md +411 -0
  8. package/docs/CLI_AUTHENTICATION.md +214 -0
  9. package/docs/DETECTOR_ARCHITECTURE.md +326 -0
  10. package/docs/DEVELOPMENT.md +194 -0
  11. package/docs/IMPLEMENTATION_PHASES.md +468 -0
  12. package/docs/OAUTH_CLARIFICATION.md +258 -0
  13. package/docs/OAUTH_SETUP_GUIDE_TEMPLATE.md +211 -0
  14. package/docs/PHASE_0_PROGRESS.md +120 -0
  15. package/docs/PHASE_1_COMPLETE.md +366 -0
  16. package/docs/PHASE_SUMMARY.md +149 -0
  17. package/docs/PLAN.md +511 -0
  18. package/docs/README.md +56 -0
  19. package/docs/STRIPE_INTEGRATION.md +447 -0
  20. package/docs/SUMMARY.md +230 -0
  21. package/docs/UPDATED_PLAN.md +447 -0
  22. package/package.json +53 -0
  23. package/src/api/backend-client.js +148 -0
  24. package/src/commands/login.js +146 -0
  25. package/src/commands/logout.js +24 -0
  26. package/src/commands/spread.js +364 -0
  27. package/src/commands/status.js +62 -0
  28. package/src/config/config-manager.js +205 -0
  29. package/src/detectors/api-client-detector.js +85 -0
  30. package/src/detectors/base-detector.js +77 -0
  31. package/src/detectors/github-detector.js +74 -0
  32. package/src/detectors/index.js +80 -0
  33. package/src/detectors/nextjs-detector.js +139 -0
  34. package/src/detectors/oauth-detector.js +122 -0
  35. package/src/detectors/registry.js +97 -0
  36. package/src/generators/api-client-generator.js +197 -0
  37. package/src/generators/env-generator.js +162 -0
  38. package/src/generators/gitignore-generator.js +92 -0
  39. package/src/generators/index.js +50 -0
  40. package/src/generators/nextauth-generator.js +242 -0
  41. package/src/generators/oauth-guide-generator.js +277 -0
  42. package/src/logo.js +116 -0
  43. package/tests/api-client-detector.test.js +214 -0
  44. package/tests/api-client-generator.test.js +169 -0
  45. package/tests/backend-client.test.js +361 -0
  46. package/tests/base-detector.test.js +101 -0
  47. package/tests/commands/login.test.js +98 -0
  48. package/tests/commands/logout.test.js +70 -0
  49. package/tests/commands/status.test.js +167 -0
  50. package/tests/config-manager.test.js +313 -0
  51. package/tests/detector-index.test.js +209 -0
  52. package/tests/detector-registry.test.js +93 -0
  53. package/tests/env-generator.test.js +278 -0
  54. package/tests/generators-index.test.js +215 -0
  55. package/tests/github-detector.test.js +145 -0
  56. package/tests/gitignore-generator.test.js +109 -0
  57. package/tests/logo.test.js +96 -0
  58. package/tests/nextauth-generator.test.js +231 -0
  59. package/tests/nextjs-detector.test.js +235 -0
  60. package/tests/oauth-detector.test.js +264 -0
  61. package/tests/oauth-guide-generator.test.js +273 -0
@@ -0,0 +1,447 @@
1
+ # 🍰 L4YERCAK3 CLI Tool - Updated Strategic Plan
2
+
3
+ ## Executive Summary
4
+
5
+ Based on new information about backend capabilities and publishing ontology, this updated plan refines the CLI tool strategy with a focus on **maximum automation** and **one-click integration**.
6
+
7
+ ---
8
+
9
+ ## Key Updates
10
+
11
+ ### ✅ API Key Generation
12
+ - **Status:** Can be implemented via backend API
13
+ - **Action:** Create `POST /api/v1/api-keys/generate` endpoint
14
+ - **CLI Integration:** CLI will call this endpoint to generate API keys automatically
15
+
16
+ ### ✅ OAuth Automation - CLARIFIED
17
+ - **What We're Automating:** Frontend OAuth (customer login), NOT backend OAuth
18
+ - **Strategy:** Use Google Cloud API, Microsoft Graph API, GitHub API to create OAuth apps
19
+ - **User Input Required:** One-time permission grant to create OAuth apps
20
+ - **Result:** OAuth credentials automatically generated and saved to `.env.local`
21
+ - **Business Value:** More automation = higher pricing potential
22
+ - **See:** `docs/OAUTH_CLARIFICATION.md` for detailed explanation
23
+
24
+ ### ✅ TypeScript Types Generation - CLARIFIED
25
+ - **Approach:** Schema endpoint that returns API structure (OpenAPI/JSON Schema)
26
+ - **Security:** Read-only, requires authentication, NO database access
27
+ - **What It Returns:** API endpoint definitions, request/response types
28
+ - **Example:** Like OpenAPI spec - just describes API structure
29
+ - **Implementation:** `GET /api/v1/schema` endpoint (needs to be created)
30
+
31
+ ### ✅ Publishing Ontology Integration
32
+ - **Location:** `vc83-com/convex/publishingOntology.ts`
33
+ - **Key Features:**
34
+ - Auto-detect env vars from GitHub repos
35
+ - Deployment configuration management
36
+ - Environment variable storage
37
+ - **CLI Integration:** Use for env var detection and template discovery
38
+
39
+ ---
40
+
41
+ ## Enhanced Integration Workflow
42
+
43
+ ### One-Click Integration Flow
44
+
45
+ ```
46
+ 1. Developer runs: npx @l4yercak3/cli spread
47
+
48
+ 2. CLI detects project type (Next.js, etc.)
49
+
50
+ 3. CLI checks if GitHub repo exists
51
+
52
+ 4. If GitHub repo found:
53
+ - Auto-detect env vars from .env.example
54
+ - Pre-fill deployment configuration
55
+
56
+ 5. Interactive setup (minimal):
57
+ - Backend API URL (auto-detect if possible)
58
+ - Organization selection/login
59
+ - Features to enable (CRM, Projects, Invoices, OAuth, Stripe)
60
+
61
+ 6. CLI automates:
62
+ - Generate API key via backend API
63
+ - Create OAuth apps (where possible)
64
+ - Generate callback URLs
65
+ - Create published page config (if using publishing ontology)
66
+
67
+ 7. CLI generates:
68
+ - API client code with TypeScript types
69
+ - Environment files (.env.local)
70
+ - NextAuth.js configuration (if OAuth enabled)
71
+ - Stripe webhook handler (if Stripe enabled)
72
+ - Type definitions
73
+
74
+ 8. Developer fills in any remaining OAuth credentials (if not automated)
75
+
76
+ 9. Integration complete! 🎉
77
+ ```
78
+
79
+ ---
80
+
81
+ ## Publishing Ontology Integration Strategy
82
+
83
+ ### How CLI Uses Publishing Ontology
84
+
85
+ #### 1. **Environment Variable Detection**
86
+ ```javascript
87
+ // CLI can call backend action
88
+ const envVars = await backendClient.autoDetectEnvVarsFromGithub({
89
+ githubUrl: 'https://github.com/user/repo'
90
+ });
91
+
92
+ // Returns:
93
+ // {
94
+ // success: true,
95
+ // foundFile: '.env.example',
96
+ // envVars: [
97
+ // { key: 'NEXT_PUBLIC_API_URL', description: '...', required: true },
98
+ // { key: 'API_KEY', description: '...', required: true }
99
+ // ]
100
+ // }
101
+ ```
102
+
103
+ **Benefits:**
104
+ - Automatically detect required env vars from template repos
105
+ - Pre-fill environment file templates
106
+ - Reduce setup friction
107
+
108
+ #### 2. **Deployment Configuration**
109
+ ```javascript
110
+ // CLI can read existing deployment config
111
+ const deployment = await backendClient.getDeploymentEnvVars({
112
+ pageId: 'published_page_id'
113
+ });
114
+
115
+ // Use this to pre-fill env vars if page already exists
116
+ ```
117
+
118
+ #### 3. **Template Discovery**
119
+ - CLI can query published pages to discover available templates
120
+ - Use template configs to generate appropriate code
121
+ - Link frontend projects to published page configs
122
+
123
+ ---
124
+
125
+ ## Enhanced Feature Roadmap
126
+
127
+ ### Phase 1: Core Integration (MVP) 🎯
128
+
129
+ #### 1.1 Project Detection & Analysis
130
+ - [x] Detect Next.js projects
131
+ - [ ] Detect GitHub repository (from git remote)
132
+ - [ ] Detect existing API client patterns
133
+ - [ ] Detect existing OAuth setup
134
+ - [ ] **NEW:** Auto-detect env vars from GitHub repo
135
+
136
+ #### 1.2 Configuration Wizard (Minimal Input)
137
+ - [ ] **NEW:** Account creation (if no account exists)
138
+ - [ ] **NEW:** Organization type selection (agency vs regular)
139
+ - [ ] **NEW:** Sub-organization creation (if agency)
140
+ - [ ] Backend API URL (with auto-detection)
141
+ - [ ] Organization login/selection (or use newly created)
142
+ - [ ] Features to enable (CRM, Projects, Invoices, OAuth, Stripe)
143
+ - [ ] **NEW:** Use publishing ontology to pre-fill env vars
144
+
145
+ #### 1.3 Automated Setup
146
+ - [ ] **NEW:** Create user account + organization via backend API
147
+ - [ ] **NEW:** Generate API key via backend API (or use existing)
148
+ - [ ] **NEW:** Create OAuth apps programmatically (Google/Microsoft/GitHub APIs)
149
+ - [ ] **NEW:** Request user permission for OAuth app creation (one-time)
150
+ - [ ] Generate OAuth callback URLs automatically
151
+ - [ ] **NEW:** Create/update published page config
152
+
153
+ #### 1.4 File Generation
154
+ - [ ] Generate API client with TypeScript types
155
+ - Scoped to Sub-Organization (for agencies) or Organization (for regular)
156
+ - NOT scoped to CRM Organization (CRM Org is customer data, not platform org)
157
+ - [ ] Generate `.env.local` with detected/pre-filled values
158
+ - [ ] Generate NextAuth.js configuration (if OAuth enabled)
159
+ - Creates frontend_users linked to crm_contacts
160
+ - Scoped to Sub-Organization or Organization
161
+ - All user management in backend
162
+ - [ ] Generate Stripe webhook handler (if Stripe enabled)
163
+ - [ ] **NEW:** Generate Stripe onboarding page
164
+ - For Sub-Organization (if agency) or Organization (if regular)
165
+ - Customer-facing, simple UI
166
+ - Uses Sub-Org's or Org's API key
167
+ - [ ] Generate TypeScript type definitions
168
+
169
+ ### Phase 2: Advanced Automation 🚀
170
+
171
+ #### 2.1 Stripe Integration
172
+ - [ ] **Stripe Connect OAuth:** Initiate Stripe Connect onboarding
173
+ - [ ] **Customer-Facing Onboarding:** Generate simple UI for Sub-Organization/Organization to onboard themselves
174
+ - **CRITICAL:** Agencies cannot onboard Sub-Organizations (legal requirement)
175
+ - Sub-Organizations must complete OAuth flow themselves
176
+ - **NOTE:** CRM Organizations do NOT have Stripe accounts (they're customer data)
177
+ - [ ] **Webhook Setup:** Create webhook endpoints via Stripe API
178
+ - [ ] **Environment Variables:** Auto-detect and configure Stripe keys
179
+ - [ ] **Code Generation:** Generate webhook handlers and Stripe utilities
180
+ - [ ] **Agency Support:** Handle Sub-Organization Stripe setup (customer self-service)
181
+
182
+ #### 2.2 OAuth Automation
183
+ - [ ] **Google OAuth:** Use Google Cloud API to create OAuth apps
184
+ - [ ] **Microsoft OAuth:** Use Azure AD API to create OAuth apps
185
+ - [ ] **GitHub OAuth:** Use GitHub API to create OAuth apps
186
+ - [ ] Store OAuth credentials securely
187
+ - [ ] Test OAuth flow automatically
188
+
189
+ #### 2.3 Publishing Ontology Integration
190
+ - [ ] Create published page configs automatically
191
+ - [ ] Link frontend projects to published pages
192
+ - [ ] Sync deployment configurations
193
+ - [ ] Manage environment variables via publishing ontology
194
+
195
+ #### 2.4 TypeScript Types
196
+ - [ ] **Option A:** Fetch schema from backend endpoint
197
+ - [ ] **Option B:** Maintain types manually based on API docs
198
+ - [ ] Generate type definitions from schema/types
199
+ - [ ] Keep types in sync with backend changes
200
+
201
+ ### Phase 3: One-Click Experience ✨
202
+
203
+ #### 3.1 Intelligent Defaults
204
+ - [ ] Auto-detect backend URL from organization
205
+ - [ ] Auto-select features based on project type
206
+ - [ ] Auto-configure OAuth based on organization settings
207
+ - [ ] Auto-generate all possible configurations
208
+
209
+ #### 3.2 Template Integration
210
+ - [ ] Discover templates from publishing ontology
211
+ - [ ] Generate code based on template configs
212
+ - [ ] Link projects to template pages
213
+ - [ ] Sync template updates
214
+
215
+ #### 3.3 Zero-Config Mode
216
+ - [ ] `l4yercak3 spread --auto` - fully automated setup
217
+ - [ ] `l4yercak3 spread --template <name>` - use template
218
+ - [ ] `l4yercak3 spread --github <url>` - auto-detect from GitHub
219
+
220
+ ---
221
+
222
+ ## Technical Implementation Details
223
+
224
+ ### Backend API Endpoints Needed
225
+
226
+ #### 1. Account Creation
227
+ ```typescript
228
+ POST /api/v1/auth/create-account
229
+ Body: {
230
+ email: string;
231
+ name: string;
232
+ organizationName: string;
233
+ }
234
+ Response: {
235
+ userId: string;
236
+ organizationId: string;
237
+ apiKey: string; // Auto-generated
238
+ sessionToken: string; // For CLI to use
239
+ }
240
+ ```
241
+
242
+ #### 2. API Key Generation
243
+ ```typescript
244
+ POST /api/v1/api-keys/generate
245
+ Authorization: Bearer <user_session_token>
246
+ Body: {
247
+ name: string;
248
+ scopes?: string[];
249
+ }
250
+ Response: {
251
+ apiKey: string;
252
+ keyPrefix: string;
253
+ createdAt: number;
254
+ }
255
+ ```
256
+
257
+ #### 3. OAuth App Creation
258
+ **Note:** This happens via provider APIs (Google Cloud, Microsoft Graph, GitHub), not backend API.
259
+ CLI uses provider APIs directly with user's permission.
260
+
261
+ #### 4. Stripe Integration
262
+ ```typescript
263
+ POST /api/v1/stripe/start-onboarding
264
+ Authorization: Bearer <api_key>
265
+ Body: {
266
+ returnUrl: string;
267
+ refreshUrl: string;
268
+ isTestMode?: boolean;
269
+ }
270
+ Response: {
271
+ onboardingUrl: string;
272
+ state: string;
273
+ }
274
+
275
+ GET /api/v1/stripe/status
276
+ Authorization: Bearer <api_key>
277
+ Response: {
278
+ isConnected: boolean;
279
+ accountId?: string;
280
+ status: string;
281
+ publishableKey?: string;
282
+ }
283
+
284
+ GET /api/v1/stripe/keys
285
+ Authorization: Bearer <api_key>
286
+ Response: {
287
+ publishableKey: string;
288
+ }
289
+ ```
290
+
291
+ #### 5. Schema/Type Definitions
292
+ ```typescript
293
+ GET /api/v1/schema
294
+ Response: {
295
+ // OpenAPI spec or JSON Schema
296
+ // Or TypeScript type definitions
297
+ }
298
+ ```
299
+
300
+ ### CLI Backend Client
301
+
302
+ ```javascript
303
+ // src/api/backend-client.js
304
+ class BackendClient {
305
+ constructor(apiUrl, apiKey) {
306
+ this.apiUrl = apiUrl;
307
+ this.apiKey = apiKey;
308
+ }
309
+
310
+ // Generate API key
311
+ async generateApiKey(name, scopes) {
312
+ // Call POST /api/v1/api-keys/generate
313
+ }
314
+
315
+ // Auto-detect env vars from GitHub
316
+ async autoDetectEnvVars(githubUrl) {
317
+ // Call publishing ontology action
318
+ }
319
+
320
+ // Create OAuth app via provider APIs
321
+ async createOAuthApp(provider, config) {
322
+ // Use Google Cloud API / Microsoft Graph API / GitHub API
323
+ // Requires user permission (one-time grant)
324
+ }
325
+
326
+ // Create account
327
+ async createAccount(email, name, orgName) {
328
+ // Call POST /api/v1/auth/create-account
329
+ }
330
+
331
+ // Get schema/types
332
+ async getSchema() {
333
+ // Call schema endpoint
334
+ }
335
+
336
+ // Stripe integration
337
+ async startStripeOnboarding(returnUrl, refreshUrl, isTestMode) {
338
+ // Call POST /api/v1/stripe/start-onboarding
339
+ }
340
+
341
+ async getStripeStatus() {
342
+ // Call GET /api/v1/stripe/status
343
+ }
344
+
345
+ async getStripeKeys() {
346
+ // Call GET /api/v1/stripe/keys
347
+ }
348
+ }
349
+ ```
350
+
351
+ ---
352
+
353
+ ## Updated Success Metrics
354
+
355
+ ### Automation Metrics
356
+ - **Setup Time:** Target < 2 minutes from `npx @l4yercak3/cli spread` to working integration
357
+ - **Manual Steps:** Target < 3 manual inputs required
358
+ - **OAuth Automation:** Target 80%+ of OAuth setups fully automated
359
+ - **Env Var Detection:** Target 90%+ accuracy in auto-detection
360
+
361
+ ### Developer Experience Metrics
362
+ - **One-Click Success Rate:** % of integrations completed with `--auto` flag
363
+ - **Error Rate:** < 5% of integrations require manual troubleshooting
364
+ - **Documentation Views:** Track which docs are needed most
365
+
366
+ ---
367
+
368
+ ## Next Steps
369
+
370
+ ### Immediate (This Week)
371
+ 1. **Backend Team:**
372
+ - [ ] Create API key generation endpoint
373
+ - [ ] Document OAuth app creation APIs (if available)
374
+ - [ ] Clarify TypeScript types approach (schema endpoint vs manual)
375
+
376
+ 2. **CLI Team:**
377
+ - [ ] Implement GitHub repo detection
378
+ - [ ] Integrate publishing ontology env var detection
379
+ - [ ] Build backend API client for CLI
380
+
381
+ ### Short-term (Next 2 Weeks)
382
+ 1. **OAuth Automation Research:**
383
+ - [ ] Research Google Cloud API for OAuth app creation
384
+ - [ ] Research Microsoft Graph API for OAuth app creation
385
+ - [ ] Research GitHub API for OAuth app creation
386
+ - [ ] Document automation possibilities
387
+
388
+ 2. **TypeScript Types:**
389
+ - [ ] Implement schema fetching (if endpoint available)
390
+ - [ ] Or create manual type definitions based on API docs
391
+ - [ ] Build type generation system
392
+
393
+ ### Medium-term (Next Month)
394
+ 1. **One-Click Integration:**
395
+ - [ ] Implement `--auto` flag
396
+ - [ ] Reduce manual inputs to minimum
397
+ - [ ] Test with real projects
398
+
399
+ ---
400
+
401
+ ## Questions for Backend Team
402
+
403
+ 1. ✅ **TypeScript Types:** CLARIFIED - Schema endpoint preferred (read-only API structure)
404
+ - **Action:** Create `GET /api/v1/schema` endpoint
405
+ - **Security:** Requires auth, read-only, no database access
406
+
407
+ 2. ✅ **OAuth App Creation:** CLARIFIED - Use provider APIs directly
408
+ - Google Cloud API ✅
409
+ - Microsoft Graph API ✅
410
+ - GitHub API ✅
411
+ - **Action:** Research provider APIs, implement in CLI
412
+
413
+ 3. **Account Creation:** Can we create accounts via API?
414
+ - **Action:** Create `POST /api/v1/auth/create-account` endpoint
415
+ - **Returns:** User, org, API key, session token
416
+
417
+ 4. **API Key Generation:** Timeline for endpoint implementation?
418
+ - **Action:** Create `POST /api/v1/api-keys/generate` endpoint
419
+
420
+ 5. **Publishing Ontology:** Can CLI create/update published page configs during setup?
421
+ - **Action:** Verify CLI can call publishing ontology mutations
422
+
423
+ 6. ✅ **Stripe Integration:** CLARIFIED - Stripe Connect setup needed
424
+ - **Action:** Create Stripe API endpoints (start-onboarding, status, keys)
425
+ - **Action:** Implement Stripe webhook automation via Stripe API
426
+ - **CRITICAL:** Generate customer-facing Stripe onboarding page (for agencies)
427
+ - **Legal Requirement:** Customers must onboard themselves (agencies cannot)
428
+ - **See:** `docs/STRIPE_INTEGRATION.md` for detailed plan
429
+ - **See:** `docs/ARCHITECTURE_RELATIONSHIPS.md` for relationship hierarchy
430
+
431
+ 7. ✅ **User Management & Relationships:** CLARIFIED & CORRECTED
432
+ - **Backend Owns All:** Frontend users, CRM contacts managed in backend
433
+ - **Hierarchy (Agency):** Agency → Sub-Organization → CRM Organization → CRM Contacts/Frontend Users
434
+ - **Hierarchy (Regular):** Organization → CRM Organization → CRM Contacts/Frontend Users
435
+ - **Key Distinction:** CRM Organization = Customer data (NOT platform organization)
436
+ - **Sub-Organization:** Platform organization created by agency (the customer boilerplate is built FOR)
437
+ - **Authentication:** Creates frontend_users linked to crm_contacts automatically
438
+ - **Scoping:** Boilerplate scoped to Sub-Organization (for agencies) or Organization (for regular)
439
+ - **Stripe:** Sub-Organization or Organization owns Stripe account (NOT CRM Organization)
440
+ - **See:** `docs/ARCHITECTURE_RELATIONSHIPS_V2.md` for corrected complete picture
441
+
442
+ ---
443
+
444
+ **Last Updated:** 2025-01-14
445
+ **Status:** Updated with new information
446
+ **Next Review:** After backend team clarifications
447
+
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@l4yercak3/cli",
3
+ "version": "1.0.0",
4
+ "description": "Icing on the L4yercak3 - The sweet finishing touch for your Layer Cake integration",
5
+ "main": "src/index.js",
6
+ "bin": {
7
+ "l4yercak3": "./bin/cli.js",
8
+ "icing": "./bin/cli.js"
9
+ },
10
+ "scripts": {
11
+ "start": "node bin/cli.js",
12
+ "test": "jest",
13
+ "test:watch": "jest --watch",
14
+ "test:coverage": "jest --coverage",
15
+ "lint": "eslint . --ext .js",
16
+ "lint:fix": "eslint . --ext .js --fix",
17
+ "type-check": "node --check bin/cli.js && node --check src/logo.js",
18
+ "build": "echo \"Build check: verifying package structure\" && node -e \"console.log('✅ Package structure valid')\"",
19
+ "verify": "npm run lint && npm run type-check && npm run test && npm run build",
20
+ "prepublishOnly": "npm run verify"
21
+ },
22
+ "jest": {
23
+ "testEnvironment": "node",
24
+ "testMatch": ["**/tests/**/*.test.js"],
25
+ "collectCoverageFrom": ["src/**/*.js"],
26
+ "coveragePathIgnorePatterns": ["/node_modules/"]
27
+ },
28
+ "keywords": [
29
+ "l4yercak3",
30
+ "layer-cake",
31
+ "cli",
32
+ "backend",
33
+ "platform",
34
+ "integration"
35
+ ],
36
+ "author": "",
37
+ "license": "MIT",
38
+ "dependencies": {
39
+ "chalk": "^4.1.2",
40
+ "commander": "^14.0.2",
41
+ "figlet": "^1.7.0",
42
+ "inquirer": "^8.2.6",
43
+ "node-fetch": "^2.7.0",
44
+ "open": "^11.0.0"
45
+ },
46
+ "devDependencies": {
47
+ "eslint": "^8.57.0",
48
+ "jest": "^30.2.0"
49
+ },
50
+ "engines": {
51
+ "node": ">=14.0.0"
52
+ }
53
+ }
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Backend API Client
3
+ * Handles communication with L4YERCAK3 backend API
4
+ */
5
+
6
+ const fetch = require('node-fetch');
7
+ const configManager = require('../config/config-manager');
8
+
9
+ class BackendClient {
10
+ constructor() {
11
+ this.baseUrl = configManager.getBackendUrl();
12
+ }
13
+
14
+ /**
15
+ * Get headers for API requests
16
+ */
17
+ getHeaders() {
18
+ const session = configManager.getSession();
19
+ const headers = {
20
+ 'Content-Type': 'application/json',
21
+ };
22
+
23
+ if (session && session.token) {
24
+ headers['Authorization'] = `Bearer ${session.token}`;
25
+ }
26
+
27
+ return headers;
28
+ }
29
+
30
+ /**
31
+ * Make API request
32
+ */
33
+ async request(method, endpoint, data = null) {
34
+ const url = `${this.baseUrl}${endpoint}`;
35
+ const options = {
36
+ method,
37
+ headers: this.getHeaders(),
38
+ };
39
+
40
+ if (data && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
41
+ options.body = JSON.stringify(data);
42
+ }
43
+
44
+ try {
45
+ const response = await fetch(url, options);
46
+ const responseData = await response.json();
47
+
48
+ if (!response.ok) {
49
+ throw new Error(responseData.message || `API request failed: ${response.status}`);
50
+ }
51
+
52
+ return responseData;
53
+ } catch (error) {
54
+ if (error.message.includes('fetch')) {
55
+ throw new Error(`Network error: Could not connect to backend at ${this.baseUrl}`);
56
+ }
57
+ throw error;
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Validate CLI session
63
+ */
64
+ async validateSession() {
65
+ try {
66
+ return await this.request('GET', '/api/v1/auth/cli/validate');
67
+ } catch (error) {
68
+ return null;
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Refresh CLI session
74
+ */
75
+ async refreshSession() {
76
+ try {
77
+ const session = configManager.getSession();
78
+ if (!session || !session.token) {
79
+ throw new Error('No session to refresh');
80
+ }
81
+
82
+ const response = await this.request('POST', '/api/v1/auth/cli/refresh', {
83
+ token: session.token,
84
+ });
85
+
86
+ // Update session
87
+ configManager.saveSession({
88
+ ...session,
89
+ token: response.token,
90
+ expiresAt: response.expiresAt,
91
+ });
92
+
93
+ return response;
94
+ } catch (error) {
95
+ configManager.clearSession();
96
+ throw error;
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Get CLI login URL (uses unified OAuth signup endpoint)
102
+ */
103
+ getLoginUrl(provider = null) {
104
+ const backendUrl = configManager.getBackendUrl();
105
+ const callbackUrl = 'http://localhost:3001/callback';
106
+
107
+ if (provider) {
108
+ // Direct OAuth provider URL
109
+ return `${backendUrl}/api/auth/oauth-signup?provider=${provider}&sessionType=cli&callback=${encodeURIComponent(callbackUrl)}`;
110
+ } else {
111
+ // Provider selection page (still uses old endpoint for now, but could be updated)
112
+ return `${backendUrl}/auth/cli-login?callback=${encodeURIComponent(callbackUrl)}`;
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Generate API key for organization
118
+ * Note: This calls Convex action directly, requires session
119
+ */
120
+ async generateApiKey(organizationId, name, scopes = ['*']) {
121
+ // This will need to call Convex action via backend API wrapper
122
+ // For now, placeholder
123
+ return await this.request('POST', `/api/v1/api-keys/generate`, {
124
+ organizationId,
125
+ name,
126
+ scopes,
127
+ });
128
+ }
129
+
130
+ /**
131
+ * Get organizations for current user
132
+ */
133
+ async getOrganizations() {
134
+ return await this.request('GET', '/api/v1/organizations');
135
+ }
136
+
137
+ /**
138
+ * Create organization
139
+ */
140
+ async createOrganization(name) {
141
+ return await this.request('POST', '/api/v1/organizations', {
142
+ name,
143
+ });
144
+ }
145
+ }
146
+
147
+ module.exports = new BackendClient();
148
+