@astratra/shipping 0.0.0-stage → 1.1.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/src/index.d.ts ADDED
@@ -0,0 +1,208 @@
1
+ import type { EventLog, WebhookHandler, WebhookLogger, Outcome } from '@astratra/payments';
2
+
3
+ /* ─────────────────── Errors ─────────────────── */
4
+
5
+ export const CODES: Readonly<{
6
+ NOT_CONFIGURED: 'not_configured';
7
+ CREDENTIALS_REFUSED: 'credentials_refused';
8
+ UNAVAILABLE: 'unavailable';
9
+ REJECTED: 'rejected';
10
+ NOT_FOUND: 'not_found';
11
+ CANCEL_REFUSED: 'cancel_refused';
12
+ NO_METHOD: 'no_method';
13
+ SERVICE_POINTS_UNAVAILABLE: 'service_points_unavailable';
14
+ INVALID_INPUT: 'invalid_input';
15
+ UNEXPECTED_RESPONSE: 'unexpected_response';
16
+ }>;
17
+ export type ShippingErrorCode = (typeof CODES)[keyof typeof CODES];
18
+
19
+ /** A stable code, an HTTP status to answer with, the provider's status — never its body nor a key. */
20
+ export class ShippingError extends Error {
21
+ constructor(code: ShippingErrorCode, details?: { providerStatus?: number });
22
+ code: ShippingErrorCode;
23
+ status: number;
24
+ providerStatus?: number;
25
+ }
26
+
27
+ /** The sentence for a code (or a ShippingError) in 'fr' or 'en'; French when the language is unknown. */
28
+ export function messageFor(codeOrError: ShippingErrorCode | string | ShippingError, language?: string): string;
29
+
30
+ /* ─────────────────── The carrier contract ─────────────────── */
31
+
32
+ export type ParcelStage = 'picked_up' | 'delivered' | 'incident';
33
+
34
+ export interface ShippingMethod {
35
+ /** Sendcloud: the shipping option code (for example 'colissimo:home/signature'). */
36
+ id: string;
37
+ name: string;
38
+ carrier: string;
39
+ servicePointRequired: boolean;
40
+ /** The provider's indicative price, in cents; null when unknown. */
41
+ priceCents: number | null;
42
+ }
43
+
44
+ export interface Recipient {
45
+ name: string;
46
+ line1: string;
47
+ line2?: string;
48
+ city: string;
49
+ postalCode: string;
50
+ /** ISO 3166-1 alpha-2. */
51
+ country: string;
52
+ phone?: string;
53
+ email?: string;
54
+ }
55
+
56
+ export interface Label {
57
+ /** The shipment, needed to cancel it. */
58
+ shipmentId: string;
59
+ /** The parcel, needed to download its label. */
60
+ parcelId: number;
61
+ trackingNumber: string;
62
+ trackingUrl: string;
63
+ carrier: string;
64
+ service: string;
65
+ /** The label PDF when the provider returns it with the shipment (one parcel); otherwise downloadLabel. */
66
+ label: Buffer | null;
67
+ /** The same `reference` was announced before: this is the first shipment, no new label was bought. */
68
+ alreadyExisted: boolean;
69
+ testMode: boolean;
70
+ }
71
+
72
+ export interface ServicePoint {
73
+ id: number;
74
+ carrier: string;
75
+ name: string;
76
+ address: string;
77
+ postalCode: string;
78
+ city: string;
79
+ country: string;
80
+ openingTimes: Record<string, unknown>;
81
+ distanceMeters: number | null;
82
+ }
83
+
84
+ export interface ParcelEvent {
85
+ parcelId: number;
86
+ trackingNumber: string;
87
+ trackingUrl: string;
88
+ /** The provider's status label. */
89
+ message: string;
90
+ stage: ParcelStage | null;
91
+ /** When the status changed, ALWAYS in milliseconds since 1970 (whatever unit arrived); webhooks can arrive out of order. */
92
+ timestamp: number | null;
93
+ }
94
+
95
+ export class Carrier {
96
+ get name(): string;
97
+ status(): Promise<{ configured: boolean; missing: string[]; testMode?: boolean }> | { configured: boolean; missing: string[] };
98
+ shippingMethods(query: { country: string; postalCode?: string; weightGrams: number; servicePointId?: number | string | null }): Promise<ShippingMethod[]>;
99
+ createLabel(input: {
100
+ orderNumber: string;
101
+ /** Unique per account: announcing it again returns the first shipment instead of a second label. */
102
+ reference?: string;
103
+ recipient: Recipient;
104
+ weightGrams: number;
105
+ method: { id?: string; code?: string };
106
+ servicePointId?: number | string | null;
107
+ }): Promise<Label>;
108
+ /** Paper size; default 'a6'. Sendcloud v3 has no "start from box N" for A4 sheets. */
109
+ downloadLabel(input: { parcelId: number; format?: 'a4' | 'a5' | 'a6' }): Promise<{ content: Buffer; type: 'application/pdf' }>;
110
+ cancelLabel(input: { shipmentId: string }): Promise<{ status: 'cancelled' | 'requested' }>;
111
+ servicePoints(query: {
112
+ country: string;
113
+ postalCode?: string;
114
+ city?: string;
115
+ latitude?: number;
116
+ longitude?: number;
117
+ /** Provider carrier codes, for example ['mondial_relay', 'colissimo']; the integration's carriers when omitted. */
118
+ carriers?: string[];
119
+ radiusMeters?: number;
120
+ limit?: number;
121
+ }): Promise<ServicePoint[]>;
122
+ verifySignature(rawBody: Buffer, signature: string | undefined): Promise<boolean> | boolean;
123
+ readEvent(json: unknown): ParcelEvent | null;
124
+ }
125
+
126
+ /* ─────────────────── Sendcloud ─────────────────── */
127
+
128
+ /** https://panel.sendcloud.sc/api/v3 */
129
+ export const SENDCLOUD_API_URL: string;
130
+ /** The free test shipping option: an unstamped letter, nothing is posted. */
131
+ export const TEST_SHIPPING_OPTION: 'sendcloud:letter';
132
+
133
+ type Secret = string | (() => string | Promise<string>);
134
+
135
+ export type Sender = { addressId: number; country: string } | {
136
+ name: string; companyName?: string; line1: string; line2?: string; houseNumber?: string;
137
+ city: string; postalCode: string; country: string; phone?: string; email?: string;
138
+ };
139
+
140
+ /** An event time in milliseconds since 1970 from seconds, milliseconds or an ISO date; null when unreadable. */
141
+ export function toMilliseconds(value: unknown): number | null;
142
+
143
+ export interface SendcloudOptions {
144
+ publicKey: Secret;
145
+ secretKey: Secret;
146
+ /** The integration's "Webhook Signature Key" when it has one; otherwise webhooks are signed with secretKey. */
147
+ webhookSecret?: Secret;
148
+ /**
149
+ * The sender: an address saved in Sendcloud, or the full address. `country` is required in both cases.
150
+ * A value, or a function read on every call (change the address without creating a new carrier).
151
+ */
152
+ sender: Sender | null | (() => Sender | null | undefined | Promise<Sender | null | undefined>);
153
+ fetch?: typeof fetch;
154
+ baseUrl?: string;
155
+ /** Default 20 000. */
156
+ timeoutMs?: number;
157
+ /** Options of @astratra/resilience retry (reads only). */
158
+ retry?: { attempts?: number; baseDelayMs?: number; maxDelayMs?: number; sleep?: (ms: number) => Promise<void> };
159
+ /** Options of @astratra/resilience createCircuitBreaker. */
160
+ breaker?: { failureThreshold?: number; recoveryMs?: number; now?: () => number };
161
+ /** Labels on 'sendcloud:letter' (unstamped letter): nothing is posted. A value, or a function read on every call. */
162
+ testMode?: boolean | (() => boolean | Promise<boolean>);
163
+ /** Default 120; false disables the service point cache. */
164
+ servicePointsCacheSeconds?: number | false;
165
+ }
166
+
167
+ export class SendcloudCarrier extends Carrier {
168
+ constructor(options: SendcloudOptions);
169
+ /** The test mode as given: a boolean, or null when it is a function (read it with status()). */
170
+ readonly testMode: boolean | null;
171
+ status(): Promise<{ configured: boolean; missing: string[]; testMode: boolean }>;
172
+ verifySignature(rawBody: Buffer, signature: string | undefined): Promise<boolean>;
173
+ }
174
+
175
+ export function createSendcloudCarrier(options: SendcloudOptions): SendcloudCarrier;
176
+
177
+ /** 'picked_up' | 'delivered' | 'incident' | null for a Sendcloud status label. */
178
+ export function classifySendcloudStatus(message: unknown): ParcelStage | null;
179
+
180
+ /* ─────────────────── Tracking webhook ─────────────────── */
181
+
182
+ export const SIGNATURE_HEADER: 'sendcloud-signature';
183
+
184
+ type ParcelHandler = (
185
+ event: ParcelEvent,
186
+ tools: { sideEffect<T>(label: string, fn: () => Promise<T> | T): Promise<T | null>; handled(reason?: string): Outcome; unrelated(reason?: string): Outcome; duplicate(reason?: string): Outcome }
187
+ ) => Promise<Outcome | void> | Outcome | void;
188
+
189
+ /** The carrier's tracking webhook on @astratra/payments: mount it before any JSON body parser. */
190
+ export function createCarrierWebhook(options: {
191
+ carrier: Pick<Carrier, 'verifySignature' | 'readEvent'>;
192
+ /** Replay protection, for example createPostgresEventLog from @astratra/payments. */
193
+ eventLog?: EventLog;
194
+ onEvent?: ParcelHandler;
195
+ onPickedUp?: ParcelHandler;
196
+ onDelivered?: ParcelHandler;
197
+ onIncident?: ParcelHandler;
198
+ signatureHeader?: string;
199
+ logger?: WebhookLogger;
200
+ /** With an event log that has prune(): handled events older than this are deleted, at most once per pruneEveryMs. Default 90 days; false disables it. */
201
+ pruneOlderThanMs?: number | false;
202
+ /** Default 24 h. */
203
+ pruneEveryMs?: number;
204
+ now?: () => number;
205
+ }): WebhookHandler & {
206
+ /** Waits for a prune in progress (tests, graceful shutdown). */
207
+ settled(): Promise<void>;
208
+ };
package/src/index.js ADDED
@@ -0,0 +1,7 @@
1
+ module.exports = {
2
+ ...require('./carrier'),
3
+ ...require('./errors'),
4
+ ...require('./statuses'),
5
+ ...require('./sendcloud'),
6
+ ...require('./webhook')
7
+ };
@@ -0,0 +1,417 @@
1
+ /**
2
+ * Sendcloud (carrier aggregator), REST API v3: shipping options, shipments,
3
+ * parcel documents, service points, tracking webhooks.
4
+ *
5
+ * - Keys come from options (a value, or a function read on every call so they
6
+ * can be rotated or arrive after start-up). Never read from a file or the
7
+ * environment here, never put in an error.
8
+ * - Calls go through a circuit breaker; only READS are retried: announcing a
9
+ * shipment twice would buy two labels. With a `reference`, Sendcloud itself
10
+ * refuses a second shipment (409) and returns the first one.
11
+ * - A 4xx is Sendcloud refusing the request, not an outage: only network
12
+ * failures and 5xx count against the breaker and deserve a retry.
13
+ * - Test mode ships with the option code "sendcloud:letter" (unstamped letter):
14
+ * nothing is posted.
15
+ *
16
+ * References: https://sendcloud.dev (API v3: shipping-options, shipments/announce,
17
+ * shipments/{id}/cancel, parcels/{id}/documents/label, service-points).
18
+ */
19
+ const { createHmac, timingSafeEqual } = require('node:crypto');
20
+ const { URLSearchParams } = require('node:url');
21
+ const { createCircuitBreaker, retry, createCache } = require('@astratra/resilience');
22
+ const { Carrier } = require('./carrier');
23
+ const { CODES, ShippingError } = require('./errors');
24
+ const { classifySendcloudStatus } = require('./statuses');
25
+
26
+ const SENDCLOUD_API_URL = 'https://panel.sendcloud.sc/api/v3';
27
+ const TEST_SHIPPING_OPTION = 'sendcloud:letter';
28
+ const DEFAULT_TIMEOUT_MS = 20_000;
29
+ const SERVICE_POINT_DELIVERY = new Set(['service_point', 'locker', 'locker_or_service_point']);
30
+
31
+ const read = async (value) => String((typeof value === 'function' ? await value() : value) ?? '').trim();
32
+ const isOutage = (error) => !error || error.providerStatus === undefined || error.providerStatus >= 500;
33
+ const kilograms = (grams) => (grams / 1000).toFixed(3);
34
+ const country = (value) => String(value ?? '').trim().toUpperCase();
35
+ const cents = (value) => {
36
+ const n = Number.parseFloat(value);
37
+ return Number.isFinite(n) ? Math.round(n * 100) : null;
38
+ };
39
+
40
+ /**
41
+ * An event time in MILLISECONDS since 1970, whatever unit arrived (seconds or milliseconds, number or
42
+ * numeric string, ISO date): below 10^12 a number is read as seconds (10^12 ms is 2001; 10^12 s is
43
+ * year 33 658). null when unreadable.
44
+ */
45
+ function toMilliseconds(value) {
46
+ if (value === null || value === undefined || value === '') return null;
47
+ const n = Number(value);
48
+ if (Number.isFinite(n)) return n > 0 ? Math.round(n < 1e12 ? n * 1000 : n) : null;
49
+ if (typeof value !== 'string') return null;
50
+ const parsed = Date.parse(value);
51
+ return Number.isFinite(parsed) ? parsed : null;
52
+ }
53
+
54
+ /** Any failure turned into a ShippingError; `whenRefused` says what a 4xx means for this call. */
55
+ function toShippingError(error, whenRefused) {
56
+ if (error instanceof ShippingError && error.code !== CODES.REJECTED) return error;
57
+ const status = error && error.providerStatus;
58
+ if (status === 401 || status === 403) return new ShippingError(CODES.CREDENTIALS_REFUSED, { providerStatus: status });
59
+ if (status !== undefined && status < 500) return new ShippingError(whenRefused, { providerStatus: status });
60
+ return new ShippingError(CODES.UNAVAILABLE, status === undefined ? {} : { providerStatus: status });
61
+ }
62
+
63
+ /** The sender, as Sendcloud's from_address: a saved sender address id, or the full address. */
64
+ function fromAddress(sender) {
65
+ if (!sender) return null;
66
+ if (sender.addressId !== undefined && sender.addressId !== null) return { sender_address_id: Number(sender.addressId) };
67
+ if (!sender.name || !sender.line1 || !sender.city || !sender.postalCode || !/^[A-Z]{2}$/.test(country(sender.country))) return null;
68
+ return {
69
+ name: sender.name,
70
+ company_name: sender.companyName || undefined,
71
+ address_line_1: sender.line1,
72
+ address_line_2: sender.line2 || undefined,
73
+ house_number: sender.houseNumber || undefined,
74
+ postal_code: sender.postalCode,
75
+ city: sender.city,
76
+ country_code: country(sender.country),
77
+ phone_number: sender.phone || undefined,
78
+ email: sender.email || undefined
79
+ };
80
+ }
81
+
82
+ class SendcloudCarrier extends Carrier {
83
+ /**
84
+ * @param {object} options
85
+ * @param {string|Function} options.publicKey
86
+ * @param {string|Function} options.secretKey
87
+ * @param {string|Function} [options.webhookSecret] the "Webhook Signature Key" when the integration has one; else the secret key
88
+ * @param {object|Function} options.sender { addressId, country } (a sender address saved in Sendcloud) or { name, line1, city, postalCode, country, … };
89
+ * a value, or a function read on every call (the shop changes its address without a restart)
90
+ * @param {Function} [options.fetch] injectable (tests)
91
+ * @param {string} [options.baseUrl]
92
+ * @param {number} [options.timeoutMs] default 20 000
93
+ * @param {object} [options.retry] options of @astratra/resilience retry (tests: { baseDelayMs: 0 })
94
+ * @param {object} [options.breaker] options of createCircuitBreaker
95
+ * @param {boolean|Function} [options.testMode] labels on "sendcloud:letter": nothing is posted (a value, or a function read on every call)
96
+ * @param {number|false} [options.servicePointsCacheSeconds] default 120; false disables the cache
97
+ */
98
+ constructor(options = {}) {
99
+ super();
100
+ this.publicKey = options.publicKey;
101
+ this.secretKey = options.secretKey;
102
+ this.webhookSecret = options.webhookSecret;
103
+ this.senderOption = options.sender;
104
+ this.fetchImpl = options.fetch || globalThis.fetch;
105
+ this.baseUrl = options.baseUrl || SENDCLOUD_API_URL;
106
+ this.timeoutMs = options.timeoutMs || DEFAULT_TIMEOUT_MS;
107
+ this.retryOptions = options.retry || {};
108
+ this.testModeOption = options.testMode;
109
+ this.breaker = createCircuitBreaker({
110
+ name: 'sendcloud', failureThreshold: 5, recoveryMs: 30_000, ...options.breaker, isFailure: isOutage
111
+ });
112
+ const seconds = options.servicePointsCacheSeconds === undefined ? 120 : options.servicePointsCacheSeconds;
113
+ this.cache = seconds ? createCache({ ttlSeconds: seconds, prefix: 'sendcloud:service-points:', maxEntries: 1000 }) : null;
114
+ }
115
+
116
+ get name() { return 'sendcloud'; }
117
+
118
+ /** The test mode as given: a boolean, or null when it is a function (read it with status()). */
119
+ get testMode() { return typeof this.testModeOption === 'function' ? null : Boolean(this.testModeOption); }
120
+
121
+ async #isTestMode() {
122
+ return Boolean(typeof this.testModeOption === 'function' ? await this.testModeOption() : this.testModeOption);
123
+ }
124
+
125
+ /** The sender, read on every call: { from: Sendcloud's from_address or null, country }. */
126
+ async #sender() {
127
+ const sender = typeof this.senderOption === 'function' ? await this.senderOption() : this.senderOption;
128
+ /* Shipping options need the departure country, also with a saved sender address. */
129
+ return { from: fromAddress(sender), country: country(sender && sender.country) };
130
+ }
131
+
132
+ /** { configured, missing, testMode } — names of what is missing, never a value. */
133
+ async status() {
134
+ const missing = [];
135
+ if (!(await read(this.publicKey))) missing.push('publicKey');
136
+ if (!(await read(this.secretKey))) missing.push('secretKey');
137
+ const sender = await this.#sender();
138
+ if (!sender.from || !/^[A-Z]{2}$/.test(sender.country)) missing.push('sender');
139
+ return { configured: missing.length === 0, missing, testMode: await this.#isTestMode() };
140
+ }
141
+
142
+ async #keys() {
143
+ const publicKey = await read(this.publicKey);
144
+ const secretKey = await read(this.secretKey);
145
+ if (!publicKey || !secretKey) throw new ShippingError(CODES.NOT_CONFIGURED);
146
+ return { publicKey, secretKey };
147
+ }
148
+
149
+ /**
150
+ * One HTTP call; retried only when `retryable` (reads). Returns the response when ok, or when its
151
+ * status is listed in `accept` (for example 409 on a shipment announced again with its reference).
152
+ */
153
+ async #call(path, { method = 'GET', body, retryable = false, accept = [], headers: extra = {} } = {}) {
154
+ const { publicKey, secretKey } = await this.#keys();
155
+ const headers = {
156
+ Authorization: `Basic ${Buffer.from(`${publicKey}:${secretKey}`).toString('base64')}`,
157
+ Accept: 'application/json',
158
+ ...extra
159
+ };
160
+ if (body !== undefined) headers['Content-Type'] = 'application/json';
161
+ const once = async () => {
162
+ let response;
163
+ try {
164
+ response = await this.fetchImpl(`${this.baseUrl}${path}`, {
165
+ method, headers, body: body === undefined ? undefined : JSON.stringify(body), signal: globalThis.AbortSignal.timeout(this.timeoutMs)
166
+ });
167
+ } catch {
168
+ /* Network failure or timeout: no HTTP status, an outage. */
169
+ throw new ShippingError(CODES.UNAVAILABLE);
170
+ }
171
+ if (!response.ok && !accept.includes(response.status)) {
172
+ throw new ShippingError(CODES.REJECTED, { providerStatus: response.status });
173
+ }
174
+ return response;
175
+ };
176
+ try {
177
+ return await this.breaker.call(() => (retryable
178
+ ? retry(once, { attempts: 3, ...this.retryOptions, shouldRetry: (error) => isOutage(error) })
179
+ : once()));
180
+ } catch (error) {
181
+ if (error && error.code === 'CIRCUIT_OPEN') throw new ShippingError(CODES.UNAVAILABLE);
182
+ throw error;
183
+ }
184
+ }
185
+
186
+ /**
187
+ * Shipping options for a destination and a weight (POST /shipping-options, with quotes). With
188
+ * `servicePointId`, only service point or locker delivery; without, only the other deliveries.
189
+ * `id` is the shipping option code; `priceCents` is Sendcloud's quote, never recomputed here.
190
+ */
191
+ async shippingMethods({ country: to, postalCode, weightGrams, servicePointId = null } = {}) {
192
+ const destination = country(to);
193
+ if (!/^[A-Z]{2}$/.test(destination) || !(Number.isFinite(weightGrams) && weightGrams > 0)) {
194
+ throw new ShippingError(CODES.INVALID_INPUT);
195
+ }
196
+ const sender = await this.#sender();
197
+ if (!/^[A-Z]{2}$/.test(sender.country)) throw new ShippingError(CODES.NOT_CONFIGURED);
198
+ const body = {
199
+ from_address: { country_code: sender.country },
200
+ to_address: { country_code: destination, ...(postalCode ? { postal_code: String(postalCode) } : {}) },
201
+ parcels: [{ weight: { value: kilograms(weightGrams), unit: 'kg' } }],
202
+ calculate_quotes: true,
203
+ ...(servicePointId ? { to_service_point: { id: String(servicePointId) } } : {})
204
+ };
205
+ let response;
206
+ try {
207
+ response = await this.#call('/shipping-options', { method: 'POST', body, retryable: true });
208
+ } catch (error) {
209
+ throw toShippingError(error, CODES.NO_METHOD);
210
+ }
211
+ const data = (await response.json().catch(() => ({}))).data;
212
+ return (Array.isArray(data) ? data : [])
213
+ .filter((option) => {
214
+ const toPoint = SERVICE_POINT_DELIVERY.has(option.functionalities?.last_mile);
215
+ return servicePointId ? toPoint : !toPoint;
216
+ })
217
+ .map((option) => ({
218
+ id: String(option.code),
219
+ name: String(option.name ?? ''),
220
+ carrier: String(option.carrier?.code ?? ''),
221
+ servicePointRequired: SERVICE_POINT_DELIVERY.has(option.functionalities?.last_mile),
222
+ priceCents: cents(option.quotes?.[0]?.price?.total?.value)
223
+ }));
224
+ }
225
+
226
+ /**
227
+ * Announces the shipment and gets its label in the same answer (POST /shipments/announce).
228
+ * NEVER retried. `reference` (optional, unique per account) makes a second announcement of the same
229
+ * shipment return the first one instead of buying a second label.
230
+ * recipient: { name, line1, line2?, houseNumber?, city, postalCode, country, phone?, email? }
231
+ * method: { id } — a shipping option code from shippingMethods
232
+ */
233
+ async createLabel({ orderNumber, reference, recipient = {}, weightGrams, method, servicePointId = null } = {}) {
234
+ const destination = country(recipient.country);
235
+ const code = method && (method.code ?? method.id);
236
+ const testMode = await this.#isTestMode();
237
+ if (!recipient.name || !recipient.line1 || !recipient.city || !recipient.postalCode || !/^[A-Z]{2}$/.test(destination)
238
+ || !(Number.isFinite(weightGrams) && weightGrams > 0) || (!code && !testMode) || !orderNumber) {
239
+ throw new ShippingError(CODES.INVALID_INPUT);
240
+ }
241
+ const sender = await this.#sender();
242
+ if (!sender.from) throw new ShippingError(CODES.NOT_CONFIGURED);
243
+ const optionCode = testMode ? TEST_SHIPPING_OPTION : String(code);
244
+ const body = {
245
+ from_address: sender.from,
246
+ to_address: {
247
+ name: recipient.name,
248
+ address_line_1: recipient.line1,
249
+ address_line_2: recipient.line2 || undefined,
250
+ house_number: recipient.houseNumber || undefined,
251
+ postal_code: recipient.postalCode,
252
+ city: recipient.city,
253
+ country_code: destination,
254
+ phone_number: recipient.phone || undefined,
255
+ email: recipient.email || undefined
256
+ },
257
+ ship_with: { type: 'shipping_option_code', properties: { shipping_option_code: optionCode } },
258
+ parcels: [{ weight: { value: kilograms(weightGrams), unit: 'kg' } }],
259
+ order_number: String(orderNumber),
260
+ ...(reference ? { external_reference_id: String(reference) } : {}),
261
+ ...(servicePointId && !testMode ? { to_service_point: { id: String(servicePointId) } } : {})
262
+ };
263
+ let response;
264
+ try {
265
+ response = await this.#call('/shipments/announce', { method: 'POST', body, accept: reference ? [409] : [] });
266
+ } catch (error) {
267
+ throw toShippingError(error, CODES.REJECTED);
268
+ }
269
+ const shipment = (await response.json().catch(() => ({}))).data;
270
+ const parcel = shipment && Array.isArray(shipment.parcels) ? shipment.parcels[0] : null;
271
+ /* A carrier refusal arrives as 201 with errors and an ANNOUNCEMENT_FAILED parcel. */
272
+ if (shipment && Array.isArray(shipment.errors) && shipment.errors.length) throw new ShippingError(CODES.REJECTED, { providerStatus: response.status });
273
+ if (parcel && String(parcel.status?.code ?? '').toUpperCase() === 'ANNOUNCEMENT_FAILED') throw new ShippingError(CODES.REJECTED, { providerStatus: response.status });
274
+ if (!shipment || !shipment.id || !parcel || !parcel.id) throw new ShippingError(CODES.UNEXPECTED_RESPONSE);
275
+ return {
276
+ shipmentId: String(shipment.id),
277
+ parcelId: Number(parcel.id),
278
+ trackingNumber: String(parcel.tracking_number ?? ''),
279
+ trackingUrl: String(parcel.tracking_url ?? ''),
280
+ carrier: String(shipment.carrier?.code ?? ''),
281
+ service: String(shipment.ship_with?.properties?.shipping_option_code ?? optionCode),
282
+ /* The label itself, when Sendcloud returns it inline (one parcel): no second request needed. */
283
+ label: typeof parcel.label_file === 'string' && parcel.label_file ? Buffer.from(parcel.label_file, 'base64') : null,
284
+ alreadyExisted: response.status === 409,
285
+ testMode
286
+ };
287
+ }
288
+
289
+ /** The label PDF (GET /parcels/{id}/documents/label), paper A4 or A6. */
290
+ async downloadLabel({ parcelId, format = 'a6' } = {}) {
291
+ const id = Number(parcelId);
292
+ if (!Number.isSafeInteger(id) || id <= 0 || !['a4', 'a5', 'a6'].includes(format)) throw new ShippingError(CODES.INVALID_INPUT);
293
+ let response;
294
+ try {
295
+ response = await this.#call(`/parcels/${id}/documents/label?paper_size=${format.toUpperCase()}`, {
296
+ retryable: true, headers: { Accept: 'application/pdf' }
297
+ });
298
+ } catch (error) {
299
+ throw toShippingError(error, CODES.NOT_FOUND);
300
+ }
301
+ const type = response.headers.get('content-type') || '';
302
+ const content = Buffer.from(await response.arrayBuffer());
303
+ if (!type.includes('pdf') || content.length === 0) throw new ShippingError(CODES.UNEXPECTED_RESPONSE);
304
+ return { content, type: 'application/pdf' };
305
+ }
306
+
307
+ /**
308
+ * Cancels a shipment (POST /shipments/{id}/cancel). 202 "queued": Sendcloud watches it and cancels
309
+ * it if nothing moves ({ status: 'requested' }). A 409 is refused (delivered, older than 42 days),
310
+ * except "already being cancelled", which is the wanted state.
311
+ */
312
+ async cancelLabel({ shipmentId } = {}) {
313
+ const id = String(shipmentId ?? '').trim();
314
+ if (!id || !/^[A-Za-z0-9_-]{1,64}$/.test(id)) throw new ShippingError(CODES.INVALID_INPUT);
315
+ let response;
316
+ try {
317
+ response = await this.#call(`/shipments/${encodeURIComponent(id)}/cancel`, { method: 'POST', accept: [409] });
318
+ } catch (error) {
319
+ throw toShippingError(error, error && error.providerStatus === 404 ? CODES.NOT_FOUND : CODES.CANCEL_REFUSED);
320
+ }
321
+ const body = await response.json().catch(() => ({}));
322
+ if (response.status === 409) {
323
+ const detail = Array.isArray(body.errors) ? body.errors.map((e) => String(e.detail ?? '')).join(' ') : '';
324
+ if (/already/i.test(detail)) return { status: 'cancelled' };
325
+ throw new ShippingError(CODES.CANCEL_REFUSED, { providerStatus: 409 });
326
+ }
327
+ return { status: response.status === 202 || body.data?.status === 'queued' ? 'requested' : 'cancelled' };
328
+ }
329
+
330
+ /**
331
+ * Service points near an address or coordinates, nearest first (GET /service-points).
332
+ * carriers: Sendcloud carrier codes (for example ['mondial_relay', 'colissimo']); without, the
333
+ * carriers enabled on the integration.
334
+ */
335
+ async servicePoints({ country: of, postalCode, city, latitude, longitude, carriers, radiusMeters = 10_000, limit = 15 } = {}) {
336
+ const pays = country(of);
337
+ const byCoordinates = latitude !== undefined || longitude !== undefined;
338
+ if (!/^[A-Z]{2}$/.test(pays)
339
+ || (byCoordinates && !(Number.isFinite(latitude) && Number.isFinite(longitude) && Math.abs(latitude) <= 90 && Math.abs(longitude) <= 180))
340
+ || (!byCoordinates && !postalCode && !city)) {
341
+ throw new ShippingError(CODES.INVALID_INPUT);
342
+ }
343
+ const wanted = Array.isArray(carriers) && carriers.length ? carriers.map((c) => String(c).toLowerCase()) : null;
344
+ const params = new URLSearchParams({ country_code: pays });
345
+ if (wanted) for (const code of wanted) params.append('carrier_code', code);
346
+ else params.set('use_integration_carriers', 'true');
347
+ if (byCoordinates) {
348
+ params.set('latitude', String(latitude));
349
+ params.set('longitude', String(longitude));
350
+ } else {
351
+ if (postalCode) params.set('address_postal_code', String(postalCode));
352
+ if (city) params.set('address_city', String(city));
353
+ }
354
+ params.set('radius', String(Math.min(50_000, Math.max(100, Math.round(radiusMeters)))));
355
+ params.set('limit', String(Math.min(200, Math.max(1, limit))));
356
+ const fetchPoints = async () => {
357
+ let response;
358
+ try {
359
+ response = await this.#call(`/service-points?${params}`, { retryable: true });
360
+ } catch (error) {
361
+ throw toShippingError(error, CODES.SERVICE_POINTS_UNAVAILABLE);
362
+ }
363
+ const body = await response.json().catch(() => ({}));
364
+ return Array.isArray(body.data?.results) ? body.data.results : [];
365
+ };
366
+ const raw = this.cache ? await this.cache.remember(params.toString(), fetchPoints) : await fetchPoints();
367
+ return raw
368
+ .map((p) => ({
369
+ id: Number(p.id),
370
+ carrier: String(p.carrier?.code ?? '').toLowerCase(),
371
+ name: String(p.name ?? ''),
372
+ address: [p.address?.street, p.address?.house_number].filter(Boolean).join(' '),
373
+ postalCode: String(p.address?.postal_code ?? ''),
374
+ city: String(p.address?.city ?? ''),
375
+ country: country(p.address?.country_code),
376
+ openingTimes: p.opening_times ?? {},
377
+ distanceMeters: Number.isFinite(Number(p.distance)) && p.distance !== null ? Number(p.distance) : null
378
+ }))
379
+ .filter((p) => p.country === pays && (!wanted || wanted.includes(p.carrier))
380
+ && Number.isSafeInteger(p.id) && p.id > 0 && p.name && p.address && p.postalCode && p.city)
381
+ .sort((a, b) => (a.distanceMeters ?? Infinity) - (b.distanceMeters ?? Infinity))
382
+ .slice(0, Math.max(1, limit));
383
+ }
384
+
385
+ /** HMAC-SHA256 of the raw body (Sendcloud-Signature header, hex), compared in constant time. */
386
+ async verifySignature(rawBody, signature) {
387
+ const secret = (await read(this.webhookSecret)) || (await read(this.secretKey));
388
+ if (!secret || typeof signature !== 'string' || !Buffer.isBuffer(rawBody)) return false;
389
+ const expected = createHmac('sha256', secret).update(rawBody).digest();
390
+ const received = Buffer.from(signature.trim().toLowerCase(), 'hex');
391
+ return received.length === expected.length && timingSafeEqual(received, expected);
392
+ }
393
+
394
+ /**
395
+ * parcel_status_changed only; anything else is null (acknowledged, nothing to do). Webhooks can
396
+ * arrive out of order: `timestamp` (always milliseconds) says which status is the latest.
397
+ */
398
+ readEvent(json) {
399
+ if (!json || json.action !== 'parcel_status_changed' || !json.parcel || !json.parcel.id) return null;
400
+ const message = String(json.parcel.status?.message ?? '');
401
+ const timestamp = toMilliseconds(json.timestamp);
402
+ return {
403
+ parcelId: Number(json.parcel.id),
404
+ trackingNumber: String(json.parcel.tracking_number ?? ''),
405
+ trackingUrl: String(json.parcel.tracking_url ?? ''),
406
+ message,
407
+ stage: classifySendcloudStatus(message),
408
+ timestamp
409
+ };
410
+ }
411
+ }
412
+
413
+ function createSendcloudCarrier(options) {
414
+ return new SendcloudCarrier(options);
415
+ }
416
+
417
+ module.exports = { SendcloudCarrier, createSendcloudCarrier, SENDCLOUD_API_URL, TEST_SHIPPING_OPTION, toMilliseconds };
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Sendcloud tracking statuses ("Tracking statuses" list; the webhooks are the same in API v2 and v3) mapped to the
3
+ * three moments a shop acts on. Pure function.
4
+ *
5
+ * - picked_up: first scan by the carrier ("label created" is NOT a scan:
6
+ * "Ready to send", "Announced", "Being announced" map to null);
7
+ * - delivered: delivered or collected by the customer;
8
+ * - incident: the parcel will not be delivered normally;
9
+ * - null: no action. A failed delivery attempt or a delay is not a final
10
+ * incident: it still counts as "on its way".
11
+ */
12
+ const PICKED_UP = new Set([
13
+ 'shipment picked up by driver',
14
+ 'en route to sorting center',
15
+ 'at sorting centre',
16
+ 'being sorted',
17
+ 'sorted',
18
+ 'parcel en route',
19
+ 'driver en route',
20
+ 'awaiting customer pickup',
21
+ 'at customs',
22
+ 'delivery delayed',
23
+ 'delivery attempt failed',
24
+ 'delivery date changed',
25
+ 'delivery method changed',
26
+ 'delivery address changed'
27
+ ]);
28
+ const DELIVERED = new Set(['delivered', 'shipment collected by customer']);
29
+ const INCIDENT = new Set(['unable to deliver', 'refused by recipient', 'returned to sender', 'address invalid', 'error collecting']);
30
+
31
+ const normalize = (message) => String(message ?? '').trim().toLowerCase().replace(/\s+/g, ' ');
32
+
33
+ /** 'picked_up' | 'delivered' | 'incident' | null for a Sendcloud status label. */
34
+ function classifySendcloudStatus(message) {
35
+ const m = normalize(message);
36
+ if (DELIVERED.has(m)) return 'delivered';
37
+ if (INCIDENT.has(m)) return 'incident';
38
+ if (PICKED_UP.has(m)) return 'picked_up';
39
+ return null;
40
+ }
41
+
42
+ module.exports = { classifySendcloudStatus };