@flexops/sdk 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.
package/README.md ADDED
@@ -0,0 +1,449 @@
1
+ # @flexops/sdk
2
+
3
+ Official Node.js/TypeScript SDK for the [FlexOps](https://flexops.io) multi-carrier shipping platform.
4
+
5
+ ## Features
6
+
7
+ - Full TypeScript support with complete type definitions
8
+ - All 4 carriers: **USPS**, **UPS**, **FedEx**, **DHL**
9
+ - High-level shipping operations (rate shopping, labels, tracking)
10
+ - Direct carrier-specific endpoint access (214 VisionSuite endpoints)
11
+ - Automatic retry with exponential backoff
12
+ - JWT and API key authentication
13
+ - Webhook signature verification (HMAC-SHA256)
14
+ - ESM and CommonJS support
15
+ - Zero external runtime dependencies
16
+
17
+ ## Installation
18
+
19
+ ```bash
20
+ npm install @flexops/sdk
21
+ ```
22
+
23
+ ## Quick Start
24
+
25
+ ### API Key Authentication (server-to-server)
26
+
27
+ ```typescript
28
+ import { FlexOps } from '@flexops/sdk';
29
+
30
+ const client = new FlexOps({
31
+ apiKey: 'fxk_live_...',
32
+ workspaceId: 'your-workspace-id',
33
+ });
34
+ ```
35
+
36
+ ### Email/Password Authentication
37
+
38
+ ```typescript
39
+ const client = new FlexOps({
40
+ baseUrl: 'https://gateway.flexops.io',
41
+ });
42
+
43
+ await client.auth.login({
44
+ email: 'user@company.com',
45
+ password: 'your-password',
46
+ });
47
+ // Token is automatically stored for subsequent requests
48
+ ```
49
+
50
+ ## Shipping Operations
51
+
52
+ ### Rate Shopping
53
+
54
+ ```typescript
55
+ // Get all available rates
56
+ const rates = await client.shipping.getRates({
57
+ fromZip: '10001',
58
+ toZip: '90210',
59
+ weight: 16,
60
+ weightUnit: 'oz',
61
+ });
62
+
63
+ // Get the single cheapest rate
64
+ const cheapest = await client.shipping.getCheapestRate({
65
+ fromZip: '10001',
66
+ toZip: '90210',
67
+ weight: 16,
68
+ });
69
+
70
+ // Get the single fastest rate
71
+ const fastest = await client.shipping.getFastestRate({
72
+ fromZip: '10001',
73
+ toZip: '90210',
74
+ weight: 16,
75
+ });
76
+ ```
77
+
78
+ ### Create a Shipping Label
79
+
80
+ ```typescript
81
+ const label = await client.shipping.createLabel({
82
+ carrier: 'USPS',
83
+ service: 'Priority Mail',
84
+ fromAddress: {
85
+ name: 'Warehouse A',
86
+ street1: '123 Ship Lane',
87
+ city: 'New York',
88
+ state: 'NY',
89
+ zip: '10001',
90
+ country: 'US',
91
+ },
92
+ toAddress: {
93
+ name: 'Jane Customer',
94
+ street1: '456 Oak Ave',
95
+ city: 'Los Angeles',
96
+ state: 'CA',
97
+ zip: '90210',
98
+ country: 'US',
99
+ },
100
+ parcel: {
101
+ weight: 16,
102
+ weightUnit: 'oz',
103
+ length: 10,
104
+ width: 8,
105
+ height: 4,
106
+ dimensionUnit: 'in',
107
+ },
108
+ });
109
+
110
+ console.log(label.data.trackingNumber);
111
+ console.log(label.data.labelData); // Base64 PDF
112
+ ```
113
+
114
+ ### Tracking
115
+
116
+ ```typescript
117
+ const tracking = await client.shipping.track('9400111899223456789012');
118
+
119
+ for (const event of tracking.data.events) {
120
+ console.log(`${event.timestamp}: ${event.description}`);
121
+ }
122
+ ```
123
+
124
+ ### Address Validation
125
+
126
+ ```typescript
127
+ const result = await client.shipping.validateAddress({
128
+ name: 'John Doe',
129
+ street1: '123 Main St',
130
+ city: 'New York',
131
+ state: 'NY',
132
+ zip: '10001',
133
+ country: 'US',
134
+ });
135
+
136
+ if (!result.data.isValid) {
137
+ console.log('Corrected:', result.data.correctedAddress);
138
+ }
139
+ ```
140
+
141
+ ### Batch Labels
142
+
143
+ ```typescript
144
+ // Preview (dry-run) before purchasing
145
+ const preview = await client.shipping.previewBatch({
146
+ items: [/* array of CreateLabelRequest */],
147
+ });
148
+
149
+ // Create the batch
150
+ const batch = await client.shipping.createBatch({
151
+ items: [/* array of CreateLabelRequest */],
152
+ });
153
+
154
+ // Check status
155
+ const status = await client.shipping.getBatchStatus(batch.data.jobId);
156
+ ```
157
+
158
+ ## Direct Carrier Access
159
+
160
+ For full control, use carrier-specific endpoints:
161
+
162
+ ### USPS
163
+
164
+ ```typescript
165
+ // Domestic label with full USPS payload
166
+ const label = await client.carriers.usps.createDomesticLabel({
167
+ imageType: 'PDF',
168
+ mailClass: 'PRIORITY_MAIL',
169
+ weightInOunces: 16,
170
+ // ... full USPS API payload
171
+ });
172
+
173
+ // Rate calculation
174
+ const rates = await client.carriers.usps.getDomesticRates({
175
+ originZIPCode: '10001',
176
+ destinationZIPCode: '90210',
177
+ weight: 1.0,
178
+ });
179
+
180
+ // Find drop-off locations
181
+ const locations = await client.carriers.usps.findDropOffLocations({
182
+ zipCode: '10001',
183
+ });
184
+ ```
185
+
186
+ ### UPS
187
+
188
+ ```typescript
189
+ const label = await client.carriers.ups.createLabel({ /* UPS payload */ });
190
+ const rates = await client.carriers.ups.getRates({ /* UPS payload */ });
191
+ const tracking = await client.carriers.ups.track({ trackingNumber: '1Z...' });
192
+ const transitTimes = await client.carriers.ups.getTransitTimes({ /* payload */ });
193
+ ```
194
+
195
+ ### FedEx
196
+
197
+ ```typescript
198
+ const shipment = await client.carriers.fedex.createShipment({ /* FedEx payload */ });
199
+ const rates = await client.carriers.fedex.getRates({ /* FedEx payload */ });
200
+ const tracking = await client.carriers.fedex.track({ /* payload */ });
201
+
202
+ // Multi-package (Open Ship)
203
+ await client.carriers.fedex.createOpenShipment({ /* payload */ });
204
+ await client.carriers.fedex.addPackagesToOpenShipment({ /* payload */ });
205
+ await client.carriers.fedex.confirmOpenShipment({ /* payload */ });
206
+ ```
207
+
208
+ ### DHL
209
+
210
+ ```typescript
211
+ const shipment = await client.carriers.dhl.createShipment({ /* DHL payload */ });
212
+ const rates = await client.carriers.dhl.getRates({ countryCode: 'US', weight: '1' });
213
+ const tracking = await client.carriers.dhl.track({ shipmentTrackingNumber: '123456' });
214
+ const landedCost = await client.carriers.dhl.calculateLandedCost({ /* payload */ });
215
+ ```
216
+
217
+ ## Workspace Management
218
+
219
+ ```typescript
220
+ // List workspaces
221
+ const workspaces = await client.workspaces.list();
222
+
223
+ // Switch workspace
224
+ client.workspaceId = 'different-workspace-id';
225
+
226
+ // Invite a member
227
+ await client.workspaces.inviteMember('newuser@company.com', 'Member');
228
+ ```
229
+
230
+ ## Webhooks
231
+
232
+ ```typescript
233
+ // Create a subscription
234
+ const webhook = await client.webhooks.create({
235
+ url: 'https://your-app.com/webhooks/flexops',
236
+ events: ['label.created', 'tracking.updated', 'shipment.delivered'],
237
+ });
238
+
239
+ // Rotate the signing secret
240
+ await client.webhooks.rotateSecret(webhook.data.id);
241
+
242
+ // Verify incoming webhook signatures in your handler
243
+ import { WebhooksResource } from '@flexops/sdk';
244
+
245
+ app.post('/webhooks/flexops', (req, res) => {
246
+ const signature = req.headers['x-flexops-signature'];
247
+ const isValid = WebhooksResource.verifySignature(
248
+ JSON.stringify(req.body),
249
+ signature,
250
+ process.env.FLEXOPS_WEBHOOK_SECRET,
251
+ );
252
+
253
+ if (!isValid) return res.status(401).send('Invalid signature');
254
+ // Process webhook...
255
+ });
256
+ ```
257
+
258
+ ## Curl Quickstart
259
+
260
+ Every SDK method is a thin wrapper around the FlexOps REST API. If you want to verify the API before committing to the SDK — or you're integrating from a language we don't ship a SDK for — these curl invocations hit the same endpoints:
261
+
262
+ ```bash
263
+ # Shop rates across all connected carriers
264
+ curl -X POST https://gateway.flexops.io/api/workspaces/ws_abc123/shipping/rates \
265
+ -H "X-API-Key: fxk_live_..." \
266
+ -H "Content-Type: application/json" \
267
+ -d '{
268
+ "fromAddress": {"street1": "123 Main St", "city": "New York", "state": "NY", "zip": "10001", "country": "US"},
269
+ "toAddress": {"street1": "456 Oak Ave", "city": "Los Angeles", "state": "CA", "zip": "90210", "country": "US"},
270
+ "parcel": {"weight": 16, "weightUnit": "oz"}
271
+ }'
272
+
273
+ # Create a label
274
+ curl -X POST https://gateway.flexops.io/api/workspaces/ws_abc123/shipping/labels \
275
+ -H "X-API-Key: fxk_live_..." \
276
+ -H "Content-Type: application/json" \
277
+ -d '{
278
+ "carrier": "USPS",
279
+ "service": "PRIORITY_MAIL",
280
+ "fromAddress": {"name": "Warehouse", "street1": "123 Main St", "city": "New York", "state": "NY", "zip": "10001", "country": "US"},
281
+ "toAddress": {"name": "Customer", "street1": "456 Oak Ave", "city": "Los Angeles", "state": "CA", "zip": "90210", "country": "US"},
282
+ "parcel": {"weight": 16, "weightUnit": "oz"}
283
+ }'
284
+
285
+ # Track a shipment
286
+ curl https://gateway.flexops.io/api/workspaces/ws_abc123/shipping/track/9400111899223456789012 \
287
+ -H "X-API-Key: fxk_live_..."
288
+
289
+ # Cancel a label (via the unified carrier-agnostic endpoint)
290
+ curl -X DELETE https://gateway.flexops.io/api/v3.0/shipping/Usps/cancel/9400111899223456789012 \
291
+ -H "X-API-Key: fxk_live_..."
292
+ ```
293
+
294
+ Use an `fxk_test_...` key instead of `fxk_live_...` to hit the sandbox environment; mock carriers respond, no real charges, no real labels.
295
+
296
+ ## Wallet & Billing
297
+
298
+ ```typescript
299
+ const balance = await client.wallet.getBalance();
300
+ console.log(`Balance: $${balance.data.balance}`);
301
+
302
+ // Add funds
303
+ await client.wallet.addFunds(100.00);
304
+
305
+ // Configure auto-reload
306
+ await client.wallet.configureAutoReload({
307
+ enabled: true,
308
+ threshold: 25.00,
309
+ amount: 100.00,
310
+ });
311
+ ```
312
+
313
+ ## Insurance
314
+
315
+ ```typescript
316
+ // Check available providers
317
+ const providers = await client.insurance.getProviders();
318
+ // Returns ["FlexOps"] or ["FlexOps", "U-PIC"]
319
+
320
+ // Get a quote
321
+ const quote = await client.insurance.getQuote({
322
+ carrier: 'USPS',
323
+ declaredValue: 500.00,
324
+ provider: 'FlexOps',
325
+ });
326
+
327
+ // Purchase insurance
328
+ const policy = await client.insurance.purchase({
329
+ trackingNumber: '9400111899223456789012',
330
+ carrier: 'USPS',
331
+ declaredValue: 500.00,
332
+ });
333
+ ```
334
+
335
+ ## Returns & RMA
336
+
337
+ ```typescript
338
+ // Create a return authorization
339
+ const rma = await client.returns.create({
340
+ orderId: 'ORD-12345',
341
+ reason: 'Defective product',
342
+ items: [{ sku: 'WIDGET-001', quantity: 1 }],
343
+ });
344
+
345
+ // Approve and generate return label
346
+ await client.returns.approve(rma.data.rmaId);
347
+ await client.returns.generateLabel(rma.data.rmaId);
348
+
349
+ // Mark items as received
350
+ await client.returns.markReceived(rma.data.rmaId, [
351
+ { sku: 'WIDGET-001', quantity: 1, condition: 'damaged' },
352
+ ]);
353
+ ```
354
+
355
+ ## Analytics
356
+
357
+ ```typescript
358
+ const trend = await client.analytics.shipmentsTrend({
359
+ startDate: '2026-01-01',
360
+ endDate: '2026-03-01',
361
+ period: 'week',
362
+ });
363
+
364
+ const carriers = await client.analytics.carrierSummary();
365
+ const returns = await client.analytics.returnsMetrics();
366
+ const performance = await client.analytics.deliveryPerformance();
367
+ ```
368
+
369
+ ## Automation Rules
370
+
371
+ ```typescript
372
+ // Create a shipping rule
373
+ await client.rules.create({
374
+ name: 'Route light packages via USPS',
375
+ isActive: true,
376
+ priority: 1,
377
+ conditions: [
378
+ { field: 'Weight', operator: 'LessThan', value: '16' },
379
+ { field: 'DestinationCountry', operator: 'Equals', value: 'US' },
380
+ ],
381
+ actions: [
382
+ { type: 'SetCarrier', value: 'USPS' },
383
+ { type: 'SetService', value: 'GROUND_ADVANTAGE' },
384
+ ],
385
+ });
386
+ ```
387
+
388
+ ## Error Handling
389
+
390
+ ```typescript
391
+ import { FlexOpsError, FlexOpsAuthError, FlexOpsRateLimitError } from '@flexops/sdk';
392
+
393
+ try {
394
+ await client.shipping.createLabel({ /* ... */ });
395
+ } catch (error) {
396
+ if (error instanceof FlexOpsRateLimitError) {
397
+ console.log(`Rate limited. Retry after ${error.retryAfter}s`);
398
+ } else if (error instanceof FlexOpsAuthError) {
399
+ console.log('Re-authenticate and try again');
400
+ } else if (error instanceof FlexOpsError) {
401
+ console.log(`API error ${error.status}: ${error.message}`);
402
+ console.log('Validation errors:', error.errors);
403
+ }
404
+ }
405
+ ```
406
+
407
+ ## Configuration
408
+
409
+ ```typescript
410
+ const client = new FlexOps({
411
+ baseUrl: 'https://gateway.flexops.io', // Default
412
+ apiKey: 'fxk_live_...',
413
+ workspaceId: 'ws-abc123',
414
+ timeout: 30000, // 30s default
415
+ retry: {
416
+ maxRetries: 3, // Default
417
+ baseDelay: 1000, // 1s, exponential backoff
418
+ retryableStatusCodes: [429, 500, 502, 503, 504],
419
+ },
420
+ headers: {
421
+ 'X-Custom-Header': 'value', // Added to every request
422
+ },
423
+ });
424
+ ```
425
+
426
+ ## OpenAPI Spec Generation
427
+
428
+ The SDK includes tooling to generate TypeScript types from the live API spec:
429
+
430
+ ```bash
431
+ # 1. Start the FlexOps platform (Aspire orchestrator)
432
+ dotnet run --project FlexOps.Platform.AppHost
433
+
434
+ # 2. Export the Gateway API spec
435
+ ./scripts/export-gateway-spec.sh http://localhost:XXXX
436
+
437
+ # 3. Pre-process and merge all specs
438
+ npm run preprocess -- --gateway specs/raw/gateway-v1.json
439
+
440
+ # 4. Generate TypeScript client (optional — for full auto-generated client)
441
+ npm run generate
442
+
443
+ # 5. Build the SDK
444
+ npm run build
445
+ ```
446
+
447
+ ## License
448
+
449
+ Proprietary - FlexOps, LLC. All rights reserved.