universal-parcel-scraper 0.178.0-main.1306 → 0.181.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.
Files changed (49) hide show
  1. package/README.md +3 -3
  2. package/data/catalog.json +56 -4
  3. package/data/coverage-summary.json +2 -2
  4. package/data/detection-golden.json +16 -0
  5. package/dist/browser/scraper.js +49 -6
  6. package/dist/carriers/5post/adapter.d.ts +22 -0
  7. package/dist/carriers/5post/adapter.js +75 -0
  8. package/dist/carriers/5post/carrier.json +44 -7
  9. package/dist/carriers/5post/numbers.json +22 -22
  10. package/dist/carriers/5post/parser.d.ts +23 -0
  11. package/dist/carriers/5post/parser.js +164 -0
  12. package/dist/carriers/5post/status.d.ts +9 -0
  13. package/dist/carriers/5post/status.js +100 -0
  14. package/dist/carriers/5post/statuses.json +63 -3
  15. package/dist/carriers/ems-vietnam/adapter.d.ts +17 -0
  16. package/dist/carriers/ems-vietnam/adapter.js +60 -0
  17. package/dist/carriers/ems-vietnam/carrier.json +65 -7
  18. package/dist/carriers/ems-vietnam/parser.d.ts +22 -0
  19. package/dist/carriers/ems-vietnam/parser.js +216 -0
  20. package/dist/carriers/ems-vietnam/status.d.ts +7 -0
  21. package/dist/carriers/ems-vietnam/status.js +55 -0
  22. package/dist/carriers/ems-vietnam/statuses.json +16 -0
  23. package/dist/carriers/israel-post/adapter.d.ts +14 -0
  24. package/dist/carriers/israel-post/adapter.js +57 -0
  25. package/dist/carriers/israel-post/carrier.json +40 -7
  26. package/dist/carriers/israel-post/parser.d.ts +6 -0
  27. package/dist/carriers/israel-post/parser.js +77 -0
  28. package/dist/carriers/israel-post/status.d.ts +4 -0
  29. package/dist/carriers/israel-post/status.js +15 -0
  30. package/dist/carriers/israel-post/statuses.json +37 -1
  31. package/dist/carriers/mayiyinfu/carrier.json +54 -0
  32. package/dist/carriers/mayiyinfu/numbers.json +17 -0
  33. package/dist/carriers/mayiyinfu/statuses.json +16 -0
  34. package/dist/carriers/pecom/adapter.d.ts +17 -0
  35. package/dist/carriers/pecom/adapter.js +60 -0
  36. package/dist/carriers/pecom/carrier.json +52 -7
  37. package/dist/carriers/pecom/parser.d.ts +13 -0
  38. package/dist/carriers/pecom/parser.js +214 -0
  39. package/dist/carriers/pecom/status.d.ts +7 -0
  40. package/dist/carriers/pecom/status.js +52 -0
  41. package/dist/carriers/pecom/statuses.json +9 -7
  42. package/dist/core/catalog/statusMaps.js +9 -4
  43. package/dist/data/catalog.json +56 -4
  44. package/dist/generated/catalog.d.ts +38 -5
  45. package/dist/generated/catalog.js +59 -5
  46. package/dist/generated/recognition.js +2 -0
  47. package/dist/generated/registry.js +13 -4
  48. package/dist/server/openapi.json +1 -1
  49. package/package.json +1 -1
@@ -0,0 +1,77 @@
1
+ import { DateTime } from 'luxon';
2
+ import { isValidS10TrackingNumber, normalizeTrackingNumber } from '../../core/detection/index.js';
3
+ import { IndeterminateError, InvalidInputError, NoHistoryError, SchemaError } from '../../core/errors/index.js';
4
+ import { languageStageStatus } from '../../core/status/index.js';
5
+ import { clean } from '../../core/transport/index.js';
6
+ import { isRecord } from '../../core/types.js';
7
+ import { israelPostStage } from './status.js';
8
+ export const PROVIDER = 'Israel Post';
9
+ const MAX_ROWS = 500;
10
+ const MAX_EVENTS = 100;
11
+ /** Postal S10 items, including imports, and Israel Post's domestic courier identifiers. */
12
+ export function normalizeIsraelPostNumber(raw) {
13
+ const number = raw.length <= 64 ? normalizeTrackingNumber(raw) : '';
14
+ if (isValidS10TrackingNumber(number) || /^\d{11}IL$/.test(number))
15
+ return number;
16
+ throw new InvalidInputError(PROVIDER, 'Israel Post requires an S10 item or domestic courier number');
17
+ }
18
+ function text(value) {
19
+ if (typeof value !== 'string' || !value.trim() || value.length > 2000) {
20
+ throw new SchemaError(PROVIDER, 'Israel Post returned invalid scan text');
21
+ }
22
+ return clean(value, 500);
23
+ }
24
+ /** The native guest read returns an identity and Maslul, newest first. */
25
+ export function parseIsraelPost(payload, raw) {
26
+ const number = normalizeIsraelPostNumber(raw);
27
+ if (!isRecord(payload) || typeof payload.ItemCode !== 'string' || !/^[A-Z0-9]{13}$/i.test(payload.ItemCode)) {
28
+ throw new SchemaError(PROVIDER, 'Israel Post returned no item identity');
29
+ }
30
+ if (payload.ItemCode.toUpperCase() !== number)
31
+ throw new IndeterminateError(PROVIDER, 'Israel Post answered for another item');
32
+ const rows = payload.Maslul;
33
+ if (!Array.isArray(rows) || rows.length > MAX_ROWS)
34
+ throw new SchemaError(PROVIDER, 'Israel Post returned an invalid history');
35
+ // The service echoes unknown identifiers with a default category. That shell
36
+ // establishes neither a shipment nor definite absence from the postal network.
37
+ if (!rows.length)
38
+ throw new NoHistoryError(PROVIDER);
39
+ const seen = new Set();
40
+ const events = [];
41
+ for (const row of rows) {
42
+ if (!isRecord(row) || !Number.isInteger(row.CategoryCode) || (row.CategoryCode < 0 || row.CategoryCode > 9999)) {
43
+ throw new SchemaError(PROVIDER, 'Israel Post returned an invalid event category');
44
+ }
45
+ const written = row.StatusDate;
46
+ if (typeof written !== 'string' || !/^\d{2}\/\d{2}\/\d{4}$/.test(written)) {
47
+ throw new SchemaError(PROVIDER, 'Israel Post returned an event without its day');
48
+ }
49
+ const date = DateTime.fromFormat(written, 'dd/MM/yyyy', { zone: 'UTC' });
50
+ if (!date.isValid)
51
+ throw new SchemaError(PROVIDER, 'Israel Post returned an invalid event day');
52
+ const code = String(row.CategoryCode);
53
+ const description = text(row.Status);
54
+ const event = { local_time: date.toISODate(), description, provider_code: code };
55
+ const stage = israelPostStage(code);
56
+ if (stage)
57
+ Object.assign(event, { stage, stage_source: 'carrier_map' });
58
+ const identity = JSON.stringify(event);
59
+ if (seen.has(identity))
60
+ continue;
61
+ seen.add(identity);
62
+ events.push(event);
63
+ }
64
+ // Preserve the server's order within a day; there is no time of day to infer.
65
+ events.sort((a, b) => String(b.local_time).localeCompare(String(a.local_time)));
66
+ const newest = events[0];
67
+ const stage = israelPostStage(newest.provider_code);
68
+ return {
69
+ status: stage ? languageStageStatus(stage) : 'unknown',
70
+ ...(stage ? { current_stage: stage, current_stage_source: 'carrier_map' } : {}),
71
+ last_status_text: newest.description, last_update: null, last_update_local: newest.local_time,
72
+ expected_delivery: null, events: events.slice(0, MAX_EVENTS),
73
+ // The carrier warns that registered-item tracking covers its domestic leg.
74
+ // Let enabled providers supplement the history, including foreign scans.
75
+ history_truncated: true,
76
+ };
77
+ }
@@ -0,0 +1,4 @@
1
+ import type { Stage } from '../../core/status/index.js';
2
+ import type { CarrierStatusMap } from '../../core/status/statusMap.js';
3
+ export declare function israelPostStage(code: string): Stage | undefined;
4
+ export declare const statusMap: CarrierStatusMap;
@@ -0,0 +1,15 @@
1
+ /** Categories of the native tracking history, not the summary's default StatusCode. */
2
+ const CATEGORIES = {
3
+ '3': 'in_transit',
4
+ '4': 'ready_for_pickup',
5
+ '5': 'delivered',
6
+ '6': 'exception',
7
+ '23': 'accepted',
8
+ };
9
+ export function israelPostStage(code) {
10
+ return Object.hasOwn(CATEGORIES, code) ? CATEGORIES[code] : undefined;
11
+ }
12
+ export const statusMap = {
13
+ stage: code => code ? israelPostStage(code) : undefined,
14
+ gaps: [],
15
+ };
@@ -1,4 +1,40 @@
1
1
  {
2
2
  "carrier": "israel-post",
3
- "entries": []
3
+ "entries": [
4
+ {
5
+ "code": "3",
6
+ "wording": "בתהליך מיון",
7
+ "stage": "in_transit",
8
+ "language": "he",
9
+ "confirmedBy": "live"
10
+ },
11
+ {
12
+ "code": "4",
13
+ "wording": "ממתין לאיסוף שלך",
14
+ "stage": "ready_for_pickup",
15
+ "language": "he",
16
+ "confirmedBy": "live"
17
+ },
18
+ {
19
+ "code": "5",
20
+ "wording": "נמסר",
21
+ "stage": "delivered",
22
+ "language": "he",
23
+ "confirmedBy": "live"
24
+ },
25
+ {
26
+ "code": "6",
27
+ "wording": "לא נמסר ויוחזר לשולח",
28
+ "stage": "exception",
29
+ "language": "he",
30
+ "confirmedBy": "live"
31
+ },
32
+ {
33
+ "code": "23",
34
+ "wording": "נקלט למשלוח",
35
+ "stage": "accepted",
36
+ "language": "he",
37
+ "confirmedBy": "live"
38
+ }
39
+ ]
4
40
  }
@@ -0,0 +1,54 @@
1
+ {
2
+ "id": "mayiyinfu",
3
+ "displayName": "Mayi Yinfu",
4
+ "aliases": [
5
+ "Mayiyinfu",
6
+ "MYYF",
7
+ "蚂蚁银服",
8
+ "螞蟻銀服",
9
+ "广东蚂蚁银服国际物流有限公司",
10
+ "Mayi Yinfu International Logistics"
11
+ ],
12
+ "region": {
13
+ "countries": [
14
+ "CN"
15
+ ]
16
+ },
17
+ "brand": {
18
+ "color": "#000000"
19
+ },
20
+ "selectable": true,
21
+ "timezone": "Asia/Shanghai",
22
+ "tracking": {
23
+ "mode": "automatic",
24
+ "adapter": "universal",
25
+ "steps": []
26
+ },
27
+ "capabilities": [],
28
+ "portal": {
29
+ "canaryUrl": "https://t.17track.net/",
30
+ "shows": [],
31
+ "scraped": [],
32
+ "discarded": [],
33
+ "unavailable": []
34
+ },
35
+ "links": [
36
+ {
37
+ "domains": [
38
+ "mayiyinfu.com.cn",
39
+ "www.mayiyinfu.com.cn"
40
+ ],
41
+ "pathPattern": "^/trackIndex\\.htm$",
42
+ "params": [
43
+ "documentCode"
44
+ ]
45
+ }
46
+ ],
47
+ "detection": [
48
+ {
49
+ "id": "mayiyinfu-1",
50
+ "pattern": "^MY\\d{10}US$",
51
+ "confidence": "high"
52
+ }
53
+ ]
54
+ }
@@ -0,0 +1,17 @@
1
+ {
2
+ "carrier": "mayiyinfu",
3
+ "records": [
4
+ {
5
+ "number": "MY9900000001US",
6
+ "role": "shipment",
7
+ "evidence": "synthetic",
8
+ "derivedFrom": "donated_real",
9
+ "shapeConfirmed": "2026-10-15",
10
+ "expect": {
11
+ "carrier": "mayiyinfu",
12
+ "confidence": "high"
13
+ },
14
+ "note": "Made-up number in the shape of the tracking number Mayi Yinfu's own tracker gives a parcel."
15
+ }
16
+ ]
17
+ }
@@ -0,0 +1,16 @@
1
+ {
2
+ "carrier": "mayiyinfu",
3
+ "entries": [
4
+ {"wording": "货物电子信息已经收到", "language": "zh", "stage": "registered", "confirmedBy": "live", "note": "The Hualei platform's own row on the order's creation time: the shipment data has arrived."},
5
+ {"wording": "已入库,到达收货点", "language": "zh", "stage": "accepted", "confirmedBy": "live", "note": "Booked into the warehouse at the receiving point."},
6
+ {"wording": "已出库,货物离开操作中心", "language": "zh", "stage": "in_transit", "confirmedBy": "live", "note": "Booked out: the parcel has left the operations centre."},
7
+ {"wording": "国内清关中", "language": "zh", "stage": "customs", "confirmedBy": "live", "note": "Export customs clearance in China is under way."},
8
+ {"wording": "已排航班", "language": "zh", "stage": "in_transit", "confirmedBy": "live", "note": "A flight has been booked."},
9
+ {"wording": "货物已交机场,等待安排航班中The goods have been delivered to the airport and are awaiting the arrangement of flights.", "language": "zh", "stage": "in_transit", "confirmedBy": "live", "note": "Handed to the airport to wait for a flight. It is not a delivery to the recipient, though a translation may read 'Delivered'."},
10
+ {"wording": "起运地航班起飞", "language": "zh", "stage": "in_transit", "confirmedBy": "live", "note": "The flight has left the origin."},
11
+ {"wording": "已到达目的国", "language": "zh", "stage": "in_transit", "confirmedBy": "live", "note": "Arrived in the destination country or region."},
12
+ {"wording": "清关完成", "language": "zh", "stage": "customs", "confirmedBy": "live", "note": "Customs clearance is complete."},
13
+ {"wording": "清关完成,待转运Clearance has been completed and it is awaiting transfer.", "language": "zh", "stage": "customs", "confirmedBy": "live", "note": "Cleared at the destination and waiting to be handed to the delivering carrier."},
14
+ {"wording": "已转运transferred", "language": "zh", "stage": "in_transit", "confirmedBy": "live", "note": "Handed to the delivering carrier, whose number the tracker then shows."}
15
+ ]
16
+ }
@@ -0,0 +1,17 @@
1
+ import type { AdapterFactory, 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 JSON-RPC endpoint PEC's website calls for everything it looks up. */
5
+ export declare const PECOM_API = "https://pecom.ru/ajax/";
6
+ /** The method the tracking page calls for one cargo's details and status history. */
7
+ export declare const PECOM_METHOD = "LK.OCR.Get";
8
+ export declare class PecomTracker {
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
+ }
17
+ export declare const adapter: AdapterFactory;
@@ -0,0 +1,60 @@
1
+ import { ChallengeError, SchemaError, TransportError } from '../../core/errors/index.js';
2
+ import { runSteps } from '../../core/runner/index.js';
3
+ import { firstAttemptMs, networkRetryStep } from '../../core/runner/networkRetry.js';
4
+ import { NOOP_RECORDER } from '../../core/telemetry/index.js';
5
+ import { decodeText, fetchBounded, userAgentOf } from '../../core/transport/index.js';
6
+ import { normalizePecomNumber, parsePecom, PECOM_MAX_BYTES, PROVIDER } from './parser.js';
7
+ /** The JSON-RPC endpoint PEC's website calls for everything it looks up. */
8
+ export const PECOM_API = 'https://pecom.ru/ajax/';
9
+ /** The method the tracking page calls for one cargo's details and status history. */
10
+ export const PECOM_METHOD = 'LK.OCR.Get';
11
+ // The page sends its session id, which the lookup does not check, so a fixed one stands in.
12
+ const GUEST_SESSION = '0'.repeat(32);
13
+ const REDIRECTS = [301, 302, 303, 307, 308];
14
+ // Qrator's script check, which fronts pecom.ru.
15
+ const CHALLENGE = /__qrator|qauth\.js/i;
16
+ function json(body, status) {
17
+ try {
18
+ return JSON.parse(body);
19
+ }
20
+ catch (cause) {
21
+ if (CHALLENGE.test(body.slice(0, 4_000)))
22
+ throw new ChallengeError(PROVIDER, 'PEC answered with its bot check', { cause, status });
23
+ if (status === 401)
24
+ throw new ChallengeError(PROVIDER, 'PEC refused the lookup', { cause, status });
25
+ throw new SchemaError(PROVIDER, 'PEC returned a reply that is not JSON', { cause });
26
+ }
27
+ }
28
+ export class PecomTracker {
29
+ options;
30
+ constructor(options = {}) {
31
+ this.options = options;
32
+ }
33
+ async fetch(raw, context = {}) {
34
+ const number = normalizePecomNumber(raw);
35
+ const read = async (signal, timeoutMs) => {
36
+ const { response, bytes } = await fetchBounded(PECOM_API, { method: 'POST', signal, headers: {
37
+ Accept: 'application/json', 'Content-Type': 'application/json', 'User-Agent': userAgentOf(this.options.userAgent),
38
+ }, body: JSON.stringify({ id: Date.now(), jsonrpc: '2.0', method: PECOM_METHOD, sessid: GUEST_SESSION, params: { cargoIndex: number } }) }, { provider: PROVIDER, timeoutMs: Math.max(1, Math.floor(timeoutMs)), maxBytes: PECOM_MAX_BYTES, redirect: 'manual',
39
+ fetcher: this.options.fetcher, allowHttpStatuses: [...REDIRECTS, 401] });
40
+ if (REDIRECTS.includes(response.status))
41
+ throw new TransportError(PROVIDER, 'PEC redirected its tracking lookup');
42
+ // JSON-RPC errors come with HTTP 401, PEC's answer to an unknown cargo among them.
43
+ return parsePecom(json(decodeText(bytes), response.status), number);
44
+ };
45
+ // A request that fails to reach PEC, or hangs, gets one more try: the
46
+ // first gets half of the budget, so the retry fits in the rest.
47
+ return runSteps({ carrier: 'pecom', budgetMs: context.budgetMs ?? 15_000, signal: context.signal,
48
+ recorder: this.options.recorder ?? NOOP_RECORDER }, [
49
+ { id: 'direct', run: ({ signal, remainingMs }) => read(signal, firstAttemptMs(remainingMs)) },
50
+ networkRetryStep(({ signal, remainingMs }) => read(signal, remainingMs)),
51
+ ]);
52
+ }
53
+ }
54
+ export const adapter = (environment) => {
55
+ const tracker = new PecomTracker({ fetcher: environment.fetcher, recorder: environment.recorder, userAgent: environment.userAgent });
56
+ return {
57
+ id: 'pecom', recordsSteps: true, steps: ['direct', 'retry'],
58
+ track: (input, context) => tracker.fetch(input.number, context),
59
+ };
60
+ };
@@ -22,18 +22,63 @@
22
22
  "timezone": "Europe/Moscow",
23
23
  "tracking": {
24
24
  "mode": "automatic",
25
- "adapter": "universal",
26
- "steps": []
25
+ "adapter": "pecom",
26
+ "steps": [
27
+ "direct",
28
+ "retry"
29
+ ],
30
+ "localClocks": true
27
31
  },
28
- "capabilities": [],
32
+ "capabilities": [
33
+ "history",
34
+ "location",
35
+ "eta",
36
+ "weight",
37
+ "pickup_point"
38
+ ],
29
39
  "portal": {
30
40
  "url": "https://pecom.ru/services-are/order-status/?code={trackingNumber}",
31
41
  "searchUrl": "https://pecom.ru/services-are/order-status/",
32
42
  "canaryUrl": "https://pecom.ru/services-are/order-status/",
33
- "shows": [],
34
- "scraped": [],
35
- "discarded": [],
36
- "unavailable": []
43
+ "shows": [
44
+ "status",
45
+ "history",
46
+ "location",
47
+ "eta",
48
+ "weight",
49
+ "volume",
50
+ "parcel_count",
51
+ "item_category",
52
+ "service_name",
53
+ "pickup_point",
54
+ "office_contact_details",
55
+ "office_opening_hours",
56
+ "origin",
57
+ "payment_details"
58
+ ],
59
+ "scraped": [
60
+ "status",
61
+ "history",
62
+ "location",
63
+ "eta",
64
+ "weight",
65
+ "pickup_point"
66
+ ],
67
+ "discarded": [
68
+ "volume",
69
+ "parcel_count",
70
+ "item_category",
71
+ "service_name",
72
+ "office_contact_details",
73
+ "office_opening_hours",
74
+ "origin",
75
+ "payment_details"
76
+ ],
77
+ "unavailable": [
78
+ "sender_name",
79
+ "recipient_name",
80
+ "offset_timestamps"
81
+ ]
37
82
  },
38
83
  "links": [
39
84
  {
@@ -0,0 +1,13 @@
1
+ import { type CarrierResult } from '../../core/result/index.js';
2
+ export declare const PROVIDER = "PEC";
3
+ export declare const PECOM_MAX_BYTES: number;
4
+ /** A cargo code: twelve digits, sometimes typed in groups of four. Anything else is not one PEC's tracker takes. */
5
+ export declare function normalizePecomNumber(raw: string): string;
6
+ /**
7
+ * The reply of `LK.OCR.Get` for one cargo code, the call PEC's tracking page
8
+ * makes for a cargo's details. PEC answers a code it does not know with a
9
+ * JSON-RPC error. The cargo must carry the whole code asked. Its current
10
+ * status decides the stage; its dated statuses and transit rows are the
11
+ * history. Sender and recipient details in the reply are never read.
12
+ */
13
+ export declare function parsePecom(payload: unknown, raw: string): CarrierResult;
@@ -0,0 +1,214 @@
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 { eventPoint } from '../../core/result/index.js';
5
+ import { languageStageStatus } from '../../core/status/index.js';
6
+ import { clean } from '../../core/transport/index.js';
7
+ import { isRecord } from '../../core/types.js';
8
+ import { pecomStage } from './status.js';
9
+ export const PROVIDER = 'PEC';
10
+ // A cargo's reply carries both terminals' timetables and its storage days; a
11
+ // long-stored one is under 300 kilobytes.
12
+ export const PECOM_MAX_BYTES = 2 * 1024 * 1024;
13
+ // PEC's error for a cargo code it does not know: "Запрашиваемый Вами груз … не найден".
14
+ const NOT_FOUND = -33000;
15
+ const NOT_FOUND_WORDING = /не\s+найден/iu;
16
+ const CLOCK = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/;
17
+ // A status PEC records without a time of day gets the last second of its day.
18
+ const END_OF_DAY = 'T23:59:59';
19
+ // Where a status happens, by its id: acceptance (1) and documentation (3) at
20
+ // the sending department, arrival (5) and collection (8) at the receiving one.
21
+ // Transit (4) and door delivery (9) name no department.
22
+ const AT_SOURCE = new Set([1, 3]);
23
+ const AT_TARGET = new Set([5, 8]);
24
+ const ARRIVED = 5;
25
+ const MAX_ROWS = 200;
26
+ // Stages before the cargo reaches the receiving terminal, when its forecast still matters.
27
+ const BEFORE_ARRIVAL = new Set(['registered', 'accepted', 'in_transit', 'customs']);
28
+ /** A cargo code: twelve digits, sometimes typed in groups of four. Anything else is not one PEC's tracker takes. */
29
+ export function normalizePecomNumber(raw) {
30
+ const number = raw.length <= 64 ? normalizeTrackingNumber(raw) : '';
31
+ if (!/^\d{12}$/.test(number))
32
+ throw new InvalidInputError(PROVIDER, 'PEC cargo codes are twelve digits');
33
+ return number;
34
+ }
35
+ /** An optional text field; anything but a string is a changed reply. */
36
+ function text(row, key, maxLength = 300) {
37
+ const value = row[key];
38
+ if (value === null || value === undefined)
39
+ return '';
40
+ if (typeof value !== 'string')
41
+ throw new SchemaError(PROVIDER, `PEC returned an invalid ${key}`);
42
+ return clean(value, maxLength);
43
+ }
44
+ /** An optional wall clock to the second. The reply names no zone, so it stays local. */
45
+ function clock(row, key) {
46
+ const value = text(row, key, 32);
47
+ if (!value)
48
+ return undefined;
49
+ // Parsing in UTC checks the calendar digits only; the wall clock keeps no offset.
50
+ const parsed = DateTime.fromISO(value, { zone: 'UTC' });
51
+ if (!CLOCK.test(value) || !parsed.isValid || parsed.toFormat("yyyy-MM-dd'T'HH:mm:ss") !== value) {
52
+ throw new SchemaError(PROVIDER, `PEC returned an invalid ${key}`);
53
+ }
54
+ return value;
55
+ }
56
+ function list(value, what) {
57
+ if (value === null || value === undefined)
58
+ return [];
59
+ if (!Array.isArray(value) || value.length > MAX_ROWS)
60
+ throw new SchemaError(PROVIDER, `PEC returned invalid ${what}`);
61
+ return value;
62
+ }
63
+ /** A PEC department: its name, its town without the district PEC adds in brackets, its address and its coordinates. */
64
+ function department(value) {
65
+ if (value === null || value === undefined)
66
+ return null;
67
+ if (!isRecord(value))
68
+ throw new SchemaError(PROVIDER, 'PEC returned an invalid department');
69
+ const town = isRecord(value.Town) ? text(value.Town, 'Town', 80).replace(/\s*\([^()]*\)$/u, '') : '';
70
+ const address = list(value.Addresses, 'department addresses')
71
+ .map((row) => (isRecord(row) && isRecord(row.address) ? row.address : null))
72
+ .find((row) => row !== null);
73
+ const coordinates = address && isRecord(address.Coordinates) ? address.Coordinates : null;
74
+ return {
75
+ name: text(value, 'DepartmentName', 120),
76
+ town,
77
+ address: address ? text(address, 'RawAddress', 200) : '',
78
+ point: coordinates ? eventPoint(coordinates.latitude, coordinates.longitude) : null,
79
+ };
80
+ }
81
+ function statusId(row) {
82
+ return Number.isSafeInteger(row.Id) && row.Id >= 0 ? row.Id : undefined;
83
+ }
84
+ /** A scan at its wall clock; a clock at the last second of a day keeps only the day. */
85
+ function scan(clock, description, place) {
86
+ const staged = pecomStage(description);
87
+ return { clock, event: {
88
+ local_time: clock.endsWith(END_OF_DAY) ? clock.slice(0, 10) : clock,
89
+ ...(place.location ? { location: place.location } : {}),
90
+ description,
91
+ ...(place.location && place.point ? { point: place.point } : {}),
92
+ ...(staged ? { stage: staged.stage, stage_source: staged.source } : {}),
93
+ } };
94
+ }
95
+ /**
96
+ * The cargo's dated statuses. A status without an actual clock is one the
97
+ * cargo has not reached; the arrival's planned or corrected date is then the
98
+ * forecast the tracker shows.
99
+ */
100
+ function statuses(cargo, source, target) {
101
+ const dated = [];
102
+ const arrival = { reached: false };
103
+ for (const row of list(cargo.statuses, 'statuses')) {
104
+ if (!isRecord(row) || !isRecord(row.clientStatus))
105
+ throw new SchemaError(PROVIDER, 'PEC returned an invalid status');
106
+ const id = statusId(row.clientStatus);
107
+ const local = clock(row, 'clientStatusActualDateTime');
108
+ if (id === ARRIVED) {
109
+ arrival.reached ||= Boolean(local);
110
+ const forecast = clock(row, 'clientStatusSpecifiedDate') ?? clock(row, 'clientStatusPlannedDate');
111
+ if (forecast)
112
+ arrival.forecast = forecast.slice(0, 10);
113
+ }
114
+ if (!local)
115
+ continue;
116
+ const description = text(row.clientStatus, 'ClientStatus', 120);
117
+ if (!description)
118
+ throw new SchemaError(PROVIDER, 'PEC returned a status without wording');
119
+ const at = id !== undefined && AT_SOURCE.has(id) ? source : id !== undefined && AT_TARGET.has(id) ? target : null;
120
+ dated.push(scan(local, description, { location: at?.town, point: at?.point }));
121
+ }
122
+ return { rows: dated, arrival };
123
+ }
124
+ /**
125
+ * The transit rows the tracker lists under "В пути": a status and the terminal
126
+ * it concerns, worded as the page words them ("Отправлен на терминал выдачи
127
+ * Раменское"). An arrival happens at its terminal; a dispatch only names where
128
+ * the cargo goes. The arrival at the receiving terminal repeats the main
129
+ * status, so the page leaves it out.
130
+ */
131
+ function transit(cargo, arrived) {
132
+ const dated = [];
133
+ for (const row of list(cargo.detailsCargoStatus, 'transit rows')) {
134
+ if (!isRecord(row))
135
+ throw new SchemaError(PROVIDER, 'PEC returned an invalid transit row');
136
+ const local = clock(row, 'initDate');
137
+ const status = text(row, 'statusName', 60);
138
+ if (!local || !status)
139
+ continue;
140
+ const kind = text(row, 'targetWarehouseType', 60);
141
+ const terminal = text(row, 'targetWarehouseName', 120);
142
+ if (status === 'Прибыл' && kind === 'Терминал выдачи' && arrived)
143
+ continue;
144
+ const kindText = kind.toLowerCase();
145
+ const description = [status, kindText ? `${kindText === 'пункт выдачи' ? 'в' : 'на'} ${kindText}` : '', terminal].filter(Boolean).join(' ');
146
+ dated.push(scan(local, description, { location: status === 'Прибыл' ? terminal : undefined }));
147
+ }
148
+ return dated;
149
+ }
150
+ /**
151
+ * The reply of `LK.OCR.Get` for one cargo code, the call PEC's tracking page
152
+ * makes for a cargo's details. PEC answers a code it does not know with a
153
+ * JSON-RPC error. The cargo must carry the whole code asked. Its current
154
+ * status decides the stage; its dated statuses and transit rows are the
155
+ * history. Sender and recipient details in the reply are never read.
156
+ */
157
+ export function parsePecom(payload, raw) {
158
+ const number = normalizePecomNumber(raw);
159
+ if (!isRecord(payload))
160
+ throw new SchemaError(PROVIDER, 'PEC returned an invalid envelope');
161
+ if (payload.error !== undefined && payload.error !== null) {
162
+ const error = isRecord(payload.error) ? payload.error : {};
163
+ if (error.code === NOT_FOUND && NOT_FOUND_WORDING.test(clean(error.message, 300)))
164
+ throw new NotFoundError(PROVIDER);
165
+ // JSON-RPC's own errors, such as an unknown method or invalid params, mean the request changed.
166
+ if (typeof error.code === 'number' && error.code <= -32000 && error.code >= -32768) {
167
+ throw new SchemaError(PROVIDER, 'PEC refused the tracking request');
168
+ }
169
+ throw new IndeterminateError(PROVIDER, 'PEC did not complete the lookup');
170
+ }
171
+ const data = isRecord(payload.result) ? payload.result.data : undefined;
172
+ if (!isRecord(data) || !isRecord(data.cargo))
173
+ throw new SchemaError(PROVIDER, 'PEC returned a reply without the cargo');
174
+ const cargo = data.cargo;
175
+ const codes = [text(cargo, 'index', 40), text(cargo, 'barcode', 40)].filter(Boolean);
176
+ if (!codes.length)
177
+ throw new SchemaError(PROVIDER, 'PEC returned a cargo without its code');
178
+ if (!codes.includes(number))
179
+ throw new IndeterminateError(PROVIDER, 'PEC answered for another cargo');
180
+ const source = department(cargo.sourceDepartment);
181
+ const target = department(cargo.targetDepartment);
182
+ const { rows: dated, arrival } = statuses(cargo, source, target);
183
+ // Newest first; of two rows at one clock, the later in the reply is newer.
184
+ const events = [...dated, ...transit(cargo, arrival.reached)]
185
+ .map((row, index) => ({ ...row, index }))
186
+ .sort((left, right) => right.clock.localeCompare(left.clock) || right.index - left.index)
187
+ .map(({ event }) => event);
188
+ const current = isRecord(cargo.currentStatus) ? text(cargo.currentStatus, 'ClientStatus', 120) : '';
189
+ if (!current && !events.length)
190
+ throw new NoHistoryError(PROVIDER);
191
+ const newest = events[0];
192
+ const summary = current ? pecomStage(current) : null;
193
+ const scanned = events.find((event) => event.stage);
194
+ const stage = (summary?.stage ?? scanned?.stage);
195
+ const stageSource = summary ? summary.source : scanned?.stage_source;
196
+ // A cargo brought to the door has a delivery order, or a status that says so.
197
+ const door = isRecord(cargo.cargoDelivery) || stage === 'out_for_delivery'
198
+ || [current, ...events.map((event) => event.description)].some((wording) => /^доставлен получателю$/iu.test(wording ?? ''));
199
+ const pickup = !door && target ? [target.name, target.address].filter(Boolean).join('\n') : '';
200
+ const expected = !arrival.reached && (!stage || BEFORE_ARRIVAL.has(stage)) ? arrival.forecast ?? null : null;
201
+ const weight = typeof cargo.totalWeight === 'number' && Number.isFinite(cargo.totalWeight) && cargo.totalWeight > 0 ? cargo.totalWeight : null;
202
+ return {
203
+ status: stage ? languageStageStatus(stage) : 'unknown',
204
+ ...(stage ? { current_stage: stage, current_stage_source: stageSource ?? 'carrier_map' } : {}),
205
+ last_status_text: current || newest.description,
206
+ ...(events.length ? {} : { summary_only: true }),
207
+ last_update: null,
208
+ ...(newest ? { last_update_local: newest.local_time } : {}),
209
+ expected_delivery: expected,
210
+ ...(pickup ? { pickup_point: pickup } : {}),
211
+ ...(weight !== null ? { weight_kg: weight } : {}),
212
+ events,
213
+ };
214
+ }
@@ -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 the map gives a status's wording, if it knows it. */
4
+ export declare function pecomMappedStage(wording: string): Stage | undefined;
5
+ /** A status's stage from the map, else from the shared wording rules; wording neither knows stays without one. */
6
+ export declare function pecomStage(wording: string): ClassifiedWording | null;
7
+ export declare const statusMap: CarrierStatusMap;