@ruckc/truss-pdf 0.0.0-stage → 1.68.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.
@@ -0,0 +1,40 @@
1
+ import type { PDFDocumentLoadingTask } from 'pdfjs-dist';
2
+ import type { PdfSource } from './types.js';
3
+ export type PdfJs = typeof import('pdfjs-dist');
4
+ /** Where pdf.js finds its worker and data files. Every field is optional; see `configurePdf`. */
5
+ export interface PdfConfig {
6
+ /** URL of `pdf.worker.min.mjs`. Default: the file from `pdfjs-dist`, emitted by Vite (`?url`). */
7
+ workerSrc?: string;
8
+ /** Base URL (trailing slash) of the CMap files (`pdfjs-dist/cmaps/`), for non-embedded CJK fonts. */
9
+ cMapUrl?: string;
10
+ /** Base URL (trailing slash) of the standard font files (`pdfjs-dist/standard_fonts/`), for non-embedded base-14 fonts. */
11
+ standardFontDataUrl?: string;
12
+ /** Base URL (trailing slash) of the wasm decoders (`pdfjs-dist/wasm/`). */
13
+ wasmUrl?: string;
14
+ /** pdf.js console logging (`VerbosityLevel`): default 0, errors only (a malformed file would otherwise log a warning per broken object). */
15
+ verbosity?: number;
16
+ /** Load pdf.js yourself (another build, e.g. `pdfjs-dist/legacy/build/pdf.mjs`, or a wrapped module). Default: `import('pdfjs-dist')`. */
17
+ loader?: () => Promise<PdfJs>;
18
+ }
19
+ /**
20
+ * Sets where pdf.js and its files come from, for every viewer (call it once at startup; it applies to documents opened afterwards).
21
+ * Fields you pass replace the current ones and `undefined` clears one. With no data URLs set, the CMaps, standard fonts and wasm decoders
22
+ * are bundled by Vite (`import.meta.glob` over `/node_modules/pdfjs-dist/`) and fetched on demand; outside Vite, or to serve them yourself,
23
+ * copy those folders and pass their URLs here.
24
+ */
25
+ export declare function configurePdf(next: PdfConfig): void;
26
+ /** Loads pdf.js once (a failed load is retried on the next call) and points it at its worker. */
27
+ export declare function loadPdfJs(): Promise<PdfJs>;
28
+ /**
29
+ * The hardened options every document is opened with, after anything else, so nothing overrides them:
30
+ * - `isEvalSupported: false`: no `eval`-compiled font or function code (pdf.js 6 dropped that path; kept so a downgrade stays safe);
31
+ * - `enableXfa: false`: XFA forms are not rendered.
32
+ * Document JavaScript never runs: it needs a scripting manager, which this package never creates, and the PDF's own annotation layer
33
+ * (form fields, link actions) is not rendered either; links are drawn by the viewer itself (see `PdfViewer`'s `onlink`).
34
+ */
35
+ export declare const SAFE_PDF_OPTIONS: {
36
+ readonly isEvalSupported: false;
37
+ readonly enableXfa: false;
38
+ };
39
+ /** Starts loading a document (await `.promise`; `.destroy()` releases it). Bytes are copied, since pdf.js transfers them to its worker. */
40
+ export declare function openPdf(src: PdfSource): Promise<PDFDocumentLoadingTask>;
package/dist/pdfjs.js ADDED
@@ -0,0 +1,49 @@
1
+ let config = {};
2
+ let loading = null;
3
+ /**
4
+ * Sets where pdf.js and its files come from, for every viewer (call it once at startup; it applies to documents opened afterwards).
5
+ * Fields you pass replace the current ones and `undefined` clears one. With no data URLs set, the CMaps, standard fonts and wasm decoders
6
+ * are bundled by Vite (`import.meta.glob` over `/node_modules/pdfjs-dist/`) and fetched on demand; outside Vite, or to serve them yourself,
7
+ * copy those folders and pass their URLs here.
8
+ */
9
+ export function configurePdf(next) {
10
+ config = { ...config, ...next };
11
+ loading = null;
12
+ }
13
+ /** Loads pdf.js once (a failed load is retried on the next call) and points it at its worker. */
14
+ export function loadPdfJs() {
15
+ loading ??= (async () => {
16
+ const pdfjs = await (config.loader ?? (() => import('pdfjs-dist')))();
17
+ const opts = pdfjs.GlobalWorkerOptions;
18
+ if (config.workerSrc)
19
+ opts.workerSrc = config.workerSrc;
20
+ else if (!opts.workerSrc && !opts.workerPort)
21
+ opts.workerSrc = (await import('pdfjs-dist/build/pdf.worker.min.mjs?url')).default;
22
+ return pdfjs;
23
+ })().catch((e) => {
24
+ loading = null;
25
+ throw e;
26
+ });
27
+ return loading;
28
+ }
29
+ /**
30
+ * The hardened options every document is opened with, after anything else, so nothing overrides them:
31
+ * - `isEvalSupported: false`: no `eval`-compiled font or function code (pdf.js 6 dropped that path; kept so a downgrade stays safe);
32
+ * - `enableXfa: false`: XFA forms are not rendered.
33
+ * Document JavaScript never runs: it needs a scripting manager, which this package never creates, and the PDF's own annotation layer
34
+ * (form fields, link actions) is not rendered either; links are drawn by the viewer itself (see `PdfViewer`'s `onlink`).
35
+ */
36
+ export const SAFE_PDF_OPTIONS = { isEvalSupported: false, enableXfa: false };
37
+ /** The data-file options: the configured URLs, else the files bundled by Vite (none when the glob found nothing). */
38
+ async function dataOptions() {
39
+ const { cMapUrl, standardFontDataUrl, wasmUrl } = config;
40
+ if (cMapUrl || standardFontDataUrl || wasmUrl)
41
+ return { cMapUrl, standardFontDataUrl, wasmUrl };
42
+ return (await import('./assets.js')).bundledDataOptions();
43
+ }
44
+ /** Starts loading a document (await `.promise`; `.destroy()` releases it). Bytes are copied, since pdf.js transfers them to its worker. */
45
+ export async function openPdf(src) {
46
+ const pdfjs = await loadPdfJs();
47
+ const source = src instanceof ArrayBuffer ? { data: new Uint8Array(src.slice(0)) } : src instanceof Uint8Array ? { data: src.slice() } : { url: String(src) };
48
+ return pdfjs.getDocument({ ...source, verbosity: config.verbosity ?? 0, ...(await dataOptions()), ...SAFE_PDF_OPTIONS });
49
+ }
@@ -0,0 +1,30 @@
1
+ /** A character range [start, end) within one segment (UTF-16 offsets). */
2
+ export interface SegmentRange {
3
+ segment: number;
4
+ start: number;
5
+ end: number;
6
+ }
7
+ export interface QuoteMatch {
8
+ ranges: SegmentRange[];
9
+ /** True when every fragment of the quote was found word for word. */
10
+ exact: boolean;
11
+ }
12
+ interface TextIndex {
13
+ /** Normalized text: lower-case letters and digits only. */
14
+ norm: string;
15
+ /** For each normalized char: segment index, and the source char's [start, end) offsets. */
16
+ seg: Int32Array;
17
+ from: Int32Array;
18
+ to: Int32Array;
19
+ }
20
+ /** Builds the normalized text of several segments, keeping a map back to the source characters. */
21
+ export declare function indexText(segments: readonly string[]): TextIndex;
22
+ /** The quote's words, normalized like the page text. */
23
+ export declare function quoteTokens(quote: string): string[];
24
+ /** Finds a quote in an index; null when no fragment of it is found. */
25
+ export declare function matchIndex(ix: TextIndex, quote: string): QuoteMatch | null;
26
+ /** Finds a quote in a list of text segments (one string for plain text). */
27
+ export declare function findQuote(segments: readonly string[], quote: string): QuoteMatch | null;
28
+ /** Merges ranges per segment (sorted, overlapping ranges joined). */
29
+ export declare function rangesBySegment(m: QuoteMatch): Map<number, [number, number][]>;
30
+ export {};
@@ -0,0 +1,145 @@
1
+ // Finds a quoted string in page text so the viewer can highlight it (adapted from EvalBot, ruckc/evalbot#dc5ce5b).
2
+ //
3
+ // Text is compared on letters and digits only (lower-cased, accents and ligatures folded), so
4
+ // differences in whitespace, line breaks, hyphenation at line ends, punctuation and curly quotes don't
5
+ // matter. A quote may be split over several text segments (a PDF text layer has one per text run).
6
+ // When the whole quote isn't found, the longest run of consecutive quote words that is found is used
7
+ // instead (a "partial" match). Quotes elided with "..." / "…" are matched fragment by fragment.
8
+ const KEEP = /[\p{L}\p{N}]/u;
9
+ const MARKS = /\p{M}/gu;
10
+ /** Folds one source character into zero or more normalized characters. */
11
+ function fold(ch) {
12
+ const f = ch.normalize('NFKD').replace(MARKS, '').toLowerCase();
13
+ let out = '';
14
+ for (const c of f)
15
+ if (KEEP.test(c))
16
+ out += c;
17
+ return out;
18
+ }
19
+ /** Builds the normalized text of several segments, keeping a map back to the source characters. */
20
+ export function indexText(segments) {
21
+ let norm = '';
22
+ const seg = [];
23
+ const from = [];
24
+ const to = [];
25
+ segments.forEach((s, i) => {
26
+ let off = 0;
27
+ for (const ch of s) {
28
+ const f = fold(ch);
29
+ for (const c of f) {
30
+ norm += c;
31
+ seg.push(i);
32
+ from.push(off);
33
+ to.push(off + ch.length);
34
+ }
35
+ off += ch.length;
36
+ }
37
+ });
38
+ return {
39
+ norm,
40
+ seg: Int32Array.from(seg),
41
+ from: Int32Array.from(from),
42
+ to: Int32Array.from(to)
43
+ };
44
+ }
45
+ /** The quote's words, normalized like the page text. */
46
+ export function quoteTokens(quote) {
47
+ return quote
48
+ .normalize('NFKD')
49
+ .replace(MARKS, '')
50
+ .toLowerCase()
51
+ .split(/[^\p{L}\p{N}]+/u)
52
+ .filter(Boolean);
53
+ }
54
+ /** Splits a quote at elisions ("...", "…", "[...]"). */
55
+ function fragments(quote) {
56
+ return quote
57
+ .split(/\s*\[?(?:\.{3,}|…)\]?\s*/u)
58
+ .map((s) => s.trim())
59
+ .filter((s) => quoteTokens(s).length > 0);
60
+ }
61
+ const MIN_PARTIAL_TOKENS = 3;
62
+ const MIN_PARTIAL_CHARS = 12;
63
+ /** Finds one fragment: [start, end) in the normalized text, or null. */
64
+ function findFragment(norm, tokens, from = 0) {
65
+ const whole = tokens.join(''); // never empty: fragments() keeps only fragments with a token
66
+ const at = norm.indexOf(whole, from);
67
+ if (at >= 0)
68
+ return { start: at, end: at + whole.length, exact: true };
69
+ // Longest run of consecutive tokens that is present (and long enough not to be a coincidence).
70
+ for (let len = tokens.length - 1; len >= MIN_PARTIAL_TOKENS; len--) {
71
+ for (let i = 0; i + len <= tokens.length; i++) {
72
+ const run = tokens.slice(i, i + len).join('');
73
+ if (run.length < MIN_PARTIAL_CHARS)
74
+ continue;
75
+ const p = norm.indexOf(run, from);
76
+ if (p >= 0)
77
+ return { start: p, end: p + run.length, exact: false };
78
+ }
79
+ }
80
+ return null;
81
+ }
82
+ /** Converts a normalized range back to per-segment source ranges. */
83
+ function toRanges(ix, start, end) {
84
+ const out = [];
85
+ for (let i = start; i < end; i++) {
86
+ const s = ix.seg[i];
87
+ const last = out.at(-1);
88
+ if (last && last.segment === s) {
89
+ last.end = Math.max(last.end, ix.to[i]);
90
+ }
91
+ else {
92
+ out.push({ segment: s, start: ix.from[i], end: ix.to[i] });
93
+ }
94
+ }
95
+ return out;
96
+ }
97
+ /** Finds a quote in an index; null when no fragment of it is found. */
98
+ export function matchIndex(ix, quote) {
99
+ const frags = fragments(quote);
100
+ if (!frags.length || !ix.norm)
101
+ return null;
102
+ const ranges = [];
103
+ let exact = true;
104
+ let found = 0;
105
+ let from = 0;
106
+ for (const f of frags) {
107
+ const hit = findFragment(ix.norm, quoteTokens(f), from) ?? findFragment(ix.norm, quoteTokens(f));
108
+ if (!hit) {
109
+ exact = false;
110
+ continue;
111
+ }
112
+ found++;
113
+ if (!hit.exact)
114
+ exact = false;
115
+ ranges.push(...toRanges(ix, hit.start, hit.end));
116
+ from = hit.end;
117
+ }
118
+ return found ? { ranges, exact } : null;
119
+ }
120
+ /** Finds a quote in a list of text segments (one string for plain text). */
121
+ export function findQuote(segments, quote) {
122
+ return matchIndex(indexText(segments), quote);
123
+ }
124
+ /** Merges ranges per segment (sorted, overlapping ranges joined). */
125
+ export function rangesBySegment(m) {
126
+ const by = new Map();
127
+ for (const r of m.ranges) {
128
+ const list = by.get(r.segment) ?? [];
129
+ list.push([r.start, r.end]);
130
+ by.set(r.segment, list);
131
+ }
132
+ for (const [k, list] of by) {
133
+ list.sort((a, b) => a[0] - b[0]);
134
+ const merged = [];
135
+ for (const r of list) {
136
+ const last = merged.at(-1);
137
+ if (last && r[0] <= last[1])
138
+ last[1] = Math.max(last[1], r[1]);
139
+ else
140
+ merged.push([r[0], r[1]]);
141
+ }
142
+ by.set(k, merged);
143
+ }
144
+ return by;
145
+ }
@@ -0,0 +1,142 @@
1
+ /** What the viewer shows: a URL, or the bytes of a PDF (copied before pdf.js transfers them to its worker, so yours stay usable). */
2
+ export type PdfSource = string | URL | ArrayBuffer | Uint8Array;
3
+ /** A rectangle in PDF user space: points, origin at the bottom-left of the page's media box, before the page's /Rotate. */
4
+ export interface PdfBox {
5
+ x: number;
6
+ y: number;
7
+ width: number;
8
+ height: number;
9
+ }
10
+ /**
11
+ * Where to go. Pass it as the `target` prop (re-applied when `targetKey` changes) or to `goTo(target)`.
12
+ * - `{ page }`: a 1-based page.
13
+ * - `{ page, x, y, width, height }`: a region in PDF user space, outlined and scrolled into view (centred when it fits).
14
+ * - `{ page?, quote }`: a quote found fuzzily in the text layer (whitespace, hyphenation, ligature and punctuation tolerant) and highlighted.
15
+ * With `page` that page is searched first and the nearest page with an exact match wins; `strict` searches that page only.
16
+ * - `{ dest }`: a named destination, else an outline (bookmark) item with that title.
17
+ * - `{ annotation }`: an annotation of the `annotations` prop by id (its page, scrolled into view; `focus` also focuses it).
18
+ */
19
+ export type PdfTarget = {
20
+ page: number;
21
+ x?: undefined;
22
+ quote?: undefined;
23
+ } | ({
24
+ page: number;
25
+ quote?: undefined;
26
+ } & PdfBox) | {
27
+ page?: number;
28
+ quote: string;
29
+ strict?: boolean;
30
+ } | {
31
+ dest: string;
32
+ } | {
33
+ annotation: string;
34
+ focus?: boolean;
35
+ };
36
+ /** `found`: shown exactly; `partial`: only part of the quote matched, or the region lies partly off the page; `missing`: not found. */
37
+ export type PdfGoToResult = 'found' | 'partial' | 'missing';
38
+ /** Visual tone of an annotation, mapped to the Truss intent tokens (`info` uses the primary colour). */
39
+ export type PdfAnnotationTone = 'danger' | 'warning' | 'info' | 'neutral' | 'success' | 'primary';
40
+ /** A host-supplied overlay. It is drawn over the page and never written into the PDF. */
41
+ export interface PdfAnnotation {
42
+ id: string;
43
+ /** 1-based page. */
44
+ page: number;
45
+ /** One or more regions in PDF user space, or a quote to locate in the page's text layer. */
46
+ target: {
47
+ boxes: PdfBox[];
48
+ } | {
49
+ quote: string;
50
+ };
51
+ /** Default `warning`. */
52
+ tone?: PdfAnnotationTone;
53
+ /** Shown in a tooltip on hover and focus, and used as the accessible name. Untrusted text is fine: it is bidi-isolated and never parsed as HTML. */
54
+ label?: string;
55
+ /** Quieter styling, e.g. an item already reviewed. */
56
+ muted?: boolean;
57
+ }
58
+ /** What the user drew or selected when creating an annotation (`oncreate`). Storing it is up to the host. */
59
+ export interface PdfCreateDetail {
60
+ page: number;
61
+ /** In PDF user space: one box for a drawn region, one per line for a text selection. */
62
+ boxes: PdfBox[];
63
+ /** The selected text, or the text inside the drawn box. */
64
+ text: string;
65
+ }
66
+ /** Tone of a review item's marker in the list and of an action button (the Truss intent tokens). */
67
+ export type ReviewTone = 'primary' | 'neutral' | 'success' | 'warning' | 'danger';
68
+ /**
69
+ * One thing to review: a finding, a redaction, a comment, a checklist entry. Extra fields of your own are kept and handed back to
70
+ * `filters`, `actions`, `onaction` and the `detail` snippet (the panel is generic over the item type).
71
+ */
72
+ export interface ReviewItem {
73
+ /** Stable id: the selection follows it across `items` updates. */
74
+ id: string;
75
+ /** 1-based page. Items without one are listed in the "Document" group, before the pages. */
76
+ page?: number | null;
77
+ /** The id of the viewer annotation this item is about: navigating scrolls it into view and selects it (`goTo({ annotation })`). */
78
+ annotation?: string;
79
+ /** Where to go when there is no `annotation` (a region, a quote); with neither, the item's `page`. */
80
+ target?: PdfTarget;
81
+ /** Shown in the list and announced. Untrusted text is fine: it is bidi-isolated and never parsed as HTML. */
82
+ title: string;
83
+ /** A second, quieter line in the list (an excerpt, a category). Bidi-isolated too. */
84
+ description?: string;
85
+ /** Colour of the item's marker. Default `warning`. */
86
+ tone?: ReviewTone;
87
+ /** The item's state (`open`, `accepted`...): filters and `actions[].applies` usually read it; `statuses` gives it a label and a tone. */
88
+ status: string;
89
+ }
90
+ /** A filter segment: its count is the number of items it matches. */
91
+ export interface ReviewFilter<T extends ReviewItem = ReviewItem> {
92
+ id: string;
93
+ label: string;
94
+ match: (item: T) => boolean;
95
+ }
96
+ /** What a confirmation asks before an action runs (return it from `ReviewAction.confirm`). */
97
+ export interface ReviewConfirm {
98
+ title: string;
99
+ message?: string;
100
+ /** The text concerned, quoted under the message (bidi-isolated, never parsed as HTML). */
101
+ excerpt?: string;
102
+ /** Label of the confirming button. Default: the action's label. */
103
+ confirmLabel?: string;
104
+ /** Default: `danger` and `warning` actions keep their tone, the others are `primary`. */
105
+ tone?: 'primary' | 'warning' | 'danger';
106
+ /** Ask for a note, handed to `onaction` as `{ note }`. `true` is an optional note with the default label. */
107
+ note?: boolean | {
108
+ label?: string;
109
+ placeholder?: string;
110
+ required?: boolean;
111
+ value?: string;
112
+ };
113
+ }
114
+ /** An action the host offers on the selected item (Accept, Dismiss, Reopen...). */
115
+ export interface ReviewAction<T extends ReviewItem = ReviewItem> {
116
+ id: string;
117
+ label: string;
118
+ /** A single key or combination (`a`, `shift+d`): pressed inside the review, outside text fields, it runs the action on the selected item. */
119
+ shortcut?: string;
120
+ tone?: ReviewTone;
121
+ /** Return a confirmation to show before the action runs, or nothing to run it at once. */
122
+ confirm?: (item: T) => ReviewConfirm | null | undefined | false;
123
+ /** Whether the action is offered for this item (default: always). */
124
+ applies?: (item: T) => boolean;
125
+ /** Offer it in the bulk bar too (with `bulk`), for the checked items it applies to. */
126
+ bulk?: boolean;
127
+ /** The confirmation for a bulk run on these items. */
128
+ confirmBulk?: (items: T[]) => ReviewConfirm | null | undefined | false;
129
+ }
130
+ /** What an action is called with besides the item: the note typed in its confirmation. */
131
+ export interface ReviewActionDetail {
132
+ note?: string;
133
+ }
134
+ /** How each status is shown: its label and tone (a status without an entry shows as is). */
135
+ export type ReviewStatuses = Record<string, {
136
+ label: string;
137
+ tone?: ReviewTone;
138
+ }>;
139
+ /** The part of a viewer the panel drives: a `PdfViewer`, a `PdfDialog`, or anything with the same `goTo`. */
140
+ export interface ReviewViewer {
141
+ goTo(target: PdfTarget): Promise<PdfGoToResult>;
142
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
- "name": "@ruckc/truss-pdf",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@ruckc/truss-pdf",
3
+ "version": "1.68.0",
4
+ "description": "A hardened pdf.js viewer for Truss UI: whole-page paging, jump to a page, region, quote or destination, annotation overlays and a review workflow",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "scripts": {
8
+ "package": "svelte-package -i src/lib -o dist",
9
+ "prepack": "npm run package"
10
+ },
11
+ "files": [
12
+ "dist",
13
+ "README.md"
14
+ ],
15
+ "sideEffects": [
16
+ "**/*.css"
17
+ ],
18
+ "svelte": "./dist/index.js",
19
+ "types": "./dist/index.d.ts",
20
+ "exports": {
21
+ ".": {
22
+ "types": "./dist/index.d.ts",
23
+ "svelte": "./dist/index.js"
24
+ }
25
+ },
26
+ "peerDependencies": {
27
+ "@ruckc/truss-ui": "^1.68.0",
28
+ "svelte": "^5.20.0"
29
+ },
30
+ "author": "Curtis Ruck",
31
+ "homepage": "https://truss.ruck.io",
32
+ "bugs": {
33
+ "url": "https://github.com/ruckc/truss-ui/issues"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/ruckc/truss-ui.git",
41
+ "directory": "packages/pdf"
42
+ },
43
+ "keywords": [
44
+ "svelte",
45
+ "sveltekit",
46
+ "truss",
47
+ "pdf",
48
+ "pdfjs",
49
+ "viewer",
50
+ "annotations"
51
+ ],
52
+ "dependencies": {
53
+ "pdfjs-dist": "^6.5.438"
54
+ }
55
+ }