@flexops/sdk 2.0.0 → 3.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 CHANGED
@@ -7,8 +7,8 @@ Official Node.js/TypeScript SDK for the [FlexOps](https://flexops.io) multi-carr
7
7
  - Full TypeScript support with complete type definitions
8
8
  - All 4 carriers: **USPS**, **UPS**, **FedEx**, **DHL**
9
9
  - High-level shipping operations (rate shopping, labels, tracking)
10
- - Direct carrier-specific endpoint access (214 VisionSuite endpoints)
11
- - Automatic retry with exponential backoff
10
+ - The documented FlexOps API only: every method is checked against the published OpenAPI in CI
11
+ - Retries that cannot buy twice: writes carry an `Idempotency-Key` (see [Retries](#retries))
12
12
  - JWT and API key authentication
13
13
  - Webhook signature verification (HMAC-SHA256)
14
14
  - ESM and CommonJS support
@@ -25,7 +25,7 @@ npm install @flexops/sdk
25
25
  ### API Key Authentication (server-to-server)
26
26
 
27
27
  ```typescript
28
- import { FlexOps } from '@flexops/sdk';
28
+ import { FlexOps, HazmatClassification } from '@flexops/sdk';
29
29
 
30
30
  const client = new FlexOps({
31
31
  apiKey: 'fxk_live_...',
@@ -73,6 +73,8 @@ const fastest = await client.shipping.getFastestRate(rateRequest);
73
73
  ```typescript
74
74
  const operation = await client.shipping.prepareLabel({
75
75
  ...rateRequest, carrierCode: 'USPS', serviceCode: 'PRIORITY',
76
+ // Required without an orderId. The SDK never fills it in; None = not hazardous.
77
+ hazmatClassification: HazmatClassification.None,
76
78
  }, 10.00, crypto.randomUUID());
77
79
  if (operation.preview) console.log({ quote: operation.preview.quotedPostageAmount,
78
80
  maximum: operation.preview.maximumPostageAmount, currency: operation.preview.currency,
@@ -96,7 +98,7 @@ try {
96
98
  ```typescript
97
99
  const tracking = await client.shipping.track('9400111899223456789012');
98
100
 
99
- for (const event of tracking.data.events) {
101
+ for (const event of tracking.events) {
100
102
  console.log(`${event.timestamp}: ${event.description}`);
101
103
  }
102
104
  ```
@@ -113,8 +115,10 @@ const result = await client.shipping.validateAddress({
113
115
  country: 'US',
114
116
  });
115
117
 
116
- if (!result.data.isValid) {
117
- console.log('Corrected:', result.data.correctedAddress);
118
+ if (result.validationUnavailable) {
119
+ console.log('Validation is unavailable right now; isValid is not a verdict.');
120
+ } else if (!result.isValid) {
121
+ console.log('Suggested:', result.suggestedAddress, result.warnings);
118
122
  }
119
123
  ```
120
124
 
@@ -135,106 +139,112 @@ const batch = await client.shipping.createBatch({
135
139
  const status = await client.shipping.getBatchStatus(batch.data.jobId);
136
140
  ```
137
141
 
138
- ## Direct Carrier Access
142
+ ## Carrier-Specific Calls
139
143
 
140
- For full control, use carrier-specific endpoints:
144
+ Rates, labels, voids, pickups and scan forms go through `client.shipping`, `client.pickups` and
145
+ `client.scanForms`, which work for every carrier and with API keys. `client.carriers` reaches
146
+ carrier-specific endpoints through the Gateway's legacy pass-through, which is deprecated and
147
+ retired on 2027-06-30:
141
148
 
142
- ### USPS
149
+ - **Lookups (GET)** work with API keys.
150
+ - **Writes** (for example `carriers.usps.getDomesticRates`, `carriers.fedex.createPickup`) are marked
151
+ `@deprecated`. They need a user token (`auth.login`): the Gateway answers an API key with 403
152
+ `API_KEY_SCOPE_REQUIRED`. Move them to the native resources above.
153
+ - **Label purchases** through the pass-through are closed by the Gateway (410), so the SDK has no
154
+ carrier-specific label methods; buy labels with `client.shipping.createLabel`.
143
155
 
144
156
  ```typescript
145
- // Domestic label with full USPS payload
146
- const label = await client.carriers.usps.createDomesticLabel({
147
- imageType: 'PDF',
148
- mailClass: 'PRIORITY_MAIL',
149
- weightInOunces: 16,
150
- // ... full USPS API payload
151
- });
152
-
153
- // Rate calculation
154
- const rates = await client.carriers.usps.getDomesticRates({
155
- originZIPCode: '10001',
156
- destinationZIPCode: '90210',
157
- weight: 1.0,
158
- });
159
-
160
- // Find drop-off locations
161
- const locations = await client.carriers.usps.findDropOffLocations({
162
- zipCode: '10001',
163
- });
164
- ```
165
-
166
- ### UPS
167
-
168
- ```typescript
169
- const label = await client.carriers.ups.createLabel({ /* UPS payload */ });
170
- const rates = await client.carriers.ups.getRates({ /* UPS payload */ });
171
- const tracking = await client.carriers.ups.track({ trackingNumber: '1Z...' });
172
- const transitTimes = await client.carriers.ups.getTransitTimes({ /* payload */ });
173
- ```
174
-
175
- ### FedEx
176
-
177
- ```typescript
178
- const shipment = await client.carriers.fedex.createShipment({ /* FedEx payload */ });
179
- const rates = await client.carriers.fedex.getRates({ /* FedEx payload */ });
180
- const tracking = await client.carriers.fedex.track({ /* payload */ });
181
-
182
- // Multi-package (Open Ship)
183
- await client.carriers.fedex.createOpenShipment({ /* payload */ });
184
- await client.carriers.fedex.addPackagesToOpenShipment({ /* payload */ });
185
- await client.carriers.fedex.confirmOpenShipment({ /* payload */ });
186
- ```
187
-
188
- ### DHL
189
-
190
- ```typescript
191
- const shipment = await client.carriers.dhl.createShipment({ /* DHL payload */ });
192
- const rates = await client.carriers.dhl.getRates({ countryCode: 'US', weight: '1' });
193
- const tracking = await client.carriers.dhl.track({ shipmentTrackingNumber: '123456' });
194
- const landedCost = await client.carriers.dhl.calculateLandedCost({ /* payload */ });
157
+ const city = await client.carriers.usps.cityStateLookup('10001');
158
+ const locations = await client.carriers.usps.findDropOffLocations({ zipCode: '10001' });
159
+ const upsTracking = await client.carriers.ups.track({ trackingNumber: '1Z...' });
160
+ const dhlRates = await client.carriers.dhl.getRates({ countryCode: 'US', weight: '1' });
195
161
  ```
196
162
 
197
163
  ## Workspace Management
198
164
 
199
165
  ```typescript
166
+ import { WorkspaceRole } from '@flexops/sdk';
167
+
200
168
  // List workspaces
201
169
  const workspaces = await client.workspaces.list();
202
170
 
203
171
  // Switch workspace
204
172
  client.workspaceId = 'different-workspace-id';
205
173
 
206
- // Invite a member
207
- await client.workspaces.inviteMember('newuser@company.com', 'Member');
174
+ // Members and pending invites
175
+ const { data } = await client.workspaces.listMembers();
176
+ console.log(data.members.length, data.pendingInvites.length);
177
+
178
+ // Invite a member (roles are numbers on the wire; use WorkspaceRole)
179
+ await client.workspaces.inviteMember('newuser@company.com', WorkspaceRole.Member);
208
180
  ```
209
181
 
210
182
  ## Webhooks
211
183
 
212
184
  ```typescript
213
- // Create a subscription
185
+ import { WebhookEventType } from '@flexops/sdk';
186
+
187
+ // Create a subscription. Omit `events` to receive every event.
214
188
  const webhook = await client.webhooks.create({
215
189
  url: 'https://your-app.com/webhooks/flexops',
216
- events: ['label.created', 'tracking.updated', 'shipment.delivered'],
190
+ events: [WebhookEventType.LabelCreated, WebhookEventType.LabelCanceled, WebhookEventType.BatchCompleted],
217
191
  });
192
+ const signingSecret = webhook.data.secret; // returned only on create; store it
218
193
 
219
194
  // Rotate the signing secret
220
195
  await client.webhooks.rotateSecret(webhook.data.id);
196
+ ```
197
+
198
+ FlexOps sends these events, named exactly as below. Names are PascalCase and matched exactly, so a
199
+ name like `label.created` would never match; the SDK refuses unknown names with an
200
+ `UnknownWebhookEvent` error.
221
201
 
222
- // Verify incoming webhook signatures in your handler
202
+ | Event | Sent when |
203
+ |---|---|
204
+ | `LabelCreated` | A live label is purchased (sandbox labels send nothing) |
205
+ | `LabelCanceled` | A live label is voided |
206
+ | `BatchCompleted` | A batch label job finishes |
207
+ | `TrackingUpdated` | A USPS tracking scan arrives (USPS push-tracking pilot workspaces only) |
208
+ | `TrackingDelivered` | A USPS package is delivered (USPS push-tracking pilot workspaces only) |
209
+
210
+ ### Verifying deliveries
211
+
212
+ Each delivery is a `POST` whose body is the event data itself (there is no `{ type, data }`
213
+ envelope). The headers carry the rest:
214
+
215
+ | Header | Value |
216
+ |---|---|
217
+ | `X-FlexOps-Event` | Event name, e.g. `LabelCreated`; `test` for a test delivery |
218
+ | `X-FlexOps-Event-Id` | Event ID; use it to ignore retried duplicates |
219
+ | `X-FlexOps-Timestamp` | Unix seconds when the delivery was signed |
220
+ | `X-FlexOps-Signature` | `sha256=` + hex HMAC-SHA256 of `{timestamp}.{raw body}`, keyed with your `whsec_...` secret |
221
+ | `X-FlexOps-Delivery` | Delivery attempt ID |
222
+
223
+ Verify against the raw body bytes. Re-serializing parsed JSON (`JSON.stringify(req.body)`) does not
224
+ reproduce what was signed.
225
+
226
+ ```typescript
227
+ import express from 'express';
223
228
  import { WebhooksResource } from '@flexops/sdk';
224
229
 
225
- app.post('/webhooks/flexops', (req, res) => {
226
- const signature = req.headers['x-flexops-signature'];
230
+ app.post('/webhooks/flexops', express.raw({ type: 'application/json' }), (req, res) => {
227
231
  const isValid = WebhooksResource.verifySignature(
228
- JSON.stringify(req.body),
229
- signature,
230
- process.env.FLEXOPS_WEBHOOK_SECRET,
232
+ req.body, // raw Buffer from express.raw()
233
+ req.header('x-flexops-signature'),
234
+ process.env.FLEXOPS_WEBHOOK_SECRET!,
235
+ req.header('x-flexops-timestamp'), // rejected if more than 300 s from now
231
236
  );
232
-
233
237
  if (!isValid) return res.status(401).send('Invalid signature');
234
- // Process webhook...
238
+
239
+ const eventType = req.header('x-flexops-event'); // 'LabelCreated', 'TrackingUpdated', 'test', ...
240
+ const data = JSON.parse(req.body.toString('utf8')); // the event data; no envelope
241
+ // Process the event...
242
+ res.sendStatus(200);
235
243
  });
236
244
  ```
237
245
 
246
+ Pass `{ toleranceSeconds }` as a fifth argument to change the 300 second timestamp window.
247
+
238
248
  ## Curl Quickstart
239
249
 
240
250
  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:
@@ -250,44 +260,37 @@ curl -X POST https://gateway.flexops.io/api/shipping/rates \
250
260
  "package": {"weight": 16, "weightUnit": "oz"}
251
261
  }'
252
262
 
253
- # Create a label
254
- curl -X POST https://gateway.flexops.io/api/workspaces/ws_abc123/shipping/labels \
263
+ # Create a label (hazmatClassification 0 = not hazardous; required when there is no orderId)
264
+ curl -X POST https://gateway.flexops.io/api/shipping/labels \
255
265
  -H "X-API-Key: fxk_live_..." \
256
266
  -H "Content-Type: application/json" \
257
267
  -d '{
258
- "carrier": "USPS",
259
- "service": "PRIORITY_MAIL",
260
- "fromAddress": {"name": "Warehouse", "street1": "123 Main St", "city": "New York", "state": "NY", "zip": "10001", "country": "US"},
261
- "toAddress": {"name": "Customer", "street1": "456 Oak Ave", "city": "Los Angeles", "state": "CA", "zip": "90210", "country": "US"},
262
- "parcel": {"weight": 16, "weightUnit": "oz"}
268
+ "carrierCode": "USPS",
269
+ "serviceCode": "PRIORITY",
270
+ "origin": {"name": "Warehouse", "addressLine1": "123 Main St", "city": "New York", "stateProvince": "NY", "postalCode": "10001", "countryCode": "US"},
271
+ "destination": {"name": "Customer", "addressLine1": "456 Oak Ave", "city": "Los Angeles", "stateProvince": "CA", "postalCode": "90210", "countryCode": "US"},
272
+ "package": {"weight": 16, "weightUnit": "oz"},
273
+ "hazmatClassification": 0
263
274
  }'
264
275
 
265
276
  # Track a shipment
266
- curl https://gateway.flexops.io/api/workspaces/ws_abc123/shipping/track/9400111899223456789012 \
277
+ curl https://gateway.flexops.io/api/shipping/track/9400111899223456789012 \
267
278
  -H "X-API-Key: fxk_live_..."
268
279
 
269
- # Cancel a label (via the unified carrier-agnostic endpoint)
270
- curl -X DELETE https://gateway.flexops.io/api/v3.0/shipping/Usps/cancel/9400111899223456789012 \
280
+ # Cancel (void) a label
281
+ curl -X DELETE "https://gateway.flexops.io/api/shipping/labels/{labelId}?carrierCode=usps" \
271
282
  -H "X-API-Key: fxk_live_..."
272
283
  ```
273
284
 
274
285
  Use an `fxk_test_...` key instead of `fxk_live_...` to hit the sandbox environment; mock carriers respond, no real charges, no real labels.
275
286
 
276
- ## Wallet & Billing
277
-
278
- ```typescript
279
- const balance = await client.wallet.getBalance();
280
- console.log(`Balance: $${balance.data.balance}`);
287
+ ## Wallet
281
288
 
282
- // Add funds
283
- await client.wallet.addFunds(100.00);
289
+ The balance is read-only here; funding and auto-reload are managed in the FlexOps portal.
284
290
 
285
- // Configure auto-reload
286
- await client.wallet.configureAutoReload({
287
- enabled: true,
288
- threshold: 25.00,
289
- amount: 100.00,
290
- });
291
+ ```typescript
292
+ const balance = await client.wallet.getBalance(); // for client.workspaceId
293
+ console.log(`Balance: $${balance.balance}`);
291
294
  ```
292
295
 
293
296
  ## Insurance
@@ -298,38 +301,92 @@ const providers = await client.insurance.getProviders();
298
301
  // Returns ["FlexOps"] or ["FlexOps", "U-PIC"]
299
302
 
300
303
  // Get a quote
301
- const quote = await client.insurance.getQuote({
302
- carrier: 'USPS',
303
- declaredValue: 500.00,
304
- provider: 'FlexOps',
305
- });
304
+ const quote = await client.insurance.getQuote({ carrierCode: 'usps', declaredValue: 500.00 });
306
305
 
307
- // Purchase insurance
306
+ // Purchase insurance (premium charged to the wallet). A shipment already insured is refused
307
+ // with 409 ALREADY_EXISTS.
308
308
  const policy = await client.insurance.purchase({
309
309
  trackingNumber: '9400111899223456789012',
310
- carrier: 'USPS',
310
+ carrierCode: 'usps',
311
311
  declaredValue: 500.00,
312
312
  });
313
+
314
+ // File a claim
315
+ await client.insurance.fileClaim({ policyId: policy.data.policyId, claimReason: 'Lost in transit', claimAmount: 500.00 });
316
+ ```
317
+
318
+ ## Carbon Offsets
319
+
320
+ ```typescript
321
+ const quote = await client.carbonOffsets.quote({ weightLbs: 2, distanceMiles: 800 });
322
+ const offset = await client.carbonOffsets.purchase({ trackingNumber: '9400...', weightLbs: 2, distanceMiles: 800 });
323
+ const summary = await client.carbonOffsets.getSummary();
313
324
  ```
314
325
 
315
326
  ## Returns & RMA
316
327
 
317
328
  ```typescript
318
- // Create a return authorization
329
+ // Create a return authorization for an order (numeric order id)
319
330
  const rma = await client.returns.create({
320
- orderId: 'ORD-12345',
331
+ orderId: 12345,
321
332
  reason: 'Defective product',
322
333
  items: [{ sku: 'WIDGET-001', quantity: 1 }],
323
334
  });
324
335
 
325
- // Approve and generate return label
326
- await client.returns.approve(rma.data.rmaId);
327
- await client.returns.generateLabel(rma.data.rmaId);
336
+ // Generate the return label. Send the package weight and size. Anything left out comes from the
337
+ // workspace's default shipping preset; with no preset the API answers 400 PackageMeasurementsRequired.
338
+ await client.returns.generateLabel('RMA-12345', {
339
+ weightOz: 16,
340
+ lengthIn: 10,
341
+ widthIn: 8,
342
+ heightIn: 4,
343
+ });
328
344
 
329
- // Mark items as received
330
- await client.returns.markReceived(rma.data.rmaId, [
331
- { sku: 'WIDGET-001', quantity: 1, condition: 'damaged' },
332
- ]);
345
+ // Record the inspected items at a warehouse (disposition 0 restock, 1 refurbish, 2 dispose)
346
+ await client.returns.markReceived(rmaId, {
347
+ rmaNumber: 'RMA-12345',
348
+ warehouseId: 1,
349
+ inspectedItems: [{ partNumber: 'WIDGET-001', quantity: 1, disposition: 2 }],
350
+ });
351
+ ```
352
+
353
+ Approving, rejecting, cancelling and refunding returns are done in the FlexOps portal.
354
+
355
+ ## Recurring Shipments, Report Schedules and Email Templates
356
+
357
+ Reads work with any API key. Writes need a user token (`auth.login`) or an API key granted the
358
+ resource's write permission: `recurring-shipments:write`, `report-schedules:write` or
359
+ `email-templates:write`. Other keys get 403 `API_KEY_SCOPE_REQUIRED`.
360
+
361
+ ```typescript
362
+ import { RecurrenceInterval, ReportFormat, ReportFrequency, TrackingEmailEvent } from '@flexops/sdk';
363
+
364
+ // Ship the same package to a saved address every week
365
+ const recurring = await client.recurringShipments.create({
366
+ name: 'Weekly refill',
367
+ addressId: 'address-guid',
368
+ presetId: 'preset-guid',
369
+ interval: RecurrenceInterval.Weekly,
370
+ firstRunUtc: '2026-11-02T15:00:00Z',
371
+ });
372
+ await client.recurringShipments.trigger(recurring.id); // run now (creates an order)
373
+
374
+ // Email a shipments report every Monday at 08:00 UTC
375
+ await client.reportSchedules.create({
376
+ reportType: 'shipments',
377
+ format: ReportFormat.Csv,
378
+ frequencyType: ReportFrequency.Weekly,
379
+ dayOfWeek: 1,
380
+ timeOfDayUtc: '08:00:00',
381
+ recipientEmails: 'ops@example.com',
382
+ });
383
+
384
+ // Customize the "delivered" tracking email
385
+ await client.emailTemplates.upsert({
386
+ eventType: TrackingEmailEvent.Delivered,
387
+ subjectTemplate: 'Your order has arrived',
388
+ htmlBodyTemplate: '<p>Delivered.</p>',
389
+ });
333
390
  ```
334
391
 
335
392
  ## Analytics
@@ -352,7 +409,7 @@ const performance = await client.analytics.deliveryPerformance();
352
409
  // Create a shipping rule
353
410
  await client.rules.create({
354
411
  name: 'Route light packages via USPS',
355
- isActive: true,
412
+ isEnabled: true,
356
413
  priority: 1,
357
414
  conditions: [
358
415
  { field: 'Weight', operator: 'LessThan', value: '16' },
@@ -363,6 +420,9 @@ await client.rules.create({
363
420
  { type: 'SetService', value: 'GROUND_ADVANTAGE' },
364
421
  ],
365
422
  });
423
+
424
+ // Dry-run the rules against a sample shipment
425
+ const result = await client.rules.test({ weightOz: 12, declaredValue: 25, destinationCountry: 'US', itemCount: 1 });
366
426
  ```
367
427
 
368
428
  ## Error Handling
@@ -403,6 +463,21 @@ const client = new FlexOps({
403
463
  });
404
464
  ```
405
465
 
466
+ ## Retries
467
+
468
+ Requests that fail with a network error, a timeout or a 429/502/503/504 are retried with
469
+ exponential backoff (`retry.maxRetries`, default 3). Retries are safe for purchases:
470
+
471
+ - Every `POST`, `PUT` and `PATCH` sends an `Idempotency-Key`: yours if you pass one, otherwise one
472
+ generated per call and reused on every retry of that call. The Gateway answers a repeated key with
473
+ the first result instead of running the request again. Pass your own key to purchases
474
+ (`insurance.purchase(request, key)`, `carbonOffsets.purchase(request, key)`) and store it, so a retry
475
+ your app makes after an error or a timeout reuses it and cannot buy twice.
476
+ - A write is never retried after a `500`, whose result the Gateway does not replay. A `409
477
+ IDEMPOTENCY_CONFLICT` (the first attempt is still running) is retried. A key reused with a different
478
+ request gets `422 IDEMPOTENCY_KEY_REUSED`, which is not retried: use a new key for a new request.
479
+ - `DELETE` is retried only on `429`. `GET` is retried on every status in `retryableStatusCodes`.
480
+
406
481
  ## OpenAPI Spec Generation
407
482
 
408
483
  The SDK includes tooling to generate TypeScript types from the live API spec: