Files
RSSHub/lib/routes/ups/track.ts
T
Tony cfcdc34e1f refactor: replace playwright with patchright (#21976)
* refactor: use patchwright

* refactor: migrate setRequestInterception and waitUntil

* fix: overwrite ua

* refactor: drop puppeteer cookie/requestfinished shims

Migrate page.cookies/setCookie and browser.cookies/setCookie call sites to the native context APIs (page.context().cookies/addCookies), rewrite requestfinished handlers to await request.response() instead of consuming the synchronous puppeteer-shaped payload, and remove the now-redundant browser.close context-cleanup wrapper. Playwright already handles all of these natively; the shims existed only for the puppeteer -> playwright migration.

* refactor: remove page.authenticate, page.setUserAgent,  browser.newPage(), browser.userAgent() shims

update cookie utility tests

* refactor: replace browser instance with context in Playwright usage across multiple routes

- Updated all instances of `browser` to `context` in Playwright-related functions for consistency and improved resource management.
- Ensured proper closure of context after operations to prevent memory leaks.
- Adjusted request interception methods to utilize the new context variable.

* fix: direct type import

* refactor: remove Puppeteer compatibility layers and unify page handling with Playwright

* fix: test case

* chore: bump patchright to v1.60.0

* chore: pin patchright to 1.59.1

nft can't resolve browser.json due to https://github.com/microsoft/playwright/pull/40093

* chore: pin to node 24.15 for playwright

browser install on node 24.16 stucks due to https://github.com/microsoft/playwright/issues/40724

* fix: update patchright and patchright-core to version 1.60.2 and adjust minify-docker.js for compatibility

* fix: import BrowserContext from patchright
2026-06-07 02:43:20 +08:00

114 lines
3.3 KiB
TypeScript

import { load } from 'cheerio';
import type { DataItem, Route } from '@/types';
import { parseDate } from '@/utils/parse-date';
import playwright from '@/utils/playwright';
export const route: Route = {
path: '/track/:trackingNumber',
categories: ['other'],
example: '/ups/track/1Z78R6790470567520',
parameters: { trackingNumber: 'The UPS tracking number (e.g., 1Z78R6790470567520).' },
features: {
requireConfig: false,
requirePuppeteer: false,
antiCrawler: false,
supportBT: false,
supportPodcast: false,
supportScihub: false,
},
name: 'Tracking',
maintainers: ['Aquabet'],
handler,
};
async function handler(ctx) {
const { trackingNumber } = ctx.req.param();
const url = `https://www.ups.com/track?loc=en_US&tracknum=${trackingNumber}`;
const context = await playwright();
const page = await context.newPage();
// skip loading images, stylesheets, and fonts
await page.route('**/*', (route) => {
if (['image', 'stylesheet', 'font', 'ping', 'fetch'].includes(route.request().resourceType())) {
route.abort();
} else {
route.continue();
}
});
await page.goto(url, { waitUntil: 'domcontentloaded' });
const viewDetailsButton = '#st_App_View_Details';
try {
await page.waitForSelector(viewDetailsButton);
await page.click(viewDetailsButton);
} catch {
return {
title: `UPS Tracking - ${trackingNumber}`,
link: url,
item: [],
};
}
await page.waitForSelector('tr[id^="stApp_activitydetails_row"]');
const content = await page.content();
await context.close();
const $ = load(content);
const rows = $('tr[id^="stApp_activitydetails_row"]');
const items: DataItem[] = rows.toArray().map((el, i) => {
const dateTimeRaw = $(el).find(`#stApp_activitiesdateTime${i}`).text() || 'Not Provided';
const dateTimeStr = dateTimeRaw
.trim()
.replace(/(\d+\/\d+\/\d{4})(\d+:\d+\s[AP]\.?M\.?)/, '$1 $2')
.replaceAll('P.M.', 'PM')
.replaceAll('A.M.', 'AM');
const pubDate = parseDate(dateTimeStr);
const activityCellText = $(el)
.find(`#stApp_milestoneActivityLocation${i}`)
.text()
.trim()
.replaceAll(/\s*\n\s*/g, '\n');
const lines = activityCellText
.split('\n')
.map((l) => l.trim())
.filter(Boolean);
// Situation 0: There is text within the strong element
// Example: ["Delivered", "DELIVERED", "REDMOND, WA, United States"]
// Situation 1: strong is empty => the first line in lines is the status
// Example: ["Departed from Facility", "Seattle, WA, United States"]
const status = lines[0];
const location = lines.at(-1) || '';
const item: DataItem = {
title: status,
link: url,
guid: `${trackingNumber}-${i}`,
description: `
Status: ${status} <br>
Location: ${location} <br>
Date and Time: ${dateTimeStr}
`,
pubDate,
};
return item;
});
return {
title: `UPS Tracking - ${trackingNumber}`,
link: url,
item: items,
};
}