hh-shipments 0.3.25 → 0.3.27

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/package.json CHANGED
@@ -1,5 +1,6 @@
1
1
  {
2
2
  "dependencies": {
3
+ "@zxing/library": "^0.23.0",
3
4
  "bcryptjs": "^2.4.3",
4
5
  "cookie-parser": "^1.4.6",
5
6
  "express": "^4.21.2",
@@ -15,10 +16,10 @@
15
16
  "name": "hh-shipments",
16
17
  "scripts": {
17
18
  "start": "node server.js",
18
- "test": "node test/run-tests.js && node test/run-carriers-tests.js"
19
+ "test": "node test/run-extract-tests.js && node test/run-tests.js && node test/run-carriers-tests.js"
19
20
  },
20
21
  "type": "commonjs",
21
- "version": "0.3.25",
22
+ "version": "0.3.27",
22
23
  "bin": {
23
24
  "hh-shipments": "server.js"
24
25
  },
package/public/app.js CHANGED
@@ -381,15 +381,17 @@ async function fetchTimeout(url, opts = {}, ms = 60000) {
381
381
  }
382
382
 
383
383
  // ---- Barcode-first decoding (ZXing) ----
384
- // A decoded barcode is checksum-verified (Code128 mod-103), so it is
385
- // essentially never wrong — far more reliable than OCR text for labels.
384
+ // Bundled locally at /vendor/zxing.min.js so a CDN outage can never
385
+ // silently kill it. A decoded barcode is checksum-verified (Code128
386
+ // mod-103), so it is essentially never wrong — far more reliable than
387
+ // OCR text for labels.
386
388
  let zxingPromise = null;
387
389
  function loadZxing() {
388
390
  if (window.ZXing) return Promise.resolve();
389
391
  if (!zxingPromise) {
390
392
  zxingPromise = new Promise((res, rej) => {
391
393
  const s = document.createElement('script');
392
- s.src = 'https://cdn.jsdelivr.net/npm/@zxing/library@0.21.3/umd/index.min.js';
394
+ s.src = '/vendor/zxing.min.js';
393
395
  s.onload = res;
394
396
  s.onerror = () => rej(new Error('barcode reader failed to load'));
395
397
  document.head.appendChild(s);
@@ -398,13 +400,15 @@ function loadZxing() {
398
400
  return zxingPromise;
399
401
  }
400
402
 
401
- // OCR just the top strip of a label (sender block) for the seller name.
403
+ // OCR the top strip of a label (sender block) for the seller name.
402
404
  // Works from the ORIGINAL full-resolution image, upscaled — small text
403
- // reads far better than on the shrunk copy. Returns text or null.
405
+ // reads far better than on the shrunk copy. Top 45%: covers the sender
406
+ // block on USPS labels (~35-40%) as well as UPS/FedEx (top). Returns text
407
+ // or null.
404
408
  async function ocrTopStrip(origFile, statusEl) {
405
409
  try {
406
410
  const bmp = await createImageBitmap(origFile);
407
- const sw = bmp.width, sh = Math.max(60, Math.round(bmp.height * 0.35));
411
+ const sw = bmp.width, sh = Math.max(60, Math.round(bmp.height * 0.45));
408
412
  const targetW = 1400, scale = targetW / sw;
409
413
  const canvas = document.createElement('canvas');
410
414
  canvas.width = targetW;
@@ -424,8 +428,13 @@ async function ocrTopStrip(origFile, statusEl) {
424
428
  function strictTracking(s) {
425
429
  s = String(s || '').toUpperCase().replace(/[\s-]/g, '');
426
430
  if (/^1Z[0-9A-Z]{16}$/.test(s)) return s; // UPS
427
- if (/^9\d{19,21}$/.test(s)) return s; // USPS
428
- if (/^(\d{12}|\d{15}|\d{20})$/.test(s)) return s; // FedEx
431
+ // IMpb barcode: strip the routing prefix, return the tracking number.
432
+ // The routing portion alone is never a shipment.
433
+ var impb = (window.HHExtract && HHExtract.parseImpb) ? HHExtract.parseImpb(s) : null;
434
+ if (impb) return impb;
435
+ if (/^9[1-5]\d{18,20}$/.test(s)) return s; // USPS
436
+ if (/^420\d{9}$/.test(s)) return null; // IMpb routing — never a shipment
437
+ if (/^(\d{12}|\d{15}|\d{20})$/.test(s)) return s; // FedEx
429
438
  if (/^\d{10,11}$/.test(s)) return s; // DHL
430
439
  return null;
431
440
  }
@@ -530,9 +539,14 @@ async function handlePastedImageFile(f) {
530
539
  if (r && !r.added.length && !r.duplicates.length && !r.needs_review.some((c) => c.carrier && c.carrier !== 'unknown')) showOcrRead(target, text);
531
540
  return;
532
541
  }
533
- // 2) Fallback: OCR the printed text
542
+ // 2) Fallback: OCR the printed text (+ the sender strip for the name,
543
+ // in parallel — the number crop usually excludes the sender block)
534
544
  if (live) live.textContent = '📖 Reading screenshot…';
535
- text = await ocrFile(f, $('ocr-status-paste'));
545
+ const [ocrText, topTextFb] = await Promise.all([
546
+ ocrFile(f, $('ocr-status-paste')),
547
+ ocrTopStrip(orig, $('ocr-status-paste')),
548
+ ]);
549
+ text = ocrText;
536
550
  if (live) live.textContent = '⬆️ Uploading…';
537
551
  const fd = new FormData();
538
552
  fd.append('image', f);
@@ -542,7 +556,7 @@ async function handlePastedImageFile(f) {
542
556
  if (!up.ok) throw new Error('upload failed');
543
557
  const upId2 = await up.json().then((j) => j.id).catch(() => null);
544
558
  if (live) live.textContent = '🔍 Finding tracking number…';
545
- const r = await runQuick(text, target);
559
+ const r = await runQuick(text, target, topTextFb ? { labelText: topTextFb } : undefined);
546
560
  // Paste flow already handled this image — don't leave it nagging in the review queue.
547
561
  if (upId2) api.patch('/api/intake/' + upId2, { state: 'reviewed' }).catch(() => {});
548
562
  if (looksLikeAppScreenshot(text)) target.insertAdjacentHTML('afterbegin', '<p class="warn">⚠️ This looks like a screenshot of the app itself — paste the label photo directly for best results.</p>');
package/public/extract.js CHANGED
@@ -9,8 +9,8 @@
9
9
  var PATTERNS = [
10
10
  // UPS: 1Z + 16 alphanumerics
11
11
  { carrier: 'ups', confidence: 'high', re: /\b(1Z[0-9A-Z]{16})\b/gi },
12
- // USPS: 20-22 digits starting 92-95 (9400..., 9205..., etc.)
13
- { carrier: 'usps', confidence: 'high', re: /\b(9[2-5]\d{18,20})\b/g },
12
+ // USPS: 20-22 digits starting 91-95 (9400..., 9305..., 9205..., 9101..., etc.)
13
+ { carrier: 'usps', confidence: 'high', re: /\b(9[1-5]\d{18,20})\b/g },
14
14
  // USPS S10 international: 2 letters + 9 digits + 2 letters (ends US = USPS)
15
15
  { carrier: 'usps', confidence: 'medium', re: /\b([A-Z]{2}\d{9}US)\b/g },
16
16
  // FedEx SmartPost / Ground 22-digit starting 96
@@ -95,9 +95,14 @@
95
95
  anchorZones(text).forEach(function (z) {
96
96
  runPatterns(z.text, found, seen, z.carrier);
97
97
  spacedUpsIn(z.text, found, seen, 'high');
98
+ spacedDigitGroupsIn(z.text, found, seen, 'high');
98
99
  });
99
100
  // 1) Whole-text strict patterns
100
101
  runPatterns(text, found, seen, false);
102
+ // 1b) Spaced digit groups: labels print "9305 5110 4390 0011 2062 42"
103
+ // with spaces, which strict PATTERNS cannot match. Without this pass a
104
+ // perfectly-read number is silently dropped.
105
+ spacedDigitGroupsIn(text, found, seen, 'medium');
101
106
  // 2) OCR-tolerant recovery pass
102
107
  extractOcrTolerant(text, found, seen);
103
108
  var rank = { high: 0, medium: 1, low: 2 };
@@ -142,6 +147,9 @@
142
147
  var num = normalize(m[1]);
143
148
  if (seen[num]) continue;
144
149
  seen[num] = true;
150
+ // Never accept an IMpb routing prefix (420 + 9 digits) as a FedEx
151
+ // number — it is postal routing, not a shipment.
152
+ if (p.carrier === 'fedex' && /^420\d{9}$/.test(num)) continue;
145
153
  // Context boost: carrier word near the number, or a hot-zone anchor
146
154
  // naming this carrier (a label's "UPS GROUND" line means the number
147
155
  // under it really is UPS).
@@ -162,12 +170,61 @@
162
170
  function isValidFormat(number, carrier) {
163
171
  var n = normalize(number);
164
172
  if (carrier === 'ups') return /^1Z[0-9A-Z]{16}$/.test(n);
165
- if (carrier === 'usps') return /^9[2-5]\d{18,20}$/.test(n) || /^[A-Z]{2}\d{9}US$/.test(n);
166
- if (carrier === 'fedex') return /^(96\d{20}|\d{12}|\d{15}|\d{20})$/.test(n);
173
+ if (carrier === 'usps') return /^9[1-5]\d{18,20}$/.test(n) || /^[A-Z]{2}\d{9}US$/.test(n);
174
+ // FedEx: never accept an IMpb routing prefix (420 + 9 digits) — it is
175
+ // postal routing, not a shipment number.
176
+ if (carrier === 'fedex') return /^(96\d{20}|\d{12}|\d{15}|\d{20})$/.test(n) && !/^420\d{9}$/.test(n);
167
177
  if (carrier === 'dhl') return /^\d{10,11}$/.test(n) || /^[A-Z]{2,4}\d{10,20}$/.test(n);
168
178
  return false;
169
179
  }
170
180
 
181
+ // Intelligent Mail package barcode: 420 + routing digits + USPS tracking,
182
+ // e.g. 420078742956 + 9305511043900011206242 (34 digits). The full barcode
183
+ // is NOT the tracking number — return the trailing tracking number. The
184
+ // routing portion must never pass as a shipment number.
185
+ function parseImpb(s) {
186
+ var num = normalize(s);
187
+ if (!/^420\d{23,31}$/.test(num)) return null; // 26–34 digits total
188
+ var m = /(9[1-5]\d{18,20})$/.exec(num);
189
+ return m ? m[1] : null;
190
+ }
191
+
192
+ // A spaced/dashed digit run is only plausible as a tracking number when
193
+ // every group has 2+ digits — this rejects ZIP+4 glued to a nearby lone
194
+ // digit ("07874-2956 1 lb"), phone fragments ("1-800-555-1234"), etc.
195
+ function validSpacedGroups(raw) {
196
+ var groups = String(raw).split(/[\s-]+/);
197
+ if (groups.length < 2) return true; // contiguous — decided elsewhere
198
+ for (var i = 0; i < groups.length; i++) if (groups[i].length < 2) return false;
199
+ return true;
200
+ }
201
+
202
+ // Digit groups split by spaces/dashes: "9305 5110 4390 0011 2062 42".
203
+ // Strict PATTERNS only match contiguous runs, so this pass exists for the
204
+ // standard label printing format. Only fires when the raw match actually
205
+ // contains a separator (contiguous runs are already covered by PATTERNS).
206
+ // Joined candidates must validate against a carrier format; IMpb barcodes
207
+ // yield their tracking number, never the routing.
208
+ function spacedDigitGroupsIn(text, found, seen, conf) {
209
+ var re = /\b\d(?:[\s-]?\d){9,33}\b/g, m;
210
+ while ((m = re.exec(text)) !== null) {
211
+ if (!/[\s-]/.test(m[0])) continue;
212
+ if (!validSpacedGroups(m[0])) continue;
213
+ var num = normalize(m[0]);
214
+ if (!num || seen[num]) continue;
215
+ var impb = parseImpb(num);
216
+ if (impb) {
217
+ seen[num] = true;
218
+ if (!seen[impb]) { seen[impb] = true; found.push({ number: impb, carrier: 'usps', confidence: conf }); }
219
+ continue;
220
+ }
221
+ var carrier = guessCarrier(num);
222
+ if (carrier === 'unknown') { seen[num] = true; continue; }
223
+ seen[num] = true;
224
+ found.push({ number: num, carrier: carrier, confidence: conf });
225
+ }
226
+ }
227
+
171
228
  function guessCarrier(num) {
172
229
  var carriers = ['ups', 'usps', 'fedex', 'dhl'];
173
230
  for (var i = 0; i < carriers.length; i++) if (isValidFormat(num, carriers[i])) return carriers[i];
@@ -194,13 +251,20 @@
194
251
  // a) UPS number split by spaces/dashes (whole-text fallback; the anchor
195
252
  // pass already tried the hot zones at high confidence)
196
253
  spacedUpsIn(text, found, seen, 'medium');
197
- // b) long digit-like runs with OCR confusions -> fix -> re-match digit formats
198
- var runRe = /[0-9OILSBoilszb]{10,24}/g, run;
254
+ // b) long digit-like runs with OCR confusions -> fix -> re-match digit formats.
255
+ // Space-aware: OCR often reads "9305 51O0 ..." with both mangled chars
256
+ // AND spaces, so runs may contain separators. Runs up to 34 chars so a
257
+ // full 34-digit IMpb barcode is tested whole (parseImpb) instead of
258
+ // being split into chunks that false-positive as DHL/FedEx.
259
+ var runRe = /[0-9OILSBoilszb](?:[\s-]?[0-9OILSBoilszb]){9,33}/g, run;
199
260
  while ((run = runRe.exec(text)) !== null) {
261
+ if (/[\s-]/.test(run[0]) && !validSpacedGroups(run[0])) continue;
200
262
  var fixed = normalize(ocrDigitFix(run[0]));
201
- if (/^9[2-5]\d{18,20}$/.test(fixed)) push(fixed, 'usps', 'medium');
263
+ var impbFixed = parseImpb(fixed);
264
+ if (impbFixed) { push(impbFixed, 'usps', 'medium'); continue; }
265
+ if (/^9[1-5]\d{18,20}$/.test(fixed)) push(fixed, 'usps', 'medium');
202
266
  else if (/^96\d{20}$/.test(fixed)) push(fixed, 'fedex', 'medium');
203
- else if (/^(\d{12}|\d{15}|\d{20})$/.test(fixed)) push(fixed, 'fedex', 'medium');
267
+ else if (/^(\d{12}|\d{15}|\d{20})$/.test(fixed) && !/^420\d{9}$/.test(fixed)) push(fixed, 'fedex', 'medium');
204
268
  else if (/^\d{11}$/.test(fixed)) push(fixed, 'dhl', 'medium');
205
269
  else if (/^\d{10}$/.test(fixed)) push(fixed, 'dhl', 'low');
206
270
  }
@@ -214,6 +278,7 @@
214
278
  });
215
279
  tokens.sort(function (a, b) { return b.length - a.length; });
216
280
  tokens.slice(0, 3).forEach(function (t) {
281
+ if (/^420\d{9}$/.test(t)) return; // IMpb routing — never a shipment
217
282
  // UPS "1Z" misread as "12"/"IZ" in a joined (space-free) token
218
283
  var fixed = repairUpsZ(t);
219
284
  if (fixed) { push(fixed, 'ups', 'medium'); return; }
@@ -225,7 +290,7 @@
225
290
  });
226
291
  }
227
292
 
228
- var api = { extractTrackingNumbers: extractTrackingNumbers, extractContext: extractContext, normalize: normalize, isValidFormat: isValidFormat };
293
+ var api = { extractTrackingNumbers: extractTrackingNumbers, extractContext: extractContext, normalize: normalize, isValidFormat: isValidFormat, parseImpb: parseImpb };
229
294
  if (typeof module !== 'undefined' && module.exports) module.exports = api;
230
295
  globalThis.HHExtract = api;
231
296
  })();
package/public/sw.js CHANGED
@@ -2,7 +2,7 @@
2
2
  CACHE name includes the app version (injected by the server), so every
3
3
  deploy installs a fresh shell and deletes the old one. */
4
4
  const CACHE = 'hh-ship-__APP_VERSION__';
5
- const SHELL = ['/', '/index.html', '/styles.css', '/app.js', '/extract.js', '/manifest.webmanifest'];
5
+ const SHELL = ['/', '/index.html', '/styles.css', '/app.js', '/extract.js', '/vendor/zxing.min.js', '/manifest.webmanifest'];
6
6
 
7
7
  self.addEventListener('install', (e) => {
8
8
  e.waitUntil(caches.open(CACHE).then((c) => c.addAll(SHELL)).then(() => self.skipWaiting()));