@simpleapps-com/augur-api 0.2.5 → 0.2.7

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 (45) hide show
  1. package/API-DISCOVERY.md +132 -0
  2. package/AUTHENTICATION.md +371 -0
  3. package/QUICKSTART.md +255 -0
  4. package/README.md +125 -91
  5. package/dist/cjs/client.d.ts +36 -1
  6. package/dist/cjs/client.d.ts.map +1 -1
  7. package/dist/cjs/client.js +54 -1
  8. package/dist/cjs/client.js.map +1 -1
  9. package/dist/cjs/core/config.d.ts +24 -0
  10. package/dist/cjs/core/config.d.ts.map +1 -1
  11. package/dist/cjs/core/config.js +12 -1
  12. package/dist/cjs/core/config.js.map +1 -1
  13. package/dist/cjs/index.d.ts +2 -2
  14. package/dist/cjs/index.d.ts.map +1 -1
  15. package/dist/cjs/index.js +5 -2
  16. package/dist/cjs/index.js.map +1 -1
  17. package/dist/cjs/services/vmi/client.d.ts +501 -1
  18. package/dist/cjs/services/vmi/client.d.ts.map +1 -1
  19. package/dist/cjs/services/vmi/client.js +408 -0
  20. package/dist/cjs/services/vmi/client.js.map +1 -1
  21. package/dist/esm/client.d.ts +36 -1
  22. package/dist/esm/client.d.ts.map +1 -1
  23. package/dist/esm/client.js +52 -0
  24. package/dist/esm/client.js.map +1 -1
  25. package/dist/esm/core/config.d.ts +24 -0
  26. package/dist/esm/core/config.d.ts.map +1 -1
  27. package/dist/esm/core/config.js +10 -0
  28. package/dist/esm/core/config.js.map +1 -1
  29. package/dist/esm/index.d.ts +2 -2
  30. package/dist/esm/index.d.ts.map +1 -1
  31. package/dist/esm/index.js +3 -1
  32. package/dist/esm/index.js.map +1 -1
  33. package/dist/esm/services/vmi/client.d.ts +501 -1
  34. package/dist/esm/services/vmi/client.d.ts.map +1 -1
  35. package/dist/esm/services/vmi/client.js +408 -0
  36. package/dist/esm/services/vmi/client.js.map +1 -1
  37. package/dist/types/client.d.ts +36 -1
  38. package/dist/types/client.d.ts.map +1 -1
  39. package/dist/types/core/config.d.ts +24 -0
  40. package/dist/types/core/config.d.ts.map +1 -1
  41. package/dist/types/index.d.ts +2 -2
  42. package/dist/types/index.d.ts.map +1 -1
  43. package/dist/types/services/vmi/client.d.ts +501 -1
  44. package/dist/types/services/vmi/client.d.ts.map +1 -1
  45. package/package.json +5 -2
@@ -0,0 +1,132 @@
1
+ # API Discovery Guide
2
+
3
+ Find any functionality across 13 microservices using natural language search.
4
+
5
+ ## Quick Reference
6
+
7
+ ```typescript
8
+ import { AugurAPI } from '@simpleapps-com/augur-api';
9
+
10
+ const api = new AugurAPI({ siteId: 'your-site', bearerToken: 'token' });
11
+
12
+ // Discover all services
13
+ const services = await api.discover();
14
+
15
+ // Find specific functionality
16
+ const results = await api.findEndpoint('user management');
17
+ const inventory = await api.findEndpoint('stock levels');
18
+ const pricing = await api.findEndpoint('product pricing');
19
+ ```
20
+
21
+ ## Core Methods
22
+
23
+ ### `api.discover()`
24
+ Returns complete service map with all available endpoints.
25
+
26
+ ```typescript
27
+ const services = await api.discover();
28
+ services.forEach(service => {
29
+ console.log(`${service.serviceName}: ${service.endpointCount} endpoints`);
30
+ });
31
+ ```
32
+
33
+ ### `api.findEndpoint(searchTerm, options?)`
34
+ Search across all services for matching functionality.
35
+
36
+ ```typescript
37
+ // Basic search
38
+ const results = await api.findEndpoint('users');
39
+
40
+ // Advanced search with filters
41
+ const results = await api.findEndpoint('settings', {
42
+ service: 'agrSite', // Filter by service
43
+ domain: 'content-management', // Filter by domain
44
+ readOnly: true, // Only GET endpoints
45
+ maxResults: 5 // Limit results
46
+ });
47
+ ```
48
+
49
+ ## Common Searches
50
+
51
+ | Search Term | Returns |
52
+ |-------------|---------|
53
+ | `'user management'` | User CRUD, authentication, groups |
54
+ | `'inventory'` | Stock levels, warehouse operations |
55
+ | `'product search'` | OpenSearch, product catalogs |
56
+ | `'site settings'` | Configuration, notifications |
57
+ | `'pricing'` | Price engine, job pricing |
58
+ | `'orders'` | Order management, invoicing |
59
+
60
+ ## Search Filters
61
+
62
+ ```typescript
63
+ interface SearchOptions {
64
+ service?: string; // 'joomla', 'vmi', 'commerce', etc.
65
+ domain?: string; // 'user-management', 'inventory-management'
66
+ readOnly?: boolean; // true = GET only, false = all methods
67
+ minScore?: number; // 0.0 to 1.0 relevance threshold
68
+ maxResults?: number; // Limit number of results
69
+ }
70
+ ```
71
+
72
+ ## Business Domains
73
+
74
+ - **user-management** - Users, authentication, permissions
75
+ - **content-management** - Articles, site settings, notifications
76
+ - **e-commerce** - Shopping carts, checkout, recommendations
77
+ - **inventory-management** - Warehouses, stock levels, transfers
78
+ - **product-catalog** - Products, categories, search
79
+ - **customer-data** - Customer profiles, orders, addresses
80
+ - **order-processing** - Orders, invoicing, payments
81
+
82
+ ## AI Assistant Integration
83
+
84
+ Every method includes semantic tags for AI assistants:
85
+
86
+ ```typescript
87
+ /**
88
+ * @searchTerms ["users", "user management", "authentication"]
89
+ * @relatedEndpoints ["api.joomla.users.get", "api.joomla.users.create"]
90
+ * @commonPatterns ["List all users", "Get user directory"]
91
+ */
92
+ ```
93
+
94
+ When you ask an AI assistant "help me manage users", it can:
95
+ 1. Find `api.joomla.users.list()` through searchTerms
96
+ 2. Suggest related operations from relatedEndpoints
97
+ 3. Provide examples using commonPatterns
98
+ 4. Show complete workflows across services
99
+
100
+ ## Example Workflows
101
+
102
+ ### User Management
103
+ ```typescript
104
+ const userOps = await api.findEndpoint('user management');
105
+ // Returns: api.joomla.users.list, api.joomla.users.get, api.joomla.users.create
106
+
107
+ const users = await api.joomla.users.list({ limit: 10 });
108
+ const user = await api.joomla.users.get('123');
109
+ ```
110
+
111
+ ### Inventory Operations
112
+ ```typescript
113
+ const inventory = await api.findEndpoint('inventory levels');
114
+ // Returns: api.vmi.inventory.checkAvailability, api.vmi.warehouses.list
115
+
116
+ const availability = await api.vmi.inventory.checkAvailability(warehouseId);
117
+ const warehouses = await api.vmi.warehouses.list({ customerId: 12345 });
118
+ ```
119
+
120
+ ### Product Search
121
+ ```typescript
122
+ const search = await api.findEndpoint('product search');
123
+ // Returns: api.opensearch.itemSearch.search, api.items.products.list
124
+
125
+ const results = await api.opensearch.itemSearch.search({
126
+ q: 'electrical wire',
127
+ searchType: 'query',
128
+ size: 20
129
+ });
130
+ ```
131
+
132
+ The discovery system eliminates the need to memorize 13 different microservice APIs. Just describe what you want to accomplish, and find the right endpoints instantly.
@@ -0,0 +1,371 @@
1
+ # Authentication Guide
2
+
3
+ Complete guide to authentication patterns in the Augur API Client.
4
+
5
+ ## Standard Authentication (Most Common)
6
+
7
+ The standard authentication pattern works for 95% of use cases.
8
+
9
+ ### Dual Authentication System
10
+
11
+ Every API request requires two pieces of authentication:
12
+
13
+ 1. **Site ID** (`x-site-id` header) - Identifies which site/tenant you're working with
14
+ 2. **Bearer Token** (JWT) - Proves you're authorized to access that site
15
+
16
+ ```typescript
17
+ const api = new AugurAPI({
18
+ siteId: 'your-site-id', // Always required
19
+ bearerToken: 'your-jwt-token', // Required except for health checks
20
+ });
21
+ ```
22
+
23
+ ### How to Get Your Credentials
24
+
25
+ **Site ID**: Usually provided by your system administrator or found in your project configuration.
26
+
27
+ **Bearer Token**: Obtained through your application's login process. This is typically a JWT token that looks like:
28
+ `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...`
29
+
30
+ ### Health Checks (No Authentication Required)
31
+
32
+ Health checks are the only endpoints that don't require a bearer token:
33
+
34
+ ```typescript
35
+ // Health checks work without bearer token
36
+ const api = new AugurAPI({
37
+ siteId: 'your-site-id',
38
+ // No bearerToken needed
39
+ });
40
+
41
+ const health = await api.joomla.getHealthCheck();
42
+ const pricingHealth = await api.pricing.getHealthCheck();
43
+ const vmiPing = await api.vmi.health.ping();
44
+ ```
45
+
46
+ ### Dynamic Authentication Updates
47
+
48
+ Update credentials at runtime when needed:
49
+
50
+ ```typescript
51
+ // Update token after login/refresh
52
+ api.setAuthToken('new-jwt-token');
53
+
54
+ // Switch to different site
55
+ api.setSiteId('different-site-id');
56
+
57
+ // Example: Token refresh scenario
58
+ async function refreshTokenIfNeeded() {
59
+ try {
60
+ await api.joomla.users.list({ limit: 1 });
61
+ } catch (error) {
62
+ if (error instanceof AuthenticationError) {
63
+ const newToken = await refreshJWTToken();
64
+ api.setAuthToken(newToken);
65
+ }
66
+ }
67
+ }
68
+ ```
69
+
70
+ ### Environment Variables Setup
71
+
72
+ Store credentials securely in environment variables:
73
+
74
+ ```bash
75
+ # .env file
76
+ AUGUR_SITE_ID=your-site-id
77
+ AUGUR_JWT_TOKEN=your-jwt-token
78
+ ```
79
+
80
+ ```typescript
81
+ const api = new AugurAPI({
82
+ siteId: process.env.AUGUR_SITE_ID!,
83
+ bearerToken: process.env.AUGUR_JWT_TOKEN!,
84
+ });
85
+ ```
86
+
87
+ ### Security Best Practices
88
+
89
+ 1. **Environment Variables**: Never hardcode credentials
90
+ 2. **Token Rotation**: Implement regular token rotation in production
91
+ 3. **HTTPS Only**: All API requests use HTTPS in production
92
+ 4. **Secure Storage**: Never store tokens in localStorage for web apps
93
+ 5. **Minimal Permissions**: Use tokens with minimal required permissions
94
+
95
+ ```typescript
96
+ // ✅ Good: Environment-based configuration
97
+ const api = new AugurAPI({
98
+ siteId: process.env.AUGUR_SITE_ID!,
99
+ bearerToken: getSecurelyStoredToken(), // From secure storage
100
+ });
101
+
102
+ // ❌ Bad: Hardcoded credentials
103
+ const api = new AugurAPI({
104
+ siteId: 'hardcoded-site-id',
105
+ bearerToken: 'hardcoded-token', // Never do this!
106
+ });
107
+ ```
108
+
109
+ ---
110
+
111
+ ## Advanced: Cross-Site Authentication
112
+
113
+ **⚠️ Advanced Feature**: Only needed for multi-tenant applications where you need to authenticate users across different sites.
114
+
115
+ ### When You Need Cross-Site Auth
116
+
117
+ Cross-site authentication is needed when:
118
+ - You're building a multi-tenant application
119
+ - You need to authenticate a user from one site against a different site
120
+ - You're managing multiple client sites from a central application
121
+
122
+ ### Prerequisites
123
+
124
+ - Access to the special `augur_info` site
125
+ - Admin-level JWT token with `augur_info` privileges
126
+ - Target site ID where you want to authenticate the user
127
+
128
+ ### Option 1: Streamlined Utility Function (Recommended)
129
+
130
+ ```typescript
131
+ import { authenticateUserForSite } from '@simpleapps-com/augur-api';
132
+
133
+ const result = await authenticateUserForSite({
134
+ targetSiteId: 'tenant_site_1',
135
+ username: 'user@tenant.com',
136
+ password: 'user-password',
137
+ augurInfoToken: 'admin-jwt-token' // JWT with augur_info admin privileges
138
+ });
139
+
140
+ if (result.success) {
141
+ // Ready-to-use API client for the target site
142
+ const userData = await result.targetSiteAPI!.joomla.users.get(result.userId!);
143
+ console.log('User authenticated:', result.username);
144
+ console.log('User data:', userData);
145
+ } else {
146
+ console.error('Authentication failed:', result.error);
147
+ }
148
+ ```
149
+
150
+ ### Option 2: Reusable Authenticator
151
+
152
+ ```typescript
153
+ import { createCrossSiteAuthenticator } from '@simpleapps-com/augur-api';
154
+
155
+ // Create reusable authenticator
156
+ const crossSiteAuth = createCrossSiteAuthenticator('admin-jwt-token');
157
+
158
+ // Use for multiple sites
159
+ const result1 = await crossSiteAuth('tenant_site_1', 'user1@tenant.com', 'pass1');
160
+ const result2 = await crossSiteAuth('tenant_site_2', 'user2@tenant.com', 'pass2');
161
+
162
+ if (result1.success) {
163
+ const tenantData = await result1.targetSiteAPI!.joomla.content.list({ limit: 10 });
164
+ }
165
+ ```
166
+
167
+ ### Option 3: Manual Approach
168
+
169
+ ```typescript
170
+ // Manual approach using the API client directly
171
+ const crossSiteAPI = new AugurAPI({
172
+ siteId: 'augur_info', // Special site for cross-site operations
173
+ bearerToken: 'admin-jwt-token', // JWT token with augur_info admin privileges
174
+ });
175
+
176
+ // Authenticate user against a different site
177
+ const authResult = await crossSiteAPI.joomla.users.verifyPassword({
178
+ username: 'user@tenant.com',
179
+ password: 'user-password',
180
+ siteId: 'tenant_site_1' // Target site for authentication
181
+ });
182
+
183
+ if (authResult.data.isVerified) {
184
+ // Create API instance for the target site
185
+ const tenantAPI = new AugurAPI({
186
+ siteId: 'tenant_site_1',
187
+ bearerToken: authResult.data.token, // Token scoped to tenant site
188
+ });
189
+
190
+ const userData = await tenantAPI.joomla.users.get(authResult.data.id);
191
+ }
192
+ ```
193
+
194
+ ### Cross-Site Auth Flow Diagram
195
+
196
+ ```
197
+ [Your App] → [augur_info API] → [Target Site] → [User Validated] → [Target Site API Client]
198
+ ↓ ↓ ↓ ↓ ↓
199
+ Admin Token → Verify User → Check Password → Return User Token → Ready for API calls
200
+ ```
201
+
202
+ ### Common Cross-Site Patterns
203
+
204
+ #### Multi-Tenant Dashboard
205
+ ```typescript
206
+ // Authenticate users across multiple tenant sites
207
+ const authenticator = createCrossSiteAuthenticator(adminToken);
208
+
209
+ const tenants = ['site1', 'site2', 'site3'];
210
+ const userCredentials = { username: 'user@example.com', password: 'pass' };
211
+
212
+ const results = await Promise.all(
213
+ tenants.map(siteId =>
214
+ authenticator(siteId, userCredentials.username, userCredentials.password)
215
+ )
216
+ );
217
+
218
+ // Process results for each tenant
219
+ results.forEach((result, index) => {
220
+ if (result.success) {
221
+ console.log(`${tenants[index]}: User authenticated as ${result.username}`);
222
+ } else {
223
+ console.log(`${tenants[index]}: Authentication failed - ${result.error}`);
224
+ }
225
+ });
226
+ ```
227
+
228
+ #### Site Switching
229
+ ```typescript
230
+ // Allow users to switch between sites they have access to
231
+ async function switchUserToSite(username: string, password: string, targetSiteId: string) {
232
+ const result = await authenticateUserForSite({
233
+ targetSiteId,
234
+ username,
235
+ password,
236
+ augurInfoToken: process.env.AUGUR_INFO_ADMIN_TOKEN!
237
+ });
238
+
239
+ if (result.success) {
240
+ // Store the new site's API client
241
+ global.userAPI = result.targetSiteAPI;
242
+ global.currentSiteId = targetSiteId;
243
+ return { success: true, siteId: targetSiteId };
244
+ }
245
+
246
+ return { success: false, error: result.error };
247
+ }
248
+ ```
249
+
250
+ ### Cross-Site Error Handling
251
+
252
+ ```typescript
253
+ try {
254
+ const result = await authenticateUserForSite({
255
+ targetSiteId: 'tenant-site',
256
+ username: 'user@tenant.com',
257
+ password: 'user-pass',
258
+ augurInfoToken: adminToken
259
+ });
260
+
261
+ if (!result.success) {
262
+ switch (result.error) {
263
+ case 'Invalid username or password':
264
+ // Handle wrong username/password
265
+ break;
266
+ case 'Site not found':
267
+ // Handle invalid target site (from API error)
268
+ break;
269
+ case 'Authentication failed':
270
+ // Handle general auth failures or network issues
271
+ break;
272
+ default:
273
+ // Handle other errors
274
+ break;
275
+ }
276
+ }
277
+ } catch (error) {
278
+ console.error('Cross-site auth failed:', error.message);
279
+ }
280
+ ```
281
+
282
+ ### Security Considerations for Cross-Site Auth
283
+
284
+ 1. **Admin Token Security**: The `augur_info` admin token is very powerful - store it extremely securely
285
+ 2. **Audit Logging**: Log all cross-site authentication attempts for security monitoring
286
+ 3. **Rate Limiting**: Implement rate limiting to prevent brute force attacks
287
+ 4. **Token Scoping**: Returned tokens are scoped to the target site only
288
+ 5. **Session Management**: Properly manage and clean up cross-site sessions
289
+
290
+ ### When NOT to Use Cross-Site Auth
291
+
292
+ Don't use cross-site authentication if:
293
+ - You're working with a single site (use standard auth)
294
+ - You don't have admin-level access to `augur_info`
295
+ - You're building a simple application without multi-tenancy
296
+ - Security requirements prohibit cross-site token exchange
297
+
298
+ ---
299
+
300
+ ## Troubleshooting Authentication
301
+
302
+ ### Common Issues
303
+
304
+ **"Authentication failed" (401 Error)**
305
+ - Check your `bearerToken` is correct and not expired
306
+ - Verify your `siteId` matches your environment
307
+ - For cross-site auth, ensure your admin token has `augur_info` privileges
308
+
309
+ **"Forbidden" (403 Error)**
310
+ - Your token is valid but doesn't have permission for this operation
311
+ - Check if you need admin-level permissions
312
+ - Verify the site ID matches the token's scope
313
+
314
+ **"Site not found" (Cross-site auth)**
315
+ - Verify the target site ID exists and is accessible
316
+ - Check that the target site is properly configured
317
+ - Ensure your admin token has access to the target site
318
+
319
+ **Token Expiration**
320
+ - Implement token refresh logic
321
+ - Monitor token expiration times
322
+ - Have fallback authentication flow
323
+
324
+ ### Authentication Testing
325
+
326
+ ```typescript
327
+ // Test standard authentication
328
+ async function testAuth() {
329
+ try {
330
+ const api = new AugurAPI({
331
+ siteId: 'your-site-id',
332
+ bearerToken: 'your-token'
333
+ });
334
+
335
+ // Simple test call
336
+ const health = await api.joomla.getHealthCheck();
337
+ console.log('✅ Authentication working:', health.data.status);
338
+
339
+ // Test authenticated call
340
+ const users = await api.joomla.users.list({ limit: 1 });
341
+ console.log('✅ Authenticated API calls working');
342
+
343
+ } catch (error) {
344
+ console.error('❌ Authentication failed:', error.message);
345
+ }
346
+ }
347
+
348
+ // Test cross-site authentication
349
+ async function testCrossSiteAuth() {
350
+ try {
351
+ const result = await authenticateUserForSite({
352
+ targetSiteId: 'test-site',
353
+ username: 'test-user',
354
+ password: 'test-pass',
355
+ augurInfoToken: 'admin-token'
356
+ });
357
+
358
+ if (result.success) {
359
+ console.log('✅ Cross-site auth working');
360
+ const testCall = await result.targetSiteAPI!.joomla.getHealthCheck();
361
+ console.log('✅ Target site API working:', testCall.data.status);
362
+ } else {
363
+ console.error('❌ Cross-site auth failed:', result.error);
364
+ }
365
+ } catch (error) {
366
+ console.error('❌ Cross-site auth error:', error.message);
367
+ }
368
+ }
369
+ ```
370
+
371
+ For most applications, stick with standard authentication. Only implement cross-site authentication if you specifically need multi-tenant capabilities.