@flexops/sdk 1.1.0 → 2.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
@@ -52,63 +52,43 @@ await client.auth.login({
52
52
  ### Rate Shopping
53
53
 
54
54
  ```typescript
55
+ const rateRequest = {
56
+ origin: { addressLine1: '123 Main St', city: 'New York', stateProvince: 'NY', postalCode: '10001' },
57
+ destination: { addressLine1: '456 Oak Ave', city: 'Los Angeles', stateProvince: 'CA', postalCode: '90210' },
58
+ package: { weight: 16, weightUnit: 'oz' },
59
+ };
60
+
55
61
  // 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
+ const rates = await client.shipping.getRates(rateRequest);
62
63
 
63
64
  // Get the single cheapest rate
64
- const cheapest = await client.shipping.getCheapestRate({
65
- fromZip: '10001',
66
- toZip: '90210',
67
- weight: 16,
68
- });
65
+ const cheapest = await client.shipping.getCheapestRate(rateRequest);
69
66
 
70
67
  // Get the single fastest rate
71
- const fastest = await client.shipping.getFastestRate({
72
- fromZip: '10001',
73
- toZip: '90210',
74
- weight: 16,
75
- });
68
+ const fastest = await client.shipping.getFastestRate(rateRequest);
76
69
  ```
77
70
 
78
71
  ### Create a Shipping Label
79
72
 
80
73
  ```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
74
+ const operation = await client.shipping.prepareLabel({
75
+ ...rateRequest, carrierCode: 'USPS', serviceCode: 'PRIORITY',
76
+ }, 10.00, crypto.randomUUID());
77
+ if (operation.preview) console.log({ quote: operation.preview.quotedPostageAmount,
78
+ maximum: operation.preview.maximumPostageAmount, currency: operation.preview.currency,
79
+ expiresAt: operation.preview.expiresAt }); // omit the signed token from display/logs
80
+ // Keep operation securely with the original Gateway and API-key identity.
81
+
82
+ // In a terminal example, ask explicitly before any live purchase:
83
+ const { createInterface } = await import('node:readline/promises');
84
+ const prompt = createInterface({ input: process.stdin, output: process.stdout });
85
+ try {
86
+ const approved = operation.sandboxLabel || await prompt.question('Type approve to buy at the displayed maximum (later adjustments/fees excluded): ') === 'approve';
87
+ if (approved) {
88
+ const label = await client.shipping.purchaseLabel(operation);
89
+ console.log(label.trackingNumber);
90
+ }
91
+ } finally { prompt.close(); }
112
92
  ```
113
93
 
114
94
  ### Tracking
@@ -261,13 +241,13 @@ Every SDK method is a thin wrapper around the FlexOps REST API. If you want to v
261
241
 
262
242
  ```bash
263
243
  # Shop rates across all connected carriers
264
- curl -X POST https://gateway.flexops.io/api/workspaces/ws_abc123/shipping/rates \
244
+ curl -X POST https://gateway.flexops.io/api/shipping/rates \
265
245
  -H "X-API-Key: fxk_live_..." \
266
246
  -H "Content-Type: application/json" \
267
247
  -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"}
248
+ "origin": {"addressLine1": "123 Main St", "city": "New York", "stateProvince": "NY", "postalCode": "10001", "countryCode": "US"},
249
+ "destination": {"addressLine1": "456 Oak Ave", "city": "Los Angeles", "stateProvince": "CA", "postalCode": "90210", "countryCode": "US"},
250
+ "package": {"weight": 16, "weightUnit": "oz"}
271
251
  }'
272
252
 
273
253
  # Create a label
@@ -447,3 +427,13 @@ npm run build
447
427
  ## License
448
428
 
449
429
  MIT © FlexOps, LLC. See [LICENSE](LICENSE) for full text.
430
+
431
+ ### Approval and retries
432
+
433
+ Use these methods only with Gateway's bounded approval contract; coordinate client/Gateway activation. Preparation does not automatically approve. The ceiling covers pre-dispatch postage, excluding later carrier adjustments and separate fees. Persist the operation securely if it must survive process restart. Retry the same request/key after response loss; OutcomeUnknown requires reconciliation, never a new purchase key. Completed replay remains possible after token expiry. Sandbox operations return a synthetic label without real postage. The legacy createLabel and USPS domestic wrapper reject preview responses; use shipping.prepareLabel/purchaseLabel for live purchases.
434
+
435
+ ## Guarded label release compatibility
436
+
437
+ This release requires a Gateway deployment with the bounded label preview/approval contract (Gateway PR #509 or later). Do not use its live label preparation against an older Gateway: older servers may purchase immediately. Upgrade the Gateway and affected callers together during a purchase maintenance window.
438
+
439
+ Live label creation now requires a USD maximum, preview, explicit approval, and replay of the saved request with its original idempotency key. Never retry an uncertain purchase with a new key. Sandbox results do not certify production postage.
package/dist/index.d.mts CHANGED
@@ -76,7 +76,20 @@ interface WorkspaceMember {
76
76
  role: 'Owner' | 'Admin' | 'Member' | 'Guest';
77
77
  joinedAt: string;
78
78
  }
79
- interface RateRequest {
79
+ type RateRequest = CanonicalRateRequest | LegacyRateRequest;
80
+ interface CanonicalRateRequest {
81
+ origin: ShippingAddress;
82
+ destination: ShippingAddress;
83
+ package: ShippingPackage;
84
+ carriers?: string[];
85
+ serviceLevels?: string[];
86
+ shipDate?: string;
87
+ includeInsurance?: boolean;
88
+ declaredValue?: number;
89
+ currency?: string;
90
+ }
91
+ /** @deprecated Use CanonicalRateRequest. The legacy shape is retained for source compatibility. */
92
+ interface LegacyRateRequest {
80
93
  fromZip: string;
81
94
  toZip: string;
82
95
  weight: number;
@@ -88,6 +101,28 @@ interface RateRequest {
88
101
  packageType?: string;
89
102
  carriers?: string[];
90
103
  }
104
+ interface ShippingAddress {
105
+ name?: string;
106
+ company?: string;
107
+ addressLine1: string;
108
+ addressLine2?: string;
109
+ city: string;
110
+ stateProvince: string;
111
+ postalCode: string;
112
+ countryCode?: string;
113
+ phone?: string;
114
+ email?: string;
115
+ isResidential?: boolean;
116
+ }
117
+ interface ShippingPackage {
118
+ weight: number;
119
+ weightUnit?: 'oz' | 'lb' | 'g' | 'kg';
120
+ length?: number;
121
+ width?: number;
122
+ height?: number;
123
+ dimensionUnit?: 'in' | 'cm';
124
+ predefinedPackage?: string;
125
+ }
91
126
  interface ShippingRate {
92
127
  carrierCode: string;
93
128
  carrierName: string;
@@ -114,6 +149,32 @@ interface CreateLabelRequest {
114
149
  labelFormat?: 'PDF' | 'PNG' | 'ZPL';
115
150
  idempotencyKey?: string;
116
151
  }
152
+ /** Normalized Gateway label request. Additional shipment options are preserved in the approval snapshot. */
153
+ interface CanonicalLabelRequest {
154
+ origin: ShippingAddress;
155
+ destination: ShippingAddress;
156
+ package: ShippingPackage;
157
+ carrierCode: string;
158
+ serviceCode: string;
159
+ orderId?: number;
160
+ labelFormat?: 'PDF' | 'PNG' | 'ZPL';
161
+ [option: string]: unknown;
162
+ }
163
+ interface LabelPurchasePreview {
164
+ status: 'Preview';
165
+ quotedPostageAmount: number;
166
+ maximumPostageAmount: number;
167
+ currency: 'USD';
168
+ expiresAt: string;
169
+ confirmationToken: string;
170
+ }
171
+ /** Retain securely for retries; requestJson contains private shipment data and the approval token. */
172
+ interface LabelPurchaseApproval {
173
+ readonly idempotencyKey: string;
174
+ readonly requestJson: string;
175
+ readonly preview: LabelPurchasePreview | null;
176
+ readonly sandboxLabel?: Label;
177
+ }
117
178
  interface Label {
118
179
  labelId: string;
119
180
  carrierCode: string;
@@ -595,7 +656,11 @@ declare class ShippingResource {
595
656
  * existing order — the order's ownership, status, ship-method and addresses are validated
596
657
  * server-side and postage is settled atomically. Returns the raw label (HTTP 201).
597
658
  */
598
- createLabel(request: CreateLabelRequest): Promise<Label>;
659
+ createLabel(request: CreateLabelRequest | CanonicalLabelRequest): Promise<Label>;
660
+ /** Preview without approval. Keep the returned immutable operation for every purchase attempt. */
661
+ prepareLabel(request: CanonicalLabelRequest, maximumPostageAmount: number, idempotencyKey: string): Promise<LabelPurchaseApproval>;
662
+ /** Call only after explicit approval. Same-key replay remains valid after token expiry. */
663
+ purchaseLabel(approval: LabelPurchaseApproval): Promise<Label>;
599
664
  /** Cancel (void) a shipping label. `carrierCode` is required. */
600
665
  cancelLabel(labelId: string, carrierCode: string): Promise<unknown>;
601
666
  /** Track a shipment by tracking number. */
@@ -1160,10 +1225,9 @@ declare class ReportsResource {
1160
1225
  *
1161
1226
  * // Get shipping rates
1162
1227
  * const rates = await client.shipping.getRates({
1163
- * fromZip: '10001',
1164
- * toZip: '90210',
1165
- * weight: 16,
1166
- * weightUnit: 'oz',
1228
+ * origin: { addressLine1: '123 Main St', city: 'New York', stateProvince: 'NY', postalCode: '10001' },
1229
+ * destination: { addressLine1: '456 Oak Ave', city: 'Los Angeles', stateProvince: 'CA', postalCode: '90210' },
1230
+ * package: { weight: 16, weightUnit: 'oz' },
1167
1231
  * });
1168
1232
  *
1169
1233
  * // Create a label with the cheapest rate
@@ -1232,4 +1296,4 @@ declare class FlexOps {
1232
1296
  setApiKey(key: string): void;
1233
1297
  }
1234
1298
 
1235
- export { type Address, type AddressValidationResult, AnalyticsResource, type ApiKeyInfo, ApiKeysResource, type ApiResponse, AuthResource, type BatchLabelJob, type BatchLabelRequest, type CarrierRecommendation, type CarrierRecommendationRequest, type CarrierRecommendationResponse, type CarrierSummary, CarriersResource, type CostSavingsSummary, type CreateApiKeyRequest, type CreateApiKeyResponse, type CreateEmailTemplateRequest, type CreateLabelRequest, type CreateRecurringShipmentRequest, type CreateReportScheduleRequest, type CreateWebhookRequest, type CreateWorkspaceRequest, type CustomsItem, type DeliveryPredictionRequest, type DeliveryPredictionResponse, type EmailTemplate, EmailTemplatesResource, type EmissionsEstimate, FlexOps, FlexOpsAuthError, type FlexOpsConfig, FlexOpsError, FlexOpsRateLimitError, type HsCodeResult, HsCodesResource, type InsurancePolicy, type InsuranceQuote, InsuranceResource, InventoryResource, type Label, type LandedCostEstimate, type LandedCostRequest, type LaneSavingsOpportunity, type LoginRequest, type LoginResponse, OffsetResource, type OffsetResult, type Order, type OrderItem, OrdersResource, type PaginatedResponse, type Parcel, type PickupConfirmation, type PickupRequest, PickupsResource, type RateRequest, type RecurringShipment, RecurringShipmentsResource, type RegisterRequest, type ReportSchedule, ReportsResource, type RetryConfig, type ReturnAuthorization, type ReturnItem, type ReturnRequest, ReturnsResource, type RuleAction, type RuleCondition, RulesResource, type ScanForm, type ScanFormRequest, ScanFormsResource, type ShipmentsTrend, type ShippingRate, ShippingResource, type ShippingRule, type TrackingEvent, type TrackingInfo, type UpdateEmailTemplateRequest, type UpdateRecurringShipmentRequest, type UpdateReportScheduleRequest, type WalletBalance, WalletResource, type WebhookSubscription, WebhooksResource, type Workspace, type WorkspaceMember, WorkspacesResource };
1299
+ export { type Address, type AddressValidationResult, AnalyticsResource, type ApiKeyInfo, ApiKeysResource, type ApiResponse, AuthResource, type BatchLabelJob, type BatchLabelRequest, type CanonicalLabelRequest, type CarrierRecommendation, type CarrierRecommendationRequest, type CarrierRecommendationResponse, type CarrierSummary, CarriersResource, type CostSavingsSummary, type CreateApiKeyRequest, type CreateApiKeyResponse, type CreateEmailTemplateRequest, type CreateLabelRequest, type CreateRecurringShipmentRequest, type CreateReportScheduleRequest, type CreateWebhookRequest, type CreateWorkspaceRequest, type CustomsItem, type DeliveryPredictionRequest, type DeliveryPredictionResponse, type EmailTemplate, EmailTemplatesResource, type EmissionsEstimate, FlexOps, FlexOpsAuthError, type FlexOpsConfig, FlexOpsError, FlexOpsRateLimitError, type HsCodeResult, HsCodesResource, type InsurancePolicy, type InsuranceQuote, InsuranceResource, InventoryResource, type Label, type LabelPurchaseApproval, type LabelPurchasePreview, type LandedCostEstimate, type LandedCostRequest, type LaneSavingsOpportunity, type LoginRequest, type LoginResponse, OffsetResource, type OffsetResult, type Order, type OrderItem, OrdersResource, type PaginatedResponse, type Parcel, type PickupConfirmation, type PickupRequest, PickupsResource, type RateRequest, type RecurringShipment, RecurringShipmentsResource, type RegisterRequest, type ReportSchedule, ReportsResource, type RetryConfig, type ReturnAuthorization, type ReturnItem, type ReturnRequest, ReturnsResource, type RuleAction, type RuleCondition, RulesResource, type ScanForm, type ScanFormRequest, ScanFormsResource, type ShipmentsTrend, type ShippingAddress, type ShippingPackage, type ShippingRate, ShippingResource, type ShippingRule, type TrackingEvent, type TrackingInfo, type UpdateEmailTemplateRequest, type UpdateRecurringShipmentRequest, type UpdateReportScheduleRequest, type WalletBalance, WalletResource, type WebhookSubscription, WebhooksResource, type Workspace, type WorkspaceMember, WorkspacesResource };
package/dist/index.d.ts CHANGED
@@ -76,7 +76,20 @@ interface WorkspaceMember {
76
76
  role: 'Owner' | 'Admin' | 'Member' | 'Guest';
77
77
  joinedAt: string;
78
78
  }
79
- interface RateRequest {
79
+ type RateRequest = CanonicalRateRequest | LegacyRateRequest;
80
+ interface CanonicalRateRequest {
81
+ origin: ShippingAddress;
82
+ destination: ShippingAddress;
83
+ package: ShippingPackage;
84
+ carriers?: string[];
85
+ serviceLevels?: string[];
86
+ shipDate?: string;
87
+ includeInsurance?: boolean;
88
+ declaredValue?: number;
89
+ currency?: string;
90
+ }
91
+ /** @deprecated Use CanonicalRateRequest. The legacy shape is retained for source compatibility. */
92
+ interface LegacyRateRequest {
80
93
  fromZip: string;
81
94
  toZip: string;
82
95
  weight: number;
@@ -88,6 +101,28 @@ interface RateRequest {
88
101
  packageType?: string;
89
102
  carriers?: string[];
90
103
  }
104
+ interface ShippingAddress {
105
+ name?: string;
106
+ company?: string;
107
+ addressLine1: string;
108
+ addressLine2?: string;
109
+ city: string;
110
+ stateProvince: string;
111
+ postalCode: string;
112
+ countryCode?: string;
113
+ phone?: string;
114
+ email?: string;
115
+ isResidential?: boolean;
116
+ }
117
+ interface ShippingPackage {
118
+ weight: number;
119
+ weightUnit?: 'oz' | 'lb' | 'g' | 'kg';
120
+ length?: number;
121
+ width?: number;
122
+ height?: number;
123
+ dimensionUnit?: 'in' | 'cm';
124
+ predefinedPackage?: string;
125
+ }
91
126
  interface ShippingRate {
92
127
  carrierCode: string;
93
128
  carrierName: string;
@@ -114,6 +149,32 @@ interface CreateLabelRequest {
114
149
  labelFormat?: 'PDF' | 'PNG' | 'ZPL';
115
150
  idempotencyKey?: string;
116
151
  }
152
+ /** Normalized Gateway label request. Additional shipment options are preserved in the approval snapshot. */
153
+ interface CanonicalLabelRequest {
154
+ origin: ShippingAddress;
155
+ destination: ShippingAddress;
156
+ package: ShippingPackage;
157
+ carrierCode: string;
158
+ serviceCode: string;
159
+ orderId?: number;
160
+ labelFormat?: 'PDF' | 'PNG' | 'ZPL';
161
+ [option: string]: unknown;
162
+ }
163
+ interface LabelPurchasePreview {
164
+ status: 'Preview';
165
+ quotedPostageAmount: number;
166
+ maximumPostageAmount: number;
167
+ currency: 'USD';
168
+ expiresAt: string;
169
+ confirmationToken: string;
170
+ }
171
+ /** Retain securely for retries; requestJson contains private shipment data and the approval token. */
172
+ interface LabelPurchaseApproval {
173
+ readonly idempotencyKey: string;
174
+ readonly requestJson: string;
175
+ readonly preview: LabelPurchasePreview | null;
176
+ readonly sandboxLabel?: Label;
177
+ }
117
178
  interface Label {
118
179
  labelId: string;
119
180
  carrierCode: string;
@@ -595,7 +656,11 @@ declare class ShippingResource {
595
656
  * existing order — the order's ownership, status, ship-method and addresses are validated
596
657
  * server-side and postage is settled atomically. Returns the raw label (HTTP 201).
597
658
  */
598
- createLabel(request: CreateLabelRequest): Promise<Label>;
659
+ createLabel(request: CreateLabelRequest | CanonicalLabelRequest): Promise<Label>;
660
+ /** Preview without approval. Keep the returned immutable operation for every purchase attempt. */
661
+ prepareLabel(request: CanonicalLabelRequest, maximumPostageAmount: number, idempotencyKey: string): Promise<LabelPurchaseApproval>;
662
+ /** Call only after explicit approval. Same-key replay remains valid after token expiry. */
663
+ purchaseLabel(approval: LabelPurchaseApproval): Promise<Label>;
599
664
  /** Cancel (void) a shipping label. `carrierCode` is required. */
600
665
  cancelLabel(labelId: string, carrierCode: string): Promise<unknown>;
601
666
  /** Track a shipment by tracking number. */
@@ -1160,10 +1225,9 @@ declare class ReportsResource {
1160
1225
  *
1161
1226
  * // Get shipping rates
1162
1227
  * const rates = await client.shipping.getRates({
1163
- * fromZip: '10001',
1164
- * toZip: '90210',
1165
- * weight: 16,
1166
- * weightUnit: 'oz',
1228
+ * origin: { addressLine1: '123 Main St', city: 'New York', stateProvince: 'NY', postalCode: '10001' },
1229
+ * destination: { addressLine1: '456 Oak Ave', city: 'Los Angeles', stateProvince: 'CA', postalCode: '90210' },
1230
+ * package: { weight: 16, weightUnit: 'oz' },
1167
1231
  * });
1168
1232
  *
1169
1233
  * // Create a label with the cheapest rate
@@ -1232,4 +1296,4 @@ declare class FlexOps {
1232
1296
  setApiKey(key: string): void;
1233
1297
  }
1234
1298
 
1235
- export { type Address, type AddressValidationResult, AnalyticsResource, type ApiKeyInfo, ApiKeysResource, type ApiResponse, AuthResource, type BatchLabelJob, type BatchLabelRequest, type CarrierRecommendation, type CarrierRecommendationRequest, type CarrierRecommendationResponse, type CarrierSummary, CarriersResource, type CostSavingsSummary, type CreateApiKeyRequest, type CreateApiKeyResponse, type CreateEmailTemplateRequest, type CreateLabelRequest, type CreateRecurringShipmentRequest, type CreateReportScheduleRequest, type CreateWebhookRequest, type CreateWorkspaceRequest, type CustomsItem, type DeliveryPredictionRequest, type DeliveryPredictionResponse, type EmailTemplate, EmailTemplatesResource, type EmissionsEstimate, FlexOps, FlexOpsAuthError, type FlexOpsConfig, FlexOpsError, FlexOpsRateLimitError, type HsCodeResult, HsCodesResource, type InsurancePolicy, type InsuranceQuote, InsuranceResource, InventoryResource, type Label, type LandedCostEstimate, type LandedCostRequest, type LaneSavingsOpportunity, type LoginRequest, type LoginResponse, OffsetResource, type OffsetResult, type Order, type OrderItem, OrdersResource, type PaginatedResponse, type Parcel, type PickupConfirmation, type PickupRequest, PickupsResource, type RateRequest, type RecurringShipment, RecurringShipmentsResource, type RegisterRequest, type ReportSchedule, ReportsResource, type RetryConfig, type ReturnAuthorization, type ReturnItem, type ReturnRequest, ReturnsResource, type RuleAction, type RuleCondition, RulesResource, type ScanForm, type ScanFormRequest, ScanFormsResource, type ShipmentsTrend, type ShippingRate, ShippingResource, type ShippingRule, type TrackingEvent, type TrackingInfo, type UpdateEmailTemplateRequest, type UpdateRecurringShipmentRequest, type UpdateReportScheduleRequest, type WalletBalance, WalletResource, type WebhookSubscription, WebhooksResource, type Workspace, type WorkspaceMember, WorkspacesResource };
1299
+ export { type Address, type AddressValidationResult, AnalyticsResource, type ApiKeyInfo, ApiKeysResource, type ApiResponse, AuthResource, type BatchLabelJob, type BatchLabelRequest, type CanonicalLabelRequest, type CarrierRecommendation, type CarrierRecommendationRequest, type CarrierRecommendationResponse, type CarrierSummary, CarriersResource, type CostSavingsSummary, type CreateApiKeyRequest, type CreateApiKeyResponse, type CreateEmailTemplateRequest, type CreateLabelRequest, type CreateRecurringShipmentRequest, type CreateReportScheduleRequest, type CreateWebhookRequest, type CreateWorkspaceRequest, type CustomsItem, type DeliveryPredictionRequest, type DeliveryPredictionResponse, type EmailTemplate, EmailTemplatesResource, type EmissionsEstimate, FlexOps, FlexOpsAuthError, type FlexOpsConfig, FlexOpsError, FlexOpsRateLimitError, type HsCodeResult, HsCodesResource, type InsurancePolicy, type InsuranceQuote, InsuranceResource, InventoryResource, type Label, type LabelPurchaseApproval, type LabelPurchasePreview, type LandedCostEstimate, type LandedCostRequest, type LaneSavingsOpportunity, type LoginRequest, type LoginResponse, OffsetResource, type OffsetResult, type Order, type OrderItem, OrdersResource, type PaginatedResponse, type Parcel, type PickupConfirmation, type PickupRequest, PickupsResource, type RateRequest, type RecurringShipment, RecurringShipmentsResource, type RegisterRequest, type ReportSchedule, ReportsResource, type RetryConfig, type ReturnAuthorization, type ReturnItem, type ReturnRequest, ReturnsResource, type RuleAction, type RuleCondition, RulesResource, type ScanForm, type ScanFormRequest, ScanFormsResource, type ShipmentsTrend, type ShippingAddress, type ShippingPackage, type ShippingRate, ShippingResource, type ShippingRule, type TrackingEvent, type TrackingInfo, type UpdateEmailTemplateRequest, type UpdateRecurringShipmentRequest, type UpdateReportScheduleRequest, type WalletBalance, WalletResource, type WebhookSubscription, WebhooksResource, type Workspace, type WorkspaceMember, WorkspacesResource };
package/dist/index.js CHANGED
@@ -153,7 +153,7 @@ var HttpClient = class {
153
153
  const error = new FlexOpsError(
154
154
  errorBody.message ?? `HTTP ${response.status}: ${response.statusText}`,
155
155
  response.status,
156
- void 0,
156
+ errorBody.code ?? errorBody.errorCode,
157
157
  errorBody.errors
158
158
  );
159
159
  if (this.retry.retryableStatusCodes.includes(response.status)) {
@@ -372,7 +372,37 @@ var ShippingResource = class {
372
372
  * server-side and postage is settled atomically. Returns the raw label (HTTP 201).
373
373
  */
374
374
  async createLabel(request) {
375
- return this.http.post("/api/shipping/labels", request, void 0);
375
+ const result = await this.http.post("/api/shipping/labels", request);
376
+ if ("status" in result) throw new FlexOpsError("Approval required. Use prepareLabel, review its preview, then purchaseLabel.", 400, "ApprovalRequired");
377
+ return result;
378
+ }
379
+ /** Preview without approval. Keep the returned immutable operation for every purchase attempt. */
380
+ async prepareLabel(request, maximumPostageAmount, idempotencyKey) {
381
+ if (!idempotencyKey.trim() || !Number.isFinite(maximumPostageAmount) || maximumPostageAmount <= 0 || maximumPostageAmount > 1e6 || Math.abs(maximumPostageAmount * 100 - Math.round(maximumPostageAmount * 100)) > 1e-7)
382
+ throw new FlexOpsError("Supply a stable key and positive USD maximum with at most two decimal places.", 400, "InvalidApproval");
383
+ const body = JSON.parse(JSON.stringify(request));
384
+ for (const key of Object.keys(body)) if (["confirmationtoken", "maximumpostageamount"].includes(key.toLowerCase())) delete body[key];
385
+ body.maximumPostageAmount = maximumPostageAmount;
386
+ const result = await this.http.request("POST", "/api/shipping/labels", {
387
+ body,
388
+ headers: { "Idempotency-Key": idempotencyKey }
389
+ });
390
+ if ("isSandbox" in result && result.isSandbox === true)
391
+ return Object.freeze({ idempotencyKey, requestJson: JSON.stringify(body), preview: null, sandboxLabel: result });
392
+ if (!("status" in result) || result.status !== "Preview" || !result.confirmationToken || result.currency !== "USD" || !Number.isFinite(result.quotedPostageAmount) || result.quotedPostageAmount <= 0 || result.quotedPostageAmount > maximumPostageAmount || result.maximumPostageAmount !== maximumPostageAmount || !Number.isFinite(Date.parse(result.expiresAt)))
393
+ throw new FlexOpsError("Gateway did not return a valid bounded preview.", 502, "InvalidPreview");
394
+ body.confirmationToken = result.confirmationToken;
395
+ return Object.freeze({ idempotencyKey, requestJson: JSON.stringify(body), preview: Object.freeze(result) });
396
+ }
397
+ /** Call only after explicit approval. Same-key replay remains valid after token expiry. */
398
+ async purchaseLabel(approval) {
399
+ if (approval.sandboxLabel) return approval.sandboxLabel;
400
+ const result = await this.http.request("POST", "/api/shipping/labels", {
401
+ body: JSON.parse(approval.requestJson),
402
+ headers: { "Idempotency-Key": approval.idempotencyKey }
403
+ });
404
+ if (!result.trackingNumber) throw new FlexOpsError("Unresolved purchase. Retain the operation and reconcile before creating another label.", 409, "OutcomeUnknown");
405
+ return result;
376
406
  }
377
407
  /** Cancel (void) a shipping label. `carrierCode` is required. */
378
408
  async cancelLabel(labelId, carrierCode) {
@@ -469,7 +499,7 @@ var CarriersResource = class {
469
499
  // Domestic USPS labels go through the reliable order-based Gateway path
470
500
  // (POST /api/shipping/labels): pass a LabelRequest body with carrierCode:'USPS'
471
501
  // and orderId set — server-side order validation + atomic postage settlement.
472
- createDomesticLabel: (body) => this.http.post("/api/shipping/labels", body),
502
+ createDomesticLabel: (body) => new ShippingResource(this.http, () => void 0).createLabel(body),
473
503
  /** Generate a domestic return label. */
474
504
  createReturnLabel: (body) => this.http.post(this.proxy("api/v3/Shipping/postUspsGenerateDomesticReturnsShippingLabel"), body),
475
505
  /** Generate an international shipping label. */
package/dist/index.mjs CHANGED
@@ -111,7 +111,7 @@ var HttpClient = class {
111
111
  const error = new FlexOpsError(
112
112
  errorBody.message ?? `HTTP ${response.status}: ${response.statusText}`,
113
113
  response.status,
114
- void 0,
114
+ errorBody.code ?? errorBody.errorCode,
115
115
  errorBody.errors
116
116
  );
117
117
  if (this.retry.retryableStatusCodes.includes(response.status)) {
@@ -330,7 +330,37 @@ var ShippingResource = class {
330
330
  * server-side and postage is settled atomically. Returns the raw label (HTTP 201).
331
331
  */
332
332
  async createLabel(request) {
333
- return this.http.post("/api/shipping/labels", request, void 0);
333
+ const result = await this.http.post("/api/shipping/labels", request);
334
+ if ("status" in result) throw new FlexOpsError("Approval required. Use prepareLabel, review its preview, then purchaseLabel.", 400, "ApprovalRequired");
335
+ return result;
336
+ }
337
+ /** Preview without approval. Keep the returned immutable operation for every purchase attempt. */
338
+ async prepareLabel(request, maximumPostageAmount, idempotencyKey) {
339
+ if (!idempotencyKey.trim() || !Number.isFinite(maximumPostageAmount) || maximumPostageAmount <= 0 || maximumPostageAmount > 1e6 || Math.abs(maximumPostageAmount * 100 - Math.round(maximumPostageAmount * 100)) > 1e-7)
340
+ throw new FlexOpsError("Supply a stable key and positive USD maximum with at most two decimal places.", 400, "InvalidApproval");
341
+ const body = JSON.parse(JSON.stringify(request));
342
+ for (const key of Object.keys(body)) if (["confirmationtoken", "maximumpostageamount"].includes(key.toLowerCase())) delete body[key];
343
+ body.maximumPostageAmount = maximumPostageAmount;
344
+ const result = await this.http.request("POST", "/api/shipping/labels", {
345
+ body,
346
+ headers: { "Idempotency-Key": idempotencyKey }
347
+ });
348
+ if ("isSandbox" in result && result.isSandbox === true)
349
+ return Object.freeze({ idempotencyKey, requestJson: JSON.stringify(body), preview: null, sandboxLabel: result });
350
+ if (!("status" in result) || result.status !== "Preview" || !result.confirmationToken || result.currency !== "USD" || !Number.isFinite(result.quotedPostageAmount) || result.quotedPostageAmount <= 0 || result.quotedPostageAmount > maximumPostageAmount || result.maximumPostageAmount !== maximumPostageAmount || !Number.isFinite(Date.parse(result.expiresAt)))
351
+ throw new FlexOpsError("Gateway did not return a valid bounded preview.", 502, "InvalidPreview");
352
+ body.confirmationToken = result.confirmationToken;
353
+ return Object.freeze({ idempotencyKey, requestJson: JSON.stringify(body), preview: Object.freeze(result) });
354
+ }
355
+ /** Call only after explicit approval. Same-key replay remains valid after token expiry. */
356
+ async purchaseLabel(approval) {
357
+ if (approval.sandboxLabel) return approval.sandboxLabel;
358
+ const result = await this.http.request("POST", "/api/shipping/labels", {
359
+ body: JSON.parse(approval.requestJson),
360
+ headers: { "Idempotency-Key": approval.idempotencyKey }
361
+ });
362
+ if (!result.trackingNumber) throw new FlexOpsError("Unresolved purchase. Retain the operation and reconcile before creating another label.", 409, "OutcomeUnknown");
363
+ return result;
334
364
  }
335
365
  /** Cancel (void) a shipping label. `carrierCode` is required. */
336
366
  async cancelLabel(labelId, carrierCode) {
@@ -427,7 +457,7 @@ var CarriersResource = class {
427
457
  // Domestic USPS labels go through the reliable order-based Gateway path
428
458
  // (POST /api/shipping/labels): pass a LabelRequest body with carrierCode:'USPS'
429
459
  // and orderId set — server-side order validation + atomic postage settlement.
430
- createDomesticLabel: (body) => this.http.post("/api/shipping/labels", body),
460
+ createDomesticLabel: (body) => new ShippingResource(this.http, () => void 0).createLabel(body),
431
461
  /** Generate a domestic return label. */
432
462
  createReturnLabel: (body) => this.http.post(this.proxy("api/v3/Shipping/postUspsGenerateDomesticReturnsShippingLabel"), body),
433
463
  /** Generate an international shipping label. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flexops/sdk",
3
- "version": "1.1.0",
3
+ "version": "2.0.0",
4
4
  "description": "Official FlexOps Platform Node.js/TypeScript SDK — multi-carrier shipping, order management, and logistics API",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -60,6 +60,6 @@
60
60
  "tsup": "^8.4.0",
61
61
  "typescript": "^5.8.0",
62
62
  "typescript-eslint": "^8.65.0",
63
- "vitest": "^4.1.10"
63
+ "vitest": "^5.0.0"
64
64
  }
65
65
  }