universal-parcel-scraper 0.158.0-main.1233 → 0.159.0-main.1237

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +2 -2
  2. package/data/catalog.json +34 -6
  3. package/data/coverage-summary.json +1 -1
  4. package/data/detection-golden.json +132 -0
  5. package/dist/browser/scraper.js +27 -7
  6. package/dist/carriers/gati/adapter.d.ts +20 -0
  7. package/dist/carriers/gati/adapter.js +105 -0
  8. package/dist/carriers/gati/carrier.json +49 -7
  9. package/dist/carriers/gati/numbers.json +67 -7
  10. package/dist/carriers/gati/parser.d.ts +13 -0
  11. package/dist/carriers/gati/parser.js +173 -0
  12. package/dist/carriers/gati/status.d.ts +7 -0
  13. package/dist/carriers/gati/status.js +37 -0
  14. package/dist/carriers/gati/statuses.json +12 -1
  15. package/dist/carriers/shadowfax/adapter.d.ts +19 -0
  16. package/dist/carriers/shadowfax/adapter.js +93 -0
  17. package/dist/carriers/shadowfax/carrier.json +55 -7
  18. package/dist/carriers/shadowfax/numbers.json +144 -8
  19. package/dist/carriers/shadowfax/parser.d.ts +28 -0
  20. package/dist/carriers/shadowfax/parser.js +206 -0
  21. package/dist/carriers/shadowfax/status.d.ts +12 -0
  22. package/dist/carriers/shadowfax/status.js +77 -0
  23. package/dist/carriers/shadowfax/statuses.json +16 -1
  24. package/dist/carriers/total-express/adapter.d.ts +15 -0
  25. package/dist/carriers/total-express/adapter.js +85 -0
  26. package/dist/carriers/total-express/carrier.json +81 -10
  27. package/dist/carriers/total-express/numbers.json +115 -1
  28. package/dist/carriers/total-express/parser.d.ts +24 -0
  29. package/dist/carriers/total-express/parser.js +195 -0
  30. package/dist/carriers/total-express/status.d.ts +7 -0
  31. package/dist/carriers/total-express/status.js +138 -0
  32. package/dist/carriers/total-express/statuses.json +101 -7
  33. package/dist/core/catalog/statusMaps.js +7 -3
  34. package/dist/data/catalog.json +34 -6
  35. package/dist/generated/catalog.d.ts +23 -6
  36. package/dist/generated/catalog.js +35 -7
  37. package/dist/generated/recognition.js +3 -0
  38. package/dist/generated/registry.js +9 -3
  39. package/dist/server/openapi.json +1 -1
  40. package/package.json +1 -1
@@ -0,0 +1,13 @@
1
+ import type { CarrierResult } from '../../core/result/index.js';
2
+ export declare const PROVIDER = "AllcargoGATI";
3
+ export declare const GATI_MAX_BYTES: number;
4
+ /** A docket number: nine digits. Anything else is not a number Gati issues. */
5
+ export declare function normalizeGatiNumber(raw: string): string;
6
+ /**
7
+ * The reply of `admin.allcargologistics.com/api/track-shipment` for one
8
+ * docket: `details` holds one entry per docket asked, which names it. The
9
+ * tracking service answers a docket it does not know with `Check Docket No`.
10
+ * The consignor, consignee, receiver, remarks, references and proof of
11
+ * delivery link are not read.
12
+ */
13
+ export declare function parseGati(payload: unknown, raw: string): CarrierResult;
@@ -0,0 +1,173 @@
1
+ import { DateTime } from 'luxon';
2
+ import { normalizeTrackingNumber } from '../../core/detection/index.js';
3
+ import { IndeterminateError, InvalidInputError, NoHistoryError, NotFoundError, SchemaError } from '../../core/errors/index.js';
4
+ import { languageStageStatus } from '../../core/status/index.js';
5
+ import { firstOccurrence } from '../../core/time/index.js';
6
+ import { clean, cleanScalar } from '../../core/transport/index.js';
7
+ import { isRecord } from '../../core/types.js';
8
+ import { gatiStage } from './status.js';
9
+ export const PROVIDER = 'AllcargoGATI';
10
+ // A long history is under ten kilobytes.
11
+ export const GATI_MAX_BYTES = 512 * 1024;
12
+ const ZONE = 'Asia/Kolkata';
13
+ const SCAN_CLOCK = 'dd-LLL-yyyy HH:mm';
14
+ const DELIVERY_CLOCK = 'dd-LLL-yyyy HH:mm:ss';
15
+ const DAY = 'dd-LLL-yyyy';
16
+ const NUMBER = /^\d{9}$/;
17
+ // The tracking service's answer for a docket it does not know.
18
+ const MISSING = 'check docket no';
19
+ // The weight the reply gives, as "12 (Kgs)".
20
+ const WEIGHT = /^(\d{1,6}(?:\.\d{1,3})?)\s*\(\s*kgs?\s*\)$/i;
21
+ const MAX_ROWS = 500;
22
+ const MAX_EVENTS = 100;
23
+ /** A docket number: nine digits. Anything else is not a number Gati issues. */
24
+ export function normalizeGatiNumber(raw) {
25
+ const number = raw.length <= 64 ? normalizeTrackingNumber(raw) : '';
26
+ if (!NUMBER.test(number))
27
+ throw new InvalidInputError(PROVIDER, 'Gati docket numbers are nine digits');
28
+ return number;
29
+ }
30
+ /** An optional text field; anything but a string is a changed reply. */
31
+ function text(row, key, maxLength = 300) {
32
+ const value = row[key];
33
+ if (value === null || value === undefined)
34
+ return '';
35
+ if (typeof value !== 'string')
36
+ throw new SchemaError(PROVIDER, `AllcargoGATI returned an invalid ${key}`);
37
+ return clean(value, maxLength);
38
+ }
39
+ /** A docket number the reply names, whole: a string, or a nonnegative integer. */
40
+ function docket(value) {
41
+ if (typeof value === 'number')
42
+ return Number.isSafeInteger(value) && value >= 0 ? String(value) : '';
43
+ return typeof value === 'string' && value.length <= 64 ? normalizeTrackingNumber(value) : '';
44
+ }
45
+ /** A wall clock in the reply's format, read back unchanged, or null. */
46
+ function wallClock(value, format) {
47
+ if (!value)
48
+ return null;
49
+ const wall = firstOccurrence(DateTime.fromFormat(value, format, { zone: ZONE, locale: 'en-US' }));
50
+ // Luxon rolls 24:00 over to the next day; only a clock that reads back unchanged is kept.
51
+ return wall.isValid && wall.toFormat(format).toUpperCase() === value.toUpperCase() ? wall : null;
52
+ }
53
+ function instant(time) {
54
+ return time.toUTC().toISO({ suppressMilliseconds: true });
55
+ }
56
+ function projectRow(row) {
57
+ const description = text(row, 'intransitStatus');
58
+ if (!description)
59
+ throw new SchemaError(PROVIDER, 'AllcargoGATI returned a scan without wording');
60
+ // Every scan is at a branch or hub of Gati's network in India, which keeps UTC+5:30 all year.
61
+ const wall = wallClock(`${text(row, 'intransitDate', 16)} ${text(row, 'intransitTime', 16)}`, SCAN_CLOCK);
62
+ if (!wall)
63
+ throw new SchemaError(PROVIDER, 'AllcargoGATI returned an invalid scan time');
64
+ const time = instant(wall);
65
+ const location = text(row, 'intransitLocation', 120);
66
+ const code = cleanScalar(row.milestonecode, 16).toUpperCase();
67
+ const staged = gatiStage(code, description);
68
+ const event = {
69
+ time,
70
+ ...(location ? { location } : {}),
71
+ description,
72
+ ...(code ? { provider_code: code } : {}),
73
+ ...(staged ? { stage: staged.stage, stage_source: staged.source } : {}),
74
+ };
75
+ return { key: JSON.stringify([time, code, description, location]), event };
76
+ }
77
+ /** A calendar day the reply gives as "21-JUL-2021", as an ISO date, or null. */
78
+ function day(value) {
79
+ return wallClock(value, DAY)?.toISODate() ?? null;
80
+ }
81
+ /** The weight booked for the docket, in kilograms. */
82
+ function weight(value) {
83
+ const kilograms = Number(WEIGHT.exec(value)?.[1]);
84
+ return Number.isFinite(kilograms) && kilograms > 0 ? kilograms : null;
85
+ }
86
+ /**
87
+ * The reply of `admin.allcargologistics.com/api/track-shipment` for one
88
+ * docket: `details` holds one entry per docket asked, which names it. The
89
+ * tracking service answers a docket it does not know with `Check Docket No`.
90
+ * The consignor, consignee, receiver, remarks, references and proof of
91
+ * delivery link are not read.
92
+ */
93
+ export function parseGati(payload, raw) {
94
+ const number = normalizeGatiNumber(raw);
95
+ if (!isRecord(payload))
96
+ throw new SchemaError(PROVIDER, 'AllcargoGATI returned an invalid envelope');
97
+ if (payload.success !== true) {
98
+ // The site checks the number before it asks the tracking service.
99
+ if (payload.success === false && isRecord(payload.errors))
100
+ throw new InvalidInputError(PROVIDER, 'AllcargoGATI refused the docket number');
101
+ // The site relays a failure of the tracking service behind it, such as its timeout.
102
+ if (payload.success === false && typeof payload.error === 'string')
103
+ throw new IndeterminateError(PROVIDER, 'AllcargoGATI tracking service did not answer');
104
+ throw new SchemaError(PROVIDER, 'AllcargoGATI returned an invalid envelope');
105
+ }
106
+ const data = payload.data;
107
+ if (!isRecord(data) || !Array.isArray(data.details))
108
+ throw new SchemaError(PROVIDER, 'AllcargoGATI returned a reply without dockets');
109
+ if (text(data, 'result', 40).toLowerCase() !== 'successful')
110
+ throw new IndeterminateError(PROVIDER, 'AllcargoGATI did not complete the lookup');
111
+ if (data.details.length !== 1 || !isRecord(data.details[0]))
112
+ throw new SchemaError(PROVIDER, 'AllcargoGATI returned an unexpected list of dockets');
113
+ const detail = data.details[0];
114
+ const asked = docket(detail.dktno);
115
+ if (!asked)
116
+ throw new SchemaError(PROVIDER, 'AllcargoGATI returned a docket without its number');
117
+ if (asked !== number)
118
+ throw new IndeterminateError(PROVIDER, 'AllcargoGATI answered for another docket');
119
+ const result = text(detail, 'result', 40).toLowerCase();
120
+ if (result === 'failed') {
121
+ if (text(detail, 'errmsg', 120).toLowerCase() === MISSING)
122
+ throw new NotFoundError(PROVIDER);
123
+ throw new IndeterminateError(PROVIDER, 'AllcargoGATI did not complete the lookup');
124
+ }
125
+ if (result !== 'successful')
126
+ throw new SchemaError(PROVIDER, 'AllcargoGATI returned a docket without a result');
127
+ if (docket(detail.docketNumber) !== number)
128
+ throw new IndeterminateError(PROVIDER, 'AllcargoGATI answered for another docket');
129
+ const rows = detail.TRANSIT_DTLS ?? [];
130
+ if (!Array.isArray(rows))
131
+ throw new SchemaError(PROVIDER, 'AllcargoGATI returned a docket with invalid scans');
132
+ if (rows.length > MAX_ROWS)
133
+ throw new SchemaError(PROVIDER, 'AllcargoGATI returned an oversized history');
134
+ const seen = new Set();
135
+ const events = [];
136
+ for (const row of rows) {
137
+ if (!isRecord(row))
138
+ throw new SchemaError(PROVIDER, 'AllcargoGATI returned an invalid scan');
139
+ const scan = projectRow(row);
140
+ if (seen.has(scan.key))
141
+ continue;
142
+ seen.add(scan.key);
143
+ events.push(scan.event);
144
+ }
145
+ if (!events.length)
146
+ throw new NoHistoryError(PROVIDER);
147
+ // Newest first, as the reply lists them; an oldest-first reply is turned round.
148
+ const newestFirst = events[0].time < events.at(-1).time ? events.reverse() : events;
149
+ const newest = newestFirst[0];
150
+ const scanned = newestFirst.find((event) => event.stage);
151
+ // The docket's own status, which the page shows over the scans.
152
+ const summary = text(detail, 'docketStatus', 80).toLowerCase() === 'delivered' ? 'delivered' : undefined;
153
+ const stage = summary ?? scanned?.stage;
154
+ const source = summary && summary !== scanned?.stage ? 'carrier_map' : scanned?.stage_source;
155
+ const delivered = stage === 'delivered'
156
+ ? wallClock(text(detail, 'DeliveryDt', 32), DELIVERY_CLOCK) ?? newestFirst.find((event) => event.stage === 'delivered')
157
+ : undefined;
158
+ // A revised date replaces the one promised at booking.
159
+ const expected = stage === 'delivered' ? null : day(text(detail, 'revisedAssuredDeliveryDate', 32)) ?? day(text(detail, 'assuredDlyDate', 32));
160
+ const kilograms = weight(text(detail, 'actualWeight', 40));
161
+ return {
162
+ status: stage ? languageStageStatus(stage) : 'unknown',
163
+ ...(stage ? { current_stage: stage, current_stage_source: source ?? 'carrier_map' } : {}),
164
+ last_status_text: newest.description,
165
+ last_update: newest.time,
166
+ expected_delivery: expected,
167
+ ...(delivered ? { delivered_at: delivered instanceof DateTime ? instant(delivered) : delivered.time } : {}),
168
+ ...(kilograms ? { weight_kg: kilograms } : {}),
169
+ timezone: ZONE,
170
+ events: newestFirst.slice(0, MAX_EVENTS),
171
+ ...(newestFirst.length > MAX_EVENTS ? { history_truncated: true } : {}),
172
+ };
173
+ }
@@ -0,0 +1,7 @@
1
+ import { type ClassifiedWording, type Stage } from '../../core/status/index.js';
2
+ import type { CarrierStatusMap } from '../../core/status/statusMap.js';
3
+ /** The stage Gati's milestone codes give a scan code. */
4
+ export declare function gatiMappedStage(code: string): Stage | undefined;
5
+ /** A scan's stage: its code, else the shared wording rules, else nothing. */
6
+ export declare function gatiStage(code: string, wording: string): ClassifiedWording | null;
7
+ export declare const statusMap: CarrierStatusMap;
@@ -0,0 +1,37 @@
1
+ import { classifyWording } from '../../core/status/index.js';
2
+ /**
3
+ * Gati's milestone codes, which come with each scan. The reply pairs most with
4
+ * a milestone, M1 at booking to M8 at delivery, and the hub scans between with
5
+ * none. Only codes seen in replies are mapped; another code falls to the
6
+ * wording rules.
7
+ */
8
+ const CODES = new Map([
9
+ // Booked at the pickup branch, which the page calls the pickup: Gati books a docket when it takes the goods.
10
+ ['DCRE', 'accepted'],
11
+ ['TCSOU', 'in_transit'], // Departed from the booking branch.
12
+ ['TCAER', 'in_transit'], // Received at a branch or transhipment centre.
13
+ ['TCSEO', 'in_transit'], // Sent on to the next location, which the wording names.
14
+ ['DKTAD', 'in_transit'], // Arrived at the delivery branch.
15
+ ['DPDCC', 'out_for_delivery'],
16
+ ['DUNDL', 'failed_attempt'], // Undelivered, with the reason; the docket goes out again.
17
+ // Some of the docket's packages were delivered; the rest are still on their way.
18
+ ['DDPVD', 'in_transit'],
19
+ ['DDLVD', 'delivered'],
20
+ ['DDETN', 'exception'], // The docket is held, as after a missed connection.
21
+ ]);
22
+ /** The stage Gati's milestone codes give a scan code. */
23
+ export function gatiMappedStage(code) {
24
+ return CODES.get(code.toUpperCase());
25
+ }
26
+ /** A scan's stage: its code, else the shared wording rules, else nothing. */
27
+ export function gatiStage(code, wording) {
28
+ const mapped = gatiMappedStage(code);
29
+ if (mapped)
30
+ return { stage: mapped, source: 'carrier_map' };
31
+ const worded = classifyWording(wording, 'in_transit');
32
+ return worded.source === 'none' ? null : worded;
33
+ }
34
+ export const statusMap = {
35
+ stage: (code) => (code ? gatiMappedStage(code) : undefined),
36
+ gaps: [],
37
+ };
@@ -1,9 +1,20 @@
1
1
  {
2
2
  "carrier": "gati",
3
3
  "entries": [
4
+ {"code": "DCRE", "wording": "Shipment Booked", "language": "en", "stage": "accepted", "confirmedBy": "live", "note": "Milestone M1: the docket is booked at the branch that takes the goods, which the tracking page calls the pickup."},
5
+ {"code": "TCSOU", "wording": "Departed From Origin", "language": "en", "stage": "in_transit", "confirmedBy": "live", "note": "Milestone M2: left the booking branch."},
6
+ {"code": "TCAER", "wording": "Received At …", "language": "en", "stage": "in_transit", "confirmedBy": "live", "note": "Received at the branch or transhipment centre the wording names; no milestone."},
7
+ {"code": "TCSEO", "wording": "Out For Next Location …", "language": "en", "stage": "in_transit", "confirmedBy": "live", "note": "Sent on to the location the wording names; no milestone."},
8
+ {"code": "DKTAD", "wording": "Arrived At Destination", "language": "en", "stage": "in_transit", "confirmedBy": "live", "note": "Milestone M4: at the delivery branch."},
9
+ {"code": "DPDCC", "wording": "Out For Delivery", "language": "en", "stage": "out_for_delivery", "confirmedBy": "live", "note": "Milestone M5."},
10
+ {"code": "DUNDL", "wording": "Undelivered Due To …", "language": "en", "stage": "failed_attempt", "confirmedBy": "live", "note": "Milestone M6, with the reason, such as Consignee Premises Closed, Consignee Request For Rescheduling or Force Majeure External Reasons. The docket goes out for delivery again."},
11
+ {"code": "DDPVD", "wording": "Partial Delivered", "language": "en", "stage": "in_transit", "confirmedBy": "live", "note": "Milestone M7: some of the docket's packages were delivered and the rest came on a later delivery."},
12
+ {"code": "DDLVD", "wording": "Delivered", "language": "en", "stage": "delivered", "confirmedBy": "live", "note": "Milestone M8. The docket's own status reads Delivered too."},
13
+ {"code": "DDETN", "wording": "Docket Detained For", "language": "en", "stage": "exception", "confirmedBy": "live", "note": "The docket is held; the wording names no reason. Seen months after a delivery, whose docket status stayed Delivered."},
4
14
  {"wording": "Delivered", "stage": "delivered", "language": "en", "confirmedBy": "portal", "note": "Status column of Gati's former tracker at gati.com in an archived lookup."},
5
15
  {"wording": "Out for delivery", "stage": "out_for_delivery", "language": "en", "confirmedBy": "source", "note": "Listed in TrackingMore's table of Gati KWE statuses."},
6
16
  {"wording": "Arrived at destination", "stage": "in_transit", "language": "en", "confirmedBy": "source", "note": "Listed in TrackingMore's table of Gati KWE statuses: at the destination branch."},
7
- {"wording": "Docket detained - connection missed", "stage": "exception", "language": "en", "confirmedBy": "source", "note": "Listed in TrackingMore's table of Gati KWE statuses: held after missing a connection."}
17
+ {"wording": "Docket detained - connection missed", "stage": "exception", "language": "en", "confirmedBy": "source", "note": "Listed in TrackingMore's table of Gati KWE statuses: held after missing a connection."},
18
+ {"wording": "Check Docket No", "language": "en", "confirmedBy": "live", "note": "The tracking service's answer for a docket it does not know; not an event."}
8
19
  ]
9
20
  }
@@ -0,0 +1,19 @@
1
+ import { type AdapterFactory, type Recognition, type TrackingContext } from '../../core/adapter/index.js';
2
+ import type { CarrierResult } from '../../core/result/index.js';
3
+ import { type StepRecorder } from '../../core/telemetry/index.js';
4
+ /** The delivery service's history of one AWB, which the tracker reads once it has opened the parcel. */
5
+ export declare const SHADOWFAX_TRACK_API = "https://saruman.shadowfax.in/web_app/delivery/track/";
6
+ /** The tracker's own lookup of a typed number, which tells a number Shadowfax does not know. */
7
+ export declare const SHADOWFAX_LOOKUP_API = "https://saruman.shadowfax.in/awb/awb_to_unique_code/";
8
+ export declare class ShadowfaxTracker {
9
+ private readonly options;
10
+ constructor(options?: {
11
+ fetcher?: typeof fetch;
12
+ recorder?: StepRecorder;
13
+ userAgent?: string;
14
+ });
15
+ fetch(raw: string, context?: TrackingContext): Promise<CarrierResult>;
16
+ /** A record that names the number is a parcel Shadowfax knows, with scans or without. */
17
+ recognize(number: string, context?: TrackingContext): Promise<Recognition>;
18
+ }
19
+ export declare const adapter: AdapterFactory;
@@ -0,0 +1,93 @@
1
+ import { accepted, recognizeFromLookup } from '../../core/adapter/index.js';
2
+ import { ChallengeError, IndeterminateError, NoHistoryError, SchemaError, TransportError } from '../../core/errors/index.js';
3
+ import { runSteps } from '../../core/runner/index.js';
4
+ import { firstAttemptMs, networkRetryStep } from '../../core/runner/networkRetry.js';
5
+ import { NOOP_RECORDER } from '../../core/telemetry/index.js';
6
+ import { decodeText, fetchBounded, userAgentOf } from '../../core/transport/index.js';
7
+ import { NO_DELIVERY, normalizeShadowfaxNumber, parseShadowfax, PROVIDER, SHADOWFAX_MAX_BYTES, shadowfaxMessage, shadowfaxUnknown } from './parser.js';
8
+ const API = 'https://saruman.shadowfax.in';
9
+ /** The delivery service's history of one AWB, which the tracker reads once it has opened the parcel. */
10
+ export const SHADOWFAX_TRACK_API = `${API}/web_app/delivery/track/`;
11
+ /** The tracker's own lookup of a typed number, which tells a number Shadowfax does not know. */
12
+ export const SHADOWFAX_LOOKUP_API = `${API}/awb/awb_to_unique_code/`;
13
+ // The token the tracker's script and the website's track page send with
14
+ // every lookup, the same for every visitor.
15
+ const TRACKER_TOKEN = 'cePcVR7z7FIETB4PxguHC2YJGk6NncHnByrJttgRIUqNxfWezuzAUvtALyqcHJEC'; // gitleaks:allow
16
+ const REDIRECTS = [301, 302, 303, 307, 308];
17
+ // The services answer a number they do not know with HTTP 400 and a message.
18
+ const REFUSED = 400;
19
+ // A missing route is not a missing parcel.
20
+ const GONE = [404, 410];
21
+ // Bot checks a CDN or firewall could put in place of the reply.
22
+ const CHALLENGE = /_cf_chl_opt|cf-turnstile|<title>\s*(?:Just a moment|Attention Required|Access denied)|captcha/i;
23
+ function json(body) {
24
+ try {
25
+ return JSON.parse(body);
26
+ }
27
+ catch (cause) {
28
+ if (CHALLENGE.test(body.slice(0, 64_000)))
29
+ throw new ChallengeError(PROVIDER, 'Shadowfax answered with a browser check', { cause });
30
+ throw new SchemaError(PROVIDER, 'Shadowfax returned a reply that is not JSON', { cause });
31
+ }
32
+ }
33
+ export class ShadowfaxTracker {
34
+ options;
35
+ constructor(options = {}) {
36
+ this.options = options;
37
+ }
38
+ async fetch(raw, context = {}) {
39
+ const number = normalizeShadowfaxNumber(raw);
40
+ // One attempt reads the delivery service's history. For a number it has
41
+ // no delivery request under, the tracker's own lookup says whether
42
+ // Shadowfax knows the number at all.
43
+ const attempt = async (signal, timeoutMs) => {
44
+ const deadline = performance.now() + timeoutMs;
45
+ const get = async (url) => {
46
+ signal.throwIfAborted();
47
+ const { response, bytes } = await fetchBounded(url, { method: 'GET', signal, headers: {
48
+ Accept: 'application/json', Authorization: `Token ${TRACKER_TOKEN}`, 'User-Agent': userAgentOf(this.options.userAgent),
49
+ } }, { provider: PROVIDER, timeoutMs: Math.max(1, Math.floor(deadline - performance.now())), maxBytes: SHADOWFAX_MAX_BYTES,
50
+ redirect: 'manual', allowHttpStatuses: [...REDIRECTS, REFUSED, ...GONE], fetcher: this.options.fetcher });
51
+ if (REDIRECTS.includes(response.status))
52
+ throw new IndeterminateError(PROVIDER, 'Shadowfax moved its tracking service');
53
+ if (GONE.includes(response.status))
54
+ throw new TransportError(PROVIDER, 'Shadowfax tracking service is unavailable');
55
+ return { status: response.status, payload: json(decodeText(bytes)) };
56
+ };
57
+ const track = await get(`${SHADOWFAX_TRACK_API}${number}/`);
58
+ if (track.status !== REFUSED)
59
+ return parseShadowfax(track.payload, number);
60
+ if (shadowfaxMessage(track.payload) !== NO_DELIVERY)
61
+ throw new IndeterminateError(PROVIDER, 'Shadowfax refused the lookup');
62
+ const lookup = await get(`${SHADOWFAX_LOOKUP_API}?${new URLSearchParams({ order_id: number })}`);
63
+ return shadowfaxUnknown(lookup.status, lookup.payload, number);
64
+ };
65
+ // A request that fails to reach Shadowfax, or hangs, gets one more try:
66
+ // the first gets half of the budget, so the retry fits in the rest. An
67
+ // HTTP status, a rate limit included, is never sent again.
68
+ return runSteps({ carrier: 'shadowfax', budgetMs: context.budgetMs ?? 15_000, signal: context.signal,
69
+ recorder: this.options.recorder ?? NOOP_RECORDER }, [
70
+ { id: 'direct', run: ({ signal, remainingMs }) => attempt(signal, firstAttemptMs(remainingMs)) },
71
+ networkRetryStep(({ signal, remainingMs }) => attempt(signal, remainingMs)),
72
+ ]);
73
+ }
74
+ /** A record that names the number is a parcel Shadowfax knows, with scans or without. */
75
+ async recognize(number, context = {}) {
76
+ try {
77
+ return await recognizeFromLookup(() => this.fetch(number, context), () => accepted(() => normalizeShadowfaxNumber(number)));
78
+ }
79
+ catch (error) {
80
+ if (error instanceof NoHistoryError)
81
+ return { known: true, lastActivityAt: null };
82
+ throw error;
83
+ }
84
+ }
85
+ }
86
+ export const adapter = (environment) => {
87
+ const tracker = new ShadowfaxTracker({ fetcher: environment.fetcher, recorder: environment.recorder, userAgent: environment.userAgent });
88
+ return {
89
+ id: 'shadowfax', recordsSteps: true, steps: ['direct', 'retry'],
90
+ track: (input, context) => tracker.fetch(input.number, context),
91
+ recognize: (number, context) => tracker.recognize(number, context),
92
+ };
93
+ };
@@ -19,18 +19,66 @@
19
19
  "timezone": "Asia/Kolkata",
20
20
  "tracking": {
21
21
  "mode": "automatic",
22
- "adapter": "universal",
23
- "steps": []
22
+ "adapter": "shadowfax",
23
+ "steps": [
24
+ "direct",
25
+ "retry"
26
+ ],
27
+ "recognition": {
28
+ "rank": 595
29
+ }
24
30
  },
25
- "capabilities": [],
31
+ "capabilities": [
32
+ "history",
33
+ "provider_code",
34
+ "location",
35
+ "eta",
36
+ "delivered_at",
37
+ "offset_timestamps"
38
+ ],
26
39
  "portal": {
27
40
  "url": "https://tracker.shadowfax.in/#/awb/{trackingNumber}",
28
41
  "searchUrl": "https://www.shadowfax.in/track",
29
42
  "canaryUrl": "https://www.shadowfax.in/track",
30
- "shows": [],
31
- "scraped": [],
32
- "discarded": [],
33
- "unavailable": []
43
+ "shows": [
44
+ "status",
45
+ "history",
46
+ "location",
47
+ "eta",
48
+ "delivered_at",
49
+ "progress_rail",
50
+ "proof_of_delivery",
51
+ "contact_details",
52
+ "remarks",
53
+ "merchant_reference",
54
+ "payment_details",
55
+ "recipient_address"
56
+ ],
57
+ "scraped": [
58
+ "status",
59
+ "history",
60
+ "provider_code",
61
+ "location",
62
+ "eta",
63
+ "delivered_at",
64
+ "offset_timestamps"
65
+ ],
66
+ "discarded": [
67
+ "progress_rail",
68
+ "proof_of_delivery",
69
+ "contact_details",
70
+ "remarks",
71
+ "merchant_reference",
72
+ "payment_details",
73
+ "recipient_address"
74
+ ],
75
+ "unavailable": [
76
+ "weight",
77
+ "service_name",
78
+ "sender_name",
79
+ "recipient_name",
80
+ "delivery_partner"
81
+ ]
34
82
  },
35
83
  "links": [
36
84
  {