diff --git a/README.md b/README.md new file mode 100644 index 0000000..df718ab --- /dev/null +++ b/README.md @@ -0,0 +1,57 @@ +# Booksorter + +A small local web app for labelling a personal library with Library of Congress call numbers. Hold a book's barcode up to a laptop webcam (or type the ISBN), and Booksorter looks up the call number from the Library of Congress and Open Library, builds a spine label, and prints cards on Avery 5388 sheets (three 3 x 5 inch cards per sheet). Everything runs on your own machine; the only outside traffic is the book lookups made by the server. + +## Install and run + +``` +npm install +npm start +``` + +`npm start` builds the web app into `dist/web` and serves it at http://localhost:4321 (only reachable from this computer). Set `PORT` to use another port. If the port is taken, the server says so and exits. + +Requires a recent Node (the server runs TypeScript directly). + +## Scanning + +Use the **Scan** tab. Every way of adding a book ends up in the same session list, where a row goes from "Looking up" to "Ready" (a call number was found) or "Needs attention". + +- **Camera**: click *Start camera*, allow access, and hold the barcode (the one with 978 or 979 under it, usually on the back cover) steady in view. A beep means it was read. Reading the same book twice is recognised and not added again. +- **Typed ISBN**: the ISBN box is always focused. Type or paste 10 or 13 digits and press Enter. A USB barcode scanner works the same way, since it types the digits and presses Enter. +- **Search by title and author**: for books with no barcode. Pick the matching result. +- **Enter LCCN**: if the book's copyright page prints a Library of Congress Control Number. +- **Enter by hand**: title, authors, and optionally a call number you already know. + +Books marked *Needs attention* appear on the **Print queue** tab, where you can retry the lookup, edit the details (including typing a call number), or delete them. Call numbers marked approximate were derived from a Dewey number rather than found in the Library of Congress catalog; check those. + +## Printing on Avery 5388 + +On the **Print queue** tab, choose which of the three positions on the sheet the first card should use (handy for a partly used sheet) and click *Make PDF*. Cards are printed in shelf order. + +1. Open the PDF in your PDF viewer and print at **Actual size / 100%** (never "Fit to page"). +2. Print **single-sided**, loading the sheet through the **manual feed slot**. +3. When the cards came out correctly, click *Yes, clear these from the queue* so they are not printed twice. + +If the text sits off-centre on the cards, print the **calibration page** (*Printer alignment*, then *Print calibration page*) on plain paper, hold it against a real sheet up to the light, and enter the X and Y offsets in millimetres (limit 10) that bring it into line. Offsets are saved and applied to every later PDF. + +## Where the data lives + +In `data/booksorter.db` (SQLite) in this folder, created on first run. Back it up by copying the file while the server is stopped. Set `BOOKSORTER_DB` to use a different file. + +## Tests + +``` +npm test # unit and server tests +npm run typecheck +``` + +The browser check drives Firefox through the real app. It needs a running server, and it adds, removes and re-adds the test book (ISBN 9781593278281 unless `ISBN` is set), so point the server at a scratch database (`BOOKSORTER_DB=/tmp/scratch.db npm start`) rather than your real one. The first run looks the book up live, which can take a minute: + +``` +npx playwright install firefox # once +npm start # in another terminal +npm run browser-check # or: node scripts/browser-check.ts [url] +``` + +Set `SHOTS=/some/dir` to save screenshots, and `ISBN=` to use a different already-resolved book. It checks that the page loads cleanly and calls only localhost, the tabs render, a typed ISBN is resolved, a generated EAN-13 barcode is decoded by the same wasm detector the camera uses, Firefox's fake camera starts and stops, and the print queue produces a PDF. It uses a fake camera, so it cannot prove that your own webcam reads real barcodes well. diff --git a/package-lock.json b/package-lock.json index e922539..381f6a9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -20,6 +20,7 @@ "devDependencies": { "@types/node": "^26.6.6", "esbuild": "^0.28.2", + "playwright": "^1.65.1", "typescript": "^7.0.2" } }, @@ -1034,6 +1035,35 @@ "tslib": "^1.11.1" } }, + "node_modules/playwright": { + "version": "1.65.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.1.tgz", + "integrity": "sha512-vJ1FuoOrNwOKHUIVEvSt3jT1L+wjjDpwhwIstKtfvTh8XIG4FG4bIFuvNdMxi81LGfAhUgUZleVFaOLY4RIUUw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.65.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.65.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.1.tgz", + "integrity": "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/preact": { "version": "11.2.0", "resolved": "https://registry.npmjs.org/preact/-/preact-11.2.0.tgz", diff --git a/package.json b/package.json index 6faa6b0..9d3474a 100644 --- a/package.json +++ b/package.json @@ -6,6 +6,7 @@ "scripts": { "test": "node --test \"src/**/*.test.ts\"", "typecheck": "tsc --noEmit", + "browser-check": "node scripts/browser-check.ts", "build": "node scripts/build-web.ts", "start": "npm run build && node src/server/main.ts" }, @@ -22,6 +23,7 @@ "devDependencies": { "@types/node": "^26.6.6", "esbuild": "^0.28.2", + "playwright": "^1.65.1", "typescript": "^7.0.2" } } diff --git a/scripts/browser-check.ts b/scripts/browser-check.ts new file mode 100644 index 0000000..1d2a987 --- /dev/null +++ b/scripts/browser-check.ts @@ -0,0 +1,155 @@ +// Drives Firefox against a running Booksorter server. Usage: node scripts/browser-check.ts [baseUrl] +// Env: SHOTS= to save screenshots, ISBN= to use another already-resolved ISBN. +import { firefox } from 'playwright'; +import { build } from 'esbuild'; +import { mkdirSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +const base = process.argv[2] ?? 'http://localhost:4321'; +const shots = process.env.SHOTS; +if (shots) mkdirSync(shots, { recursive: true }); +const ISBN = process.env.ISBN ?? '9781593278281'; +const root = fileURLToPath(new URL('..', import.meta.url)); + +const failures: string[] = []; +const check = (name: string, ok: boolean, detail = '') => { + console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail ? ' ' + detail : ''}`); + if (!ok) failures.push(name); +}; + +// EAN-13 module pattern (95 modules) for a 13-digit string. +function ean13Modules(code: string): string { + const L = ['0001101', '0011001', '0010011', '0111101', '0100011', '0110001', '0101111', '0111011', '0110111', '0001011']; + const R = L.map((p) => [...p].map((b) => (b === '0' ? '1' : '0')).join('')); + const G = R.map((p) => [...p].reverse().join('')); + const parity = ['LLLLLL', 'LLGLGG', 'LLGGLG', 'LLGGGL', 'LGLLGG', 'LGGLLG', 'LGGGLL', 'LGLGLG', 'LGLGGL', 'LGGLGL']; + const d = [...code].map(Number); + let out = '101'; + for (let i = 0; i < 6; i++) out += parity[d[0]][i] === 'L' ? L[d[i + 1]] : G[d[i + 1]]; + out += '01010'; + for (let i = 7; i < 13; i++) out += R[d[i]]; + return out + '101'; +} + +// Bundle scanner.ts (the production module) so the page can call its detector. +const bundled = await build({ + stdin: { contents: "export { makeDetector } from './src/web/scanner.ts';", resolveDir: root, loader: 'ts' }, + bundle: true, format: 'esm', write: false, target: 'es2022', logLevel: 'silent', +}); +const scannerJs = bundled.outputFiles[0].text.replaceAll('https://fastly.jsdelivr.net/npm/', '/local-only/'); + +const browser = await firefox.launch({ + headless: true, + firefoxUserPrefs: { 'media.navigator.streams.fake': true, 'media.navigator.permission.disabled': true }, +}); +const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 } }); +const page = await ctx.newPage(); +const consoleErrors: string[] = []; +const badRequests: string[] = []; +const foreign: string[] = []; +page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text()); }); +page.on('pageerror', (e) => consoleErrors.push(String(e))); +page.on('requestfailed', (r) => badRequests.push(`${r.url()} ${r.failure()?.errorText}`)); +page.on('response', (r) => { if (r.status() >= 400) badRequests.push(`${r.url()} ${r.status()}`); }); +page.on('request', (r) => { + const u = new URL(r.url()); + if (!['localhost', '127.0.0.1'].includes(u.hostname) && !['blob:', 'data:', 'about:'].includes(u.protocol)) foreign.push(r.url()); +}); +await page.route('**/__check/scanner.js', (route) => route.fulfill({ contentType: 'text/javascript', body: scannerJs })); + +const shot = async (name: string) => { if (shots) await page.screenshot({ path: `${shots}/${name}.png`, fullPage: true }); }; +const tab = (name: RegExp) => page.getByRole('tab', { name }); + +try { + await page.goto(base, { waitUntil: 'networkidle' }); + await tab(/^Scan/).waitFor(); + check('page loads, Scan tab renders', await page.getByRole('heading', { name: 'This session' }).isVisible()); + await shot('scan-1280'); + await page.setViewportSize({ width: 380, height: 800 }); + await shot('scan-380'); + await page.setViewportSize({ width: 1280, height: 900 }); + + // Typed ISBN. A book already in the catalog would only show "Already in catalog", so remove it first + // (it re-resolves from the lookup cache). Run this against a scratch database, not your real one. + await page.evaluate(async (isbn) => { + const books = await (await fetch('/api/books?filter=all')).json(); + for (const b of books.filter((x: any) => x.isbn13 === isbn)) await fetch(`/api/books/${b.id}`, { method: 'DELETE' }); + }, ISBN); + const box = page.getByLabel('ISBN'); + check('ISBN box is focused on load', await box.evaluate((el) => el === document.activeElement)); + await box.fill(ISBN); + await box.press('Enter'); + await page.locator('.scan .right li.item .chip.ok').first().waitFor({ timeout: 120_000 }); + check('typed ISBN reaches Ready', true, (await page.locator('.scan .right li.item').first().innerText()).replace(/\s+/g, ' ')); + await shot('scan-after-1280'); + + // Barcode path, no camera + const modules = ean13Modules(ISBN); + const decoded = await page.evaluate(async ({ modules, src }) => { + const { makeDetector } = await import(/* @vite-ignore */ src); + const scale = 4, quiet = 12 * scale, h = 120; + const c = document.createElement('canvas'); + c.width = modules.length * scale + quiet * 2; c.height = h; + const g = c.getContext('2d')!; + g.fillStyle = '#fff'; g.fillRect(0, 0, c.width, h); + g.fillStyle = '#000'; + [...modules].forEach((m, i) => { if (m === '1') g.fillRect(quiet + i * scale, 10, scale, h - 20); }); + const found = await makeDetector().detect(c); + return found.map((f: { rawValue: string; format: string }) => `${f.format}:${f.rawValue}`); + }, { modules, src: '/__check/scanner.js' }); + check('wasm barcode decode', decoded.includes(`ean_13:${ISBN}`), JSON.stringify(decoded)); + + // Camera (Firefox fake stream) + await page.getByRole('button', { name: 'Start camera' }).click(); + await page.getByRole('button', { name: 'Stop camera' }).waitFor({ timeout: 15_000 }); + const playing = await page.waitForFunction(() => { + const v = document.querySelector('video') as HTMLVideoElement | null; + return !!v && !!v.srcObject && v.videoWidth > 0 && !v.paused; + }, null, { timeout: 15_000 }).then(() => true, () => false); + check('Start camera plays video', playing); + check('no camera error message', (await page.locator('.scan .warn[role=alert]').count()) === 0); + await page.waitForTimeout(1500); // let the scan loop run on the fake frames + await shot('scan-camera-1280'); + await page.getByRole('button', { name: 'Stop camera' }).click(); + await page.getByRole('button', { name: 'Start camera' }).waitFor(); + const stopped = await page.evaluate(() => !(document.querySelector('video') as HTMLVideoElement).srcObject); + check('Stop camera releases the stream', stopped); + + // Print queue + await tab(/^Print queue/).click(); + await page.getByRole('heading', { name: 'Print queue' }).waitFor(); + const rows = await page.locator('.queue section').first().locator('li.item').count(); + check('Print queue lists resolved books', rows >= 1, `${rows} rows`); + const keys: string[] = await page.evaluate(async () => { + const books = await (await fetch('/api/books?filter=queue')).json(); + return books.filter((b: any) => b.status === 'resolved' && b.callNumber).map((b: any) => b.sortKey ?? '~'); + }); + check('queue order matches shelf (sort key) order', JSON.stringify(keys) === JSON.stringify([...keys].sort()) && rows === keys.length); + await shot('queue-1280'); + const [pdfResp] = await Promise.all([ + page.waitForResponse((r) => r.url().includes('/api/print.pdf')), + page.getByRole('button', { name: 'Make PDF' }).click(), + ]); + const pdfBody = await pdfResp.body(); + check('Make PDF fetches a PDF', pdfResp.status() === 200 && pdfBody.subarray(0, 4).toString() === '%PDF', `${pdfBody.length} bytes`); + check('X-Book-Ids header present', /^\d+(,\d+)*$/.test(pdfResp.headers()['x-book-ids'] ?? '')); + await page.getByText('Did the cards print correctly?').waitFor(); + await shot('queue-confirm-1280'); + await page.getByRole('button', { name: 'Not yet' }).click(); + + // Catalog + await tab(/^Catalog/).click(); + await page.waitForTimeout(500); + check('Catalog tab renders', (await page.locator('main').innerText()).trim().length > 0); + await shot('catalog-1280'); + + check('no console errors', consoleErrors.length === 0, consoleErrors.join(' | ')); + check('no failed requests', badRequests.length === 0, badRequests.join(' | ')); + check('no request left localhost', foreign.length === 0, foreign.join(' | ')); +} catch (e) { + check('script ran to completion', false, String(e)); + await shot('failure').catch(() => {}); +} +await browser.close(); +console.log(failures.length ? `\n${failures.length} check(s) failed` : '\nAll checks passed'); +process.exit(failures.length ? 1 : 0); diff --git a/scripts/gen-lcc-outline.ts b/scripts/gen-lcc-outline.ts new file mode 100644 index 0000000..e2ad8cc --- /dev/null +++ b/scripts/gen-lcc-outline.ts @@ -0,0 +1,118 @@ +// Generates src/shared/lcc-outline.ts from the Library of Congress Classification +// Outline (https://www.loc.gov/catdir/cpso/lcco/), a US government publication. +// Usage: node scripts/gen-lcc-outline.ts [cacheDir] (or env LCC_CACHE_DIR) +// Requires `pdftotext` (poppler). Downloads are cached outside the repo. +import { execFileSync } from 'node:child_process'; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +const INDEX = 'https://www.loc.gov/catdir/cpso/lcco/'; +const UA = 'Mozilla/5.0 (compatible; lcc-outline-generator)'; +const cache = process.argv[2] ?? process.env.LCC_CACHE_DIR ?? join(tmpdir(), 'lcc-outline-cache'); +mkdirSync(cache, { recursive: true }); +const out = new URL('../src/shared/lcc-outline.ts', import.meta.url); + +// Fix-ups applied to names after sentence-casing / extraction. +const MAIN_FIXES: Record = { + 'Auxiliary sciences of history': 'Auxiliary sciences of history', +}; +const SUB_FIXES: Record = { + 'Christian Denominations': 'Christian denominations', +}; + +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); +async function get(url: string, file: string): Promise { + const p = join(cache, file); + if (existsSync(p)) return readFileSync(p); + const res = await fetch(url, { headers: { 'User-Agent': UA } }); + if (!res.ok) throw new Error(`${url}: ${res.status}`); + const buf = Buffer.from(await res.arrayBuffer()); + writeFileSync(p, buf); + await sleep(1000); + return buf; +} + +const clean = (s: string) => s.replace(/\s+/g, ' ').trim(); +function sentenceCase(s: string): string { + const t = clean(s).toLowerCase(); + return t + .replace(/(^|\. )([a-z])/g, (_m, a: string, b: string) => a + b.toUpperCase()) + .replace(/\((general)\)/g, '(General)') + .replace(/\b(europe|asia|africa|australia|new zealand|americas?)\b/g, (w) => w.replace(/\b[a-z]/g, (c) => c.toUpperCase())) + .replace(/,? etc$/, ', etc.'); +} + +// Captions over 120 chars (PT lists many literatures) are cut at the last " - " that fits. +function shorten(s: string): string { + if (s.length <= 120) return s; + const parts = s.split(' - '); + let r = parts[0]!; + for (const p of parts.slice(1)) { + if ((r + ' - ' + p).length > 120) break; + r += ' - ' + p; + } + return r.length <= 120 ? r : r.slice(0, 119).trimEnd() + '…'; +} + +const indexHtml = (await get(INDEX, 'index.html')).toString('utf8'); +const hrefs = [...new Set([...indexHtml.matchAll(/href="([^"]*lcco_[a-z]+\.pdf)"/g)].map((m) => m[1]!))]; +if (hrefs.length < 20) throw new Error(`expected ~20 class PDFs, found ${hrefs.length}`); + +const MAIN: Record = {}; +const SUB: Record = {}; + +for (const href of hrefs) { + const name = href.split('/').pop()!; + const pdf = join(cache, name); + await get(new URL(href, INDEX).href, name); + const lines = execFileSync('pdftotext', ['-layout', pdf, '-'], { encoding: 'utf8', maxBuffer: 1 << 28 }).split('\n'); + + // Title: "CLASS Q - SCIENCE", possibly wrapped onto following lines. + const ti = lines.findIndex((l) => /^\s*CLASS [A-Z](-[A-Z])? - /.test(l)); + if (ti < 0) throw new Error(`no title in ${name}`); + const tm = lines[ti]!.match(/CLASS ([A-Z])(?:-([A-Z]))? - (.*)$/)!; + let title = tm[3]!; + for (let i = ti + 1; i < lines.length && lines[i]!.trim() && !lines[i]!.includes('Click'); i++) title += ' ' + lines[i]!.trim(); + const mainName = sentenceCase(title.replace(/[.,]\s*$/, '')); + for (const c of [tm[1]!, tm[2]].filter(Boolean) as string[]) MAIN[c] = MAIN_FIXES[mainName] ?? mainName; + + // Summary list at top: "Subclass QA Mathematics" with indented wrapped continuations. + for (let i = ti; i < lines.length; i++) { + const l = lines[i]!; + if (/^\s*Subclass [A-Z]+\s*$/.test(l) || /^[A-Z]{1,3}\d/.test(l)) break; // detail section starts + const m = l.match(/^\s*Subclass ([A-Z]{1,3})\s{2,}(\S.*)$/); + if (!m) continue; + let cap = m[2]!; + while (i + 1 < lines.length && /^\s{4,}\S/.test(lines[i + 1]!) && !/^\s*Subclass /.test(lines[i + 1]!)) cap += ' ' + lines[++i]!.trim(); + cap = clean(cap).replace(/\.$/, ''); + SUB[m[1]!] = shorten(SUB_FIXES[cap] ?? cap); + } +} + +const q = (s: string) => JSON.stringify(s); +const rec = (o: Record) => + Object.keys(o).sort().map((k) => ` ${k}: ${q(o[k]!)},`).join('\n'); + +const src = `// GENERATED by scripts/gen-lcc-outline.ts -- do not edit by hand. +// Source: Library of Congress Classification Outline, ${INDEX} +// (a US government publication). Re-run: node scripts/gen-lcc-outline.ts + +export const MAIN_CLASSES: Record = { +${rec(MAIN)} +}; + +export const SUBCLASSES: Record = { +${rec(SUB)} +}; + +export function classNames(letters: string): { className: string | null; subclassName: string | null } { + const l = letters.trim().toUpperCase(); + if (!/^[A-Z]{1,3}$/.test(l)) return { className: null, subclassName: null }; + const className = MAIN_CLASSES[l[0]!] ?? null; + const subclassName = SUBCLASSES[l] ?? (l.length === 3 ? (SUBCLASSES[l.slice(0, 2)] ?? null) : null); + return { className, subclassName }; +} +`; +writeFileSync(out, src); +console.log(`wrote ${Object.keys(MAIN).length} main classes, ${Object.keys(SUB).length} subclasses`); diff --git a/src/server/app.ts b/src/server/app.ts index 87d8dae..5388953 100644 --- a/src/server/app.ts +++ b/src/server/app.ts @@ -5,12 +5,12 @@ import { normalizeIsbn } from '../shared/isbn.ts'; import { formatCallNumber, parseCallNumber, sortKeyOfRaw } from '../shared/callnumber.ts'; import type { Db, Filter, NewBook } from './db.ts'; import type { Jobs, ResolverLike } from './jobs.ts'; +import type { renderCalibrationPdf, renderCardsPdf } from './pdf/render.ts'; +import type { classNames } from '../shared/lcc-outline.ts'; -// Structural matches for pdf/render.ts (Task 4). -export type RenderCardsPdf = (cards: CardData[], opts: Settings & { startPosition: 1 | 2 | 3 }) => Promise; -export type RenderCalibrationPdf = (s: Settings) => Promise; -// Matches classNames in shared/lcc-outline.ts (Task 1b). -export type ClassNames = (letters: string) => { className: string | null; subclassName: string | null }; +export type RenderCardsPdf = typeof renderCardsPdf; +export type RenderCalibrationPdf = typeof renderCalibrationPdf; +export type ClassNames = typeof classNames; export interface EventBus { on(listener: (event: string, data: unknown) => void): () => void; diff --git a/src/server/db.ts b/src/server/db.ts index fc9504d..55cccfb 100644 --- a/src/server/db.ts +++ b/src/server/db.ts @@ -3,8 +3,8 @@ import { mkdirSync } from 'node:fs'; import { dirname } from 'node:path'; import type { Book, Confidence, Settings, Source, Status } from '../shared/types.ts'; -// Structural match for SourceCache in resolve/resolver.ts (Task 2). -export interface SourceCache { get(key: string): string | null; set(key: string, body: string): void } +import type { SourceCache } from './sources/http.ts'; +export type { SourceCache }; export interface NewBook { isbn13?: string | null; lccn?: string | null; title: string; subtitle?: string | null; diff --git a/src/server/jobs.ts b/src/server/jobs.ts index 41d90df..ed098ac 100644 --- a/src/server/jobs.ts +++ b/src/server/jobs.ts @@ -1,11 +1,8 @@ -import type { Book, BookMeta, ResolveInput, Resolution, SearchResult } from '../shared/types.ts'; +import type { Book, BookMeta, ResolveInput } from '../shared/types.ts'; import type { Db } from './db.ts'; +import type { Resolver } from './resolve/resolver.ts'; -// Structural match for Resolver in resolve/resolver.ts (Task 2). -export interface ResolverLike { - resolve(input: ResolveInput, opts?: { onMeta?: (meta: BookMeta) => void }): Promise; - search(title: string, author: string): Promise; -} +export type ResolverLike = Resolver; export interface Jobs { enqueue(id: number): void; resume(): void; idle(): Promise } diff --git a/src/server/resolve/resolver.test.ts b/src/server/resolve/resolver.test.ts index c04db66..c1ca56a 100644 --- a/src/server/resolve/resolver.test.ts +++ b/src/server/resolve/resolver.test.ts @@ -154,3 +154,10 @@ test('search by title and author', async () => { assert.ok(out.length > 0); assert.ok(out[0]!.title); }); + +test('lccn.loc.gov "Record not found" (HTTP 200) is an empty result, not a block page', async () => { + const { createLoc } = await import('../sources/loc.ts'); + const fetchStub = (async () => new Response('Record not found for LCCN: 2003054578.', { status: 200 })) as typeof fetch; + const loc = createLoc({ fetch: fetchStub, cache: memCache(), intervalMs: 0, sleep: noSleep }); + assert.deepEqual(await loc.byLccn('2003054578'), []); +}); diff --git a/src/server/sources/loc.ts b/src/server/sources/loc.ts index 07b922b..8d6a66e 100644 --- a/src/server/sources/loc.ts +++ b/src/server/sources/loc.ts @@ -75,7 +75,8 @@ export function createLoc(deps: { if (hit !== null) return parseMarcXml(hit); await throttle(); const res = await getText(deps.fetch, `https://lccn.loc.gov/${encodeURIComponent(lccn)}/marcxml`); - if (res.status === 404) return []; + // lccn.loc.gov answers an unknown number with 200 and a short Record not found body. + if (res.status === 404 || /\s*Record not found/i.test(res.body)) { ok(); return []; } if (res.status >= 400 || !isLocXml(res.body)) blocked(); ok(); deps.cache.set(key, res.body); diff --git a/src/server/sources/marc.test.ts b/src/server/sources/marc.test.ts index 7ee87ec..86c8e04 100644 --- a/src/server/sources/marc.test.ts +++ b/src/server/sources/marc.test.ts @@ -44,3 +44,12 @@ test('single datafield/subfield objects, several 050s, other prefixes, 082, 264' test('garbage is no records', () => { assert.deepEqual(parseMarcXml('nope'), []); }); + +test('non-text records (a DVD of the book) contribute no call number', () => { + const rec = (type: string) => `01234c${type}m a2200337 a 4500 + DVE9004.R69(viewing copy) + Harry Potter`; + assert.deepEqual(parseMarcXml(rec('g'))[0]!.lcc, []); + assert.equal(parseMarcXml(rec('g'))[0]!.meta.title, 'Harry Potter'); + assert.equal(parseMarcXml(rec('a'))[0]!.lcc.length, 1); +}); diff --git a/src/server/sources/marc.ts b/src/server/sources/marc.ts index 40fb1ff..40885ec 100644 --- a/src/server/sources/marc.ts +++ b/src/server/sources/marc.ts @@ -64,8 +64,12 @@ export function parseMarcRecord(rec: Node): MarcFields { const fields = fieldsOf(rec); const all = (tag: string) => fields.filter((f) => f.tag === tag); + // Leader position 6 is the record type. Videos, sound recordings and the like carry their own + // classification (a DVD of a novel is not the novel's shelf number), so only text records count. + const leader = text(rec['leader']); + const isText = leader.length < 7 || 'at'.includes(leader[6]); const lcc: Candidate[] = []; - for (const f of all('050')) { + for (const f of isText ? all('050') : []) { const a = sub(f, 'a'); if (!a) continue; const b = sub(f, 'b'); diff --git a/src/shared/lcc-outline.test.ts b/src/shared/lcc-outline.test.ts new file mode 100644 index 0000000..cc69e53 --- /dev/null +++ b/src/shared/lcc-outline.test.ts @@ -0,0 +1,39 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { MAIN_CLASSES, SUBCLASSES, classNames } from './lcc-outline.ts'; + +test('known classes', () => { + assert.deepEqual(classNames('QA'), { className: 'Science', subclassName: 'Mathematics' }); + assert.equal(classNames('Q').subclassName, 'Science (General)'); + assert.equal(classNames('PS').subclassName, 'American literature'); + assert.equal(classNames('TX').subclassName, 'Home economics'); + assert.equal(classNames('BX').subclassName, 'Christian denominations'); + assert.equal(classNames('DS').subclassName, 'Asia'); + assert.ok(classNames('TK').subclassName?.startsWith('Electrical engineering')); +}); + +test('edge cases', () => { + const zz = classNames('ZZ'); + assert.ok(zz.className?.startsWith('Bibliography')); + assert.equal(zz.subclassName, null); + assert.deepEqual(classNames('I'), { className: null, subclassName: null }); + const kf = classNames('KF'); + assert.equal(kf.className, 'Law'); + assert.ok(kf.subclassName); + const e = classNames('E'); + assert.ok(e.className?.includes('America')); + assert.equal(e.subclassName, null); + assert.deepEqual(classNames('qa'), classNames('QA')); + assert.ok(classNames('KFC').subclassName); + assert.ok(classNames('DAW').subclassName); +}); + +test('table sanity', () => { + assert.ok(Object.keys(SUBCLASSES).length >= 200); + for (const c of 'ABCDEFGHJKLMNPQRSTUVZ') assert.ok(MAIN_CLASSES[c], c); + for (const n of [...Object.values(MAIN_CLASSES), ...Object.values(SUBCLASSES)]) { + assert.ok(n.length > 0 && n.length <= 120, n); + assert.ok(!/ {2}/.test(n), n); + assert.ok(!/[A-Z]{1,3}\d+(\.\d+)?-\d*\s*$/.test(n), n); + } +}); diff --git a/src/shared/lcc-outline.ts b/src/shared/lcc-outline.ts new file mode 100644 index 0000000..004bf6f --- /dev/null +++ b/src/shared/lcc-outline.ts @@ -0,0 +1,259 @@ +// GENERATED by scripts/gen-lcc-outline.ts -- do not edit by hand. +// Source: Library of Congress Classification Outline, https://www.loc.gov/catdir/cpso/lcco/ +// (a US government publication). Re-run: node scripts/gen-lcc-outline.ts + +export const MAIN_CLASSES: Record = { + A: "General works", + B: "Philosophy. Psychology. Religion", + C: "Auxiliary sciences of history", + D: "World history and history of Europe, Asia, Africa, Australia, New Zealand, etc.", + E: "History of the Americas", + F: "History of the Americas", + G: "Geography. Anthropology. Recreation", + H: "Social sciences", + J: "Political science", + K: "Law", + L: "Education", + M: "Music", + N: "Fine arts", + P: "Language and literature", + Q: "Science", + R: "Medicine", + S: "Agriculture", + T: "Technology", + U: "Military science", + V: "Naval science", + Z: "Bibliography. Library science. Information resources (General)", +}; + +export const SUBCLASSES: Record = { + AC: "Collections. Series. Collected works", + AE: "Encyclopedias", + AG: "Dictionaries and other general reference works", + AI: "Indexes", + AM: "Museums. Collectors and collecting", + AN: "Newspapers", + AP: "Periodicals", + AS: "Academies and learned societies", + AY: "Yearbooks. Almanacs. Directories", + AZ: "History of scholarship and learning. The humanities", + B: "Philosophy (General)", + BC: "Logic", + BD: "Speculative philosophy", + BF: "Psychology", + BH: "Aesthetics", + BJ: "Ethics", + BL: "Religions. Mythology. Rationalism", + BM: "Judaism", + BP: "Islam. Bahaism. Theosophy, etc", + BQ: "Buddhism", + BR: "Christianity", + BS: "The Bible", + BT: "Doctrinal Theology", + BV: "Practical Theology", + BX: "Christian denominations", + C: "Auxiliary Sciences of History (General)", + CB: "History of Civilization", + CC: "Archaeology", + CD: "Diplomatics. Archives. Seals", + CE: "Technical Chronology. Calendar", + CJ: "Numismatics", + CN: "Inscriptions. Epigraphy", + CR: "Heraldry", + CS: "Genealogy", + CT: "Biography", + D: "History (General)", + DA: "Great Britain", + DAW: "Central Europe", + DB: "Austria - Liechtenstein - Hungary - Czechoslovakia", + DC: "France - Andorra - Monaco", + DD: "Germany", + DE: "Greco-Roman World", + DF: "Greece", + DG: "Italy - Malta", + DH: "Low Countries - Benelux Countries", + DJ: "Netherlands (Holland)", + DJK: "Eastern Europe (General)", + DK: "Russia. Soviet Union. Former Soviet Republics - Poland", + DL: "Northern Europe. Scandinavia", + DP: "Spain - Portugal", + DQ: "Switzerland", + DR: "Balkan Peninsula", + DS: "Asia", + DT: "Africa", + DU: "Oceania (South Seas)", + DX: "Romanies", + G: "Geography (General). Atlases. Maps", + GA: "Mathematical geography. Cartography", + GB: "Physical geography", + GC: "Oceanography", + GE: "Environmental Sciences", + GF: "Human ecology. Anthropogeography", + GN: "Anthropology", + GR: "Folklore", + GT: "Manners and customs (General)", + GV: "Recreation. Leisure", + H: "Social sciences (General)", + HA: "Statistics", + HB: "Economic theory. Demography", + HC: "Economic history and conditions", + HD: "Industries. Land use. Labor", + HE: "Transportation and communications", + HF: "Commerce", + HG: "Finance", + HJ: "Public finance", + HM: "Sociology (General)", + HN: "Social history and conditions. Social problems. Social reform", + HQ: "The family. Marriage. Women", + HS: "Societies: secret, benevolent, etc", + HT: "Communities. Classes. Races", + HV: "Social pathology. Social and public welfare. Criminology", + HX: "Socialism. Communism. Anarchism", + J: "General legislative and executive papers", + JA: "Political science (General)", + JC: "Political theory", + JF: "Political institutions and public administration", + JJ: "Political institutions and public administration (North America)", + JK: "Political institutions and public administration (United States)", + JL: "Political institutions and public administration (Canada, Latin America, etc.)", + JN: "Political institutions and public administration (Europe)", + JQ: "Political institutions and public administration (Asia, Africa, Australia, Pacific Area, etc.)", + JS: "Local government. Municipal government", + JV: "Colonies and colonization. Emigration and immigration. International migration", + JX: "International law, see JZ and KZ", + JZ: "International relations", + K: "Law in general. Comparative and uniform law. Jurisprudence", + KB: "Religious law in general. Comparative religious law. Jurisprudence", + KBM: "Jewish law", + KBP: "Islamic law", + KBR: "History of canon law", + KBU: "Law of the Roman Catholic Church. The Holy See", + KDZ: "America. North America", + KE: "Canada", + KF: "United States", + KG: "Latin America - Mexico and Central America - West Indies. Caribbean area", + KH: "South America", + KZ: "Law of nations", + L: "Education (General)", + LA: "History of education", + LB: "Theory and practice of education", + LC: "Special aspects of education", + LD: "Individual institutions - United States", + LE: "Individual institutions - America (except United States)", + LF: "Individual institutions - Europe", + LG: "Individual institutions - Asia, Africa, Indian Ocean islands, Australia, New Zealand, Pacific islands", + LH: "College and school magazines and papers", + LJ: "Student fraternities and societies, United States", + LT: "Textbooks", + M: "Music", + ML: "Literature on music", + MT: "Instruction and study", + N: "Visual arts", + NA: "Architecture", + NB: "Sculpture", + NC: "Drawing. Design. Illustration", + ND: "Painting", + NE: "Print media", + NK: "Decorative arts", + NX: "Arts in general", + P: "Philology. Linguistics", + PA: "Greek language and literature. Latin language and literature", + PB: "Modern languages. Celtic languages", + PC: "Romance languages", + PD: "Germanic languages. Scandinavian languages", + PE: "English language", + PF: "West Germanic languages", + PG: "Slavic languages. Baltic languages. Albanian language", + PH: "Uralic languages. Basque language", + PJ: "Oriental languages and literatures", + PK: "Indo-Iranian languages and literatures", + PL: "Languages and literatures of Eastern Asia, Africa, Oceania", + PM: "Hyperborean, Indian, and artificial languages", + PN: "Literature (General)", + PQ: "French literature - Italian literature - Spanish literature - Portuguese literature", + PR: "English literature", + PS: "American literature", + PT: "German literature - Dutch literature - Flemish literature since 1830 Afrikaans literature - Scandinavian literature", + PZ: "Fiction and juvenile belles lettres", + Q: "Science (General)", + QA: "Mathematics", + QB: "Astronomy", + QC: "Physics", + QD: "Chemistry", + QE: "Geology", + QH: "Natural history - Biology", + QK: "Botany", + QL: "Zoology", + QM: "Human anatomy", + QP: "Physiology", + QR: "Microbiology", + R: "Medicine (General)", + RA: "Public aspects of medicine", + RB: "Pathology", + RC: "Internal medicine", + RD: "Surgery", + RE: "Ophthalmology", + RF: "Otorhinolaryngology", + RG: "Gynecology and obstetrics", + RJ: "Pediatrics", + RK: "Dentistry", + RL: "Dermatology", + RM: "Therapeutics. Pharmacology", + RS: "Pharmacy and materia medica", + RT: "Nursing", + RV: "Botanic, Thomsonian, and eclectic medicine", + RX: "Homeopathy", + RZ: "Other systems of medicine", + S: "Agriculture (General)", + SB: "Plant culture", + SD: "Forestry", + SF: "Animal culture", + SH: "Aquaculture. Fisheries. Angling", + SK: "Hunting sports", + T: "Technology (General)", + TA: "Engineering (General). Civil engineering", + TC: "Hydraulic engineering. Ocean engineering", + TD: "Environmental technology. Sanitary engineering", + TE: "Highway engineering. Roads and pavements", + TF: "Railroad engineering and operation", + TG: "Bridge engineering", + TH: "Building construction", + TJ: "Mechanical engineering and machinery", + TK: "Electrical engineering. Electronics. Nuclear engineering", + TL: "Motor vehicles. Aeronautics. Astronautics", + TN: "Mining engineering. Metallurgy", + TP: "Chemical technology", + TR: "Photography", + TS: "Manufactures", + TT: "Handicrafts. Arts and crafts", + TX: "Home economics", + U: "Military science (General)", + UA: "Armies: Organization, distribution, military situation", + UB: "Military administration", + UC: "Maintenance and transportation", + UD: "Infantry", + UE: "Cavalry. Armor", + UF: "Artillery", + UG: "Military engineering. Air forces", + UH: "Other services", + V: "Naval science (General)", + VA: "Navies: Organization, distribution, naval situation", + VB: "Naval administration", + VC: "Naval maintenance", + VD: "Naval seamen", + VE: "Marines", + VF: "Naval ordnance", + VG: "Minor services of navies", + VK: "Navigation. Merchant marine", + VM: "Naval architecture. Shipbuilding. Marine engineering", + Z: "Books (General). Writing. Paleography. Book industries and trade. Libraries. Bibliography", + ZA: "Information resources (General)", +}; + +export function classNames(letters: string): { className: string | null; subclassName: string | null } { + const l = letters.trim().toUpperCase(); + if (!/^[A-Z]{1,3}$/.test(l)) return { className: null, subclassName: null }; + const className = MAIN_CLASSES[l[0]!] ?? null; + const subclassName = SUBCLASSES[l] ?? (l.length === 3 ? (SUBCLASSES[l.slice(0, 2)] ?? null) : null); + return { className, subclassName }; +} diff --git a/src/web/index.html b/src/web/index.html index b741165..1f0f204 100644 --- a/src/web/index.html +++ b/src/web/index.html @@ -4,6 +4,7 @@ Booksorter + diff --git a/src/web/scanner.ts b/src/web/scanner.ts index b862746..cf35f8d 100644 --- a/src/web/scanner.ts +++ b/src/web/scanner.ts @@ -20,6 +20,12 @@ function prepare(): void { }); } +/** The one detector configuration the scanner uses; also used by scripts/browser-check.ts. */ +export function makeDetector(): BarcodeDetector { + prepare(); + return new BarcodeDetector({ formats: ['ean_13'] }); +} + const INTERVAL_MS = 150; export async function startScanner( @@ -54,7 +60,7 @@ export async function startScanner( throw e; } - const detector = new BarcodeDetector({ formats: ['ean_13'] }); + const detector = makeDetector(); let state = newReadState(); // Sequential loop: the next round is scheduled only after the previous detection finished, diff --git a/src/web/styles.css b/src/web/styles.css index ed4d7a3..7b8a475 100644 --- a/src/web/styles.css +++ b/src/web/styles.css @@ -52,6 +52,7 @@ video.mirror { transform: scaleX(-1); } .item.column { flex-direction: column; align-items: stretch; gap: 8px; } .item-btn { display: flex; gap: 14px; align-items: flex-start; width: 100%; text-align: left; border: 0; padding: 0; background: none; } .item-main { display: flex; flex-direction: column; min-width: 0; flex: 1; } +.item-main .chip { align-self: flex-start; margin-top: 4px; } .item-side { display: flex; flex-direction: column; align-items: flex-end; gap: 4px; text-align: right; } .title { overflow-wrap: anywhere; } .callno { display: inline-flex; flex-direction: column; font-family: ui-monospace, "SF Mono", Menlo, monospace; font-variant-numeric: tabular-nums; white-space: pre; min-width: 9.5em; font-size: .92rem; line-height: 1.35; }