@lemonriver/core 0.6.0 → 0.7.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 (44) hide show
  1. package/dist/{build-RlcGG-Ve.js → build-CKwrex8y.js} +1 -1
  2. package/dist/cli/bin.js +3 -3
  3. package/dist/{config-BJT87wE9.js → config-B1_gk0sy.js} +1641 -60
  4. package/dist/{dev-DR-j_xda.js → dev-DZ2Yzl2p.js} +1 -1
  5. package/dist/{preview-BTAhTb5B.js → preview-hMDcuHfP.js} +1 -1
  6. package/dist/vite/index.js +1 -1
  7. package/package.json +1 -1
  8. package/src/app/lemonriver/chrome/app-chrome.tsx +12 -1
  9. package/src/app/lemonriver/features.test.ts +5 -0
  10. package/src/app/lemonriver/features.ts +2 -1
  11. package/src/app/lemonriver/feedback/pending-toast.ts +7 -2
  12. package/src/app/lemonriver/home/deck-card.tsx +10 -1
  13. package/src/app/lemonriver/home/home-page.tsx +52 -1
  14. package/src/app/lemonriver/share/capture.ts +76 -0
  15. package/src/app/lemonriver/share/client.ts +162 -0
  16. package/src/app/lemonriver/share/codes.test.ts +49 -0
  17. package/src/app/lemonriver/share/codes.ts +30 -0
  18. package/src/app/lemonriver/share/compare.test.ts +199 -0
  19. package/src/app/lemonriver/share/compare.ts +367 -0
  20. package/src/app/lemonriver/share/drop.ts +84 -0
  21. package/src/app/lemonriver/share/folder.test.ts +42 -0
  22. package/src/app/lemonriver/share/folder.ts +29 -0
  23. package/src/app/lemonriver/share/freeze.ts +51 -0
  24. package/src/app/lemonriver/share/guide.test.ts +78 -0
  25. package/src/app/lemonriver/share/guide.ts +222 -0
  26. package/src/app/lemonriver/share/import-dialog.tsx +391 -0
  27. package/src/app/lemonriver/share/import-entry.tsx +106 -0
  28. package/src/app/lemonriver/share/model.ts +150 -0
  29. package/src/app/lemonriver/share/naming.test.ts +59 -0
  30. package/src/app/lemonriver/share/naming.ts +71 -0
  31. package/src/app/lemonriver/share/paths.test.ts +75 -0
  32. package/src/app/lemonriver/share/paths.ts +181 -0
  33. package/src/app/lemonriver/share/pdf.test.ts +79 -0
  34. package/src/app/lemonriver/share/pdf.ts +169 -0
  35. package/src/app/lemonriver/share/share-dialog.tsx +286 -0
  36. package/src/app/lemonriver/share/summary.ts +47 -0
  37. package/src/app/lemonriver/slide-extensions.tsx +69 -23
  38. package/src/app/lemonriver/templates/library-page.tsx +5 -2
  39. package/src/app/lemonriver/text/en.ts +67 -0
  40. package/src/app/lemonriver/text/es.ts +67 -0
  41. package/src/app/lemonriver/text/ja.ts +67 -0
  42. package/src/app/lemonriver/text/types.ts +78 -0
  43. package/src/app/lemonriver/text/zh-cn.ts +62 -0
  44. package/src/app/lemonriver/text/zh-tw.ts +62 -0
@@ -0,0 +1,59 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import {
3
+ dayStamp,
4
+ freeImportSlideId,
5
+ isValidExtraName,
6
+ packageBaseName,
7
+ safeFileName,
8
+ uniqueFileName,
9
+ } from './naming.ts';
10
+
11
+ describe('package file names', () => {
12
+ it('strips what Finder and Explorer refuse', () => {
13
+ expect(safeFileName('Q3/经营:汇报*?"<>|', 'q3')).toBe('Q3经营汇报');
14
+ expect(safeFileName(' 前后有空格 ', 'q3')).toBe('前后有空格');
15
+ expect(safeFileName('a\u0007b', 'q3')).toBe('ab');
16
+ });
17
+
18
+ it('falls back to the slide id, then to a name', () => {
19
+ expect(safeFileName('///', 'q3-report')).toBe('q3-report');
20
+ expect(safeFileName('', '')).toBe('LemonRiver');
21
+ });
22
+
23
+ it('keeps the name to 80 characters', () => {
24
+ expect(safeFileName('长'.repeat(200), 'q3')).toHaveLength(80);
25
+ });
26
+
27
+ it('numbers a second package with the same name', () => {
28
+ expect(uniqueFileName('Q3', [])).toBe('Q3');
29
+ expect(uniqueFileName('Q3', ['q3'])).toBe('Q3 (2)');
30
+ expect(uniqueFileName('Q3', ['Q3', 'Q3 (2)'])).toBe('Q3 (3)');
31
+ });
32
+
33
+ it('names one deck after itself and several after the day', () => {
34
+ expect(packageBaseName([{ title: 'Q3 经营汇报', slideId: 'q3' }], 0)).toBe('Q3 经营汇报');
35
+ const many = [
36
+ { title: 'A', slideId: 'a' },
37
+ { title: 'B', slideId: 'b' },
38
+ ];
39
+ const now = new Date(2026, 10, 1, 12).getTime();
40
+ expect(packageBaseName(many, now)).toBe('LemonRiver 备份 2026-11-01');
41
+ expect(dayStamp(now)).toBe('2026-11-01');
42
+ });
43
+
44
+ it('gives an imported deck its own id', () => {
45
+ expect(freeImportSlideId('q3', [])).toBe('q3');
46
+ expect(freeImportSlideId('q3', ['Q3'])).toBe('q3-imported');
47
+ expect(freeImportSlideId('q3', ['q3', 'q3-imported'])).toBe('q3-imported-2');
48
+ });
49
+
50
+ it('only lets a PDF, an HTML page or text ride along', () => {
51
+ expect(isValidExtraName('Q3 经营汇报.pdf')).toBe(true);
52
+ expect(isValidExtraName('怎么打开.html')).toBe(true);
53
+ expect(isValidExtraName('README.txt')).toBe(true);
54
+ expect(isValidExtraName('setup.sh')).toBe(false);
55
+ expect(isValidExtraName('../x.pdf')).toBe(false);
56
+ expect(isValidExtraName('.hidden.pdf')).toBe(false);
57
+ expect(isValidExtraName('no-extension')).toBe(false);
58
+ });
59
+ });
@@ -0,0 +1,71 @@
1
+ const RESERVED = new Set(['/', '\\', ':', '*', '?', '"', '<', '>', '|']);
2
+ const MAX_BASE = 80;
3
+
4
+ function clean(raw: string): string {
5
+ let out = '';
6
+ for (const character of raw) {
7
+ const code = character.codePointAt(0) ?? 0;
8
+ if (code < 0x20 || code === 0x7f) continue;
9
+ if (RESERVED.has(character)) continue;
10
+ out += character;
11
+ }
12
+ return out.replace(/\s+/g, ' ').trim().slice(0, MAX_BASE).trim();
13
+ }
14
+
15
+ /** What the user can call a file without tripping over macOS, Windows or Finder. */
16
+ export function safeFileName(raw: string, fallback: string): string {
17
+ const name = clean(raw);
18
+ if (name !== '') return name;
19
+ const fallbackName = clean(fallback);
20
+ return fallbackName !== '' ? fallbackName : 'LemonRiver';
21
+ }
22
+
23
+ function two(n: number): string {
24
+ return String(n).padStart(2, '0');
25
+ }
26
+
27
+ export function dayStamp(now: number): string {
28
+ const date = new Date(now);
29
+ return `${date.getFullYear()}-${two(date.getMonth() + 1)}-${two(date.getDate())}`;
30
+ }
31
+
32
+ /** One deck is named after itself; a set of them is a backup with a date. */
33
+ export function packageBaseName(decks: { title: string; slideId: string }[], now: number): string {
34
+ if (decks.length === 1) {
35
+ const [deck] = decks;
36
+ return safeFileName(deck.title, deck.slideId);
37
+ }
38
+ return safeFileName(`LemonRiver 备份 ${dayStamp(now)}`, `LemonRiver-${dayStamp(now)}`);
39
+ }
40
+
41
+ /** Finder and Explorer both treat these as the same name. */
42
+ export function uniqueFileName(base: string, taken: Iterable<string>): string {
43
+ const used = new Set([...taken].map((name) => name.toLowerCase()));
44
+ if (!used.has(base.toLowerCase())) return base;
45
+ for (let n = 2; ; n++) {
46
+ const candidate = `${base} (${n})`;
47
+ if (!used.has(candidate.toLowerCase())) return candidate;
48
+ }
49
+ }
50
+
51
+ /** A deck that arrives beside one with the same id gets its own. */
52
+ export function freeImportSlideId(slideId: string, taken: Iterable<string>): string {
53
+ const used = new Set([...taken].map((id) => id.toLowerCase()));
54
+ if (!used.has(slideId.toLowerCase())) return slideId;
55
+ for (let n = 1; ; n++) {
56
+ const candidate = n === 1 ? `${slideId}-imported` : `${slideId}-imported-${n}`;
57
+ if (!used.has(candidate.toLowerCase())) return candidate;
58
+ }
59
+ }
60
+
61
+ const EXTRA_EXTENSIONS = new Set(['pdf', 'html', 'txt']);
62
+
63
+ /** The PDF and the how-to-open page ride at the top of the zip. */
64
+ export function isValidExtraName(name: string): boolean {
65
+ if (name === '' || name.startsWith('.') || name.includes('/') || name.includes('\\'))
66
+ return false;
67
+ if (name.includes('\0')) return false;
68
+ const dot = name.lastIndexOf('.');
69
+ if (dot <= 0) return false;
70
+ return EXTRA_EXTENSIONS.has(name.slice(dot + 1).toLowerCase());
71
+ }
@@ -0,0 +1,75 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { isJunkPath, isPackagePath, packagePathProblem, slideIdOfPath } from './paths.ts';
3
+
4
+ describe('package paths', () => {
5
+ it('accepts the folders a package is made of', () => {
6
+ expect(isPackagePath('manifest.json')).toBe(true);
7
+ expect(isPackagePath('slides/q3-report/index.tsx')).toBe(true);
8
+ expect(isPackagePath('slides/q3-report/kit/skeletons.tsx')).toBe(true);
9
+ expect(isPackagePath('slides/q3-report/assets/logo.png')).toBe(true);
10
+ expect(isPackagePath('board/q3-report.json')).toBe(true);
11
+ expect(isPackagePath('thumbs/q3-report/01.jpg')).toBe(true);
12
+ expect(isPackagePath('themes/aero.md')).toBe(true);
13
+ expect(isPackagePath('themes/aero.demo.tsx')).toBe(true);
14
+ expect(isPackagePath('slides/q3-report/kit/fonts/OFL.txt')).toBe(true);
15
+ expect(isPackagePath('slides/q3-report/kit/LICENSE')).toBe(true);
16
+ });
17
+
18
+ it('refuses paths that climb out or lie about where they are', () => {
19
+ expect(packagePathProblem('../x')?.code).toBe('bad-path');
20
+ expect(packagePathProblem('slides/../x.tsx')?.code).toBe('bad-path');
21
+ expect(packagePathProblem('slides/q3/kit/../index.tsx')?.code).toBe('bad-path');
22
+ expect(packagePathProblem('slides/q3/kit/../../logo.png')?.code).toBe('bad-path');
23
+ expect(packagePathProblem('slides/q3/./index.tsx')?.code).toBe('bad-path');
24
+ expect(packagePathProblem('/etc/passwd')?.code).toBe('bad-path');
25
+ expect(packagePathProblem('C:/x.tsx')?.code).toBe('bad-path');
26
+ expect(packagePathProblem('slides\\q3\\index.tsx')?.code).toBe('bad-path');
27
+ expect(packagePathProblem('slides//index.tsx')?.code).toBe('bad-path');
28
+ expect(packagePathProblem('slides/q3/.hidden.tsx')?.code).toBe('bad-path');
29
+ expect(packagePathProblem('slides/q3/index.tsx\0.png')?.code).toBe('bad-path');
30
+ });
31
+
32
+ it('refuses node_modules and files that would configure the other machine', () => {
33
+ expect(packagePathProblem('slides/q3/node_modules/x.js')?.code).toBe('blocked-file');
34
+ expect(packagePathProblem('slides/q3/package.json')?.code).toBe('blocked-file');
35
+ expect(packagePathProblem('slides/q3/package-lock.json')?.code).toBe('blocked-file');
36
+ expect(packagePathProblem('slides/q3/pnpm-lock.yaml')?.code).toBe('blocked-file');
37
+ expect(packagePathProblem('slides/q3/yarn.lock')?.code).toBe('blocked-file');
38
+ expect(packagePathProblem('slides/q3/bun.lockb')?.code).toBe('blocked-file');
39
+ expect(packagePathProblem('slides/q3/.npmrc')?.code).toBe('bad-path');
40
+ expect(packagePathProblem('slides/q3/vite.config.ts')?.code).toBe('blocked-file');
41
+ expect(packagePathProblem('slides/q3/lemonriver.config.ts')?.code).toBe('blocked-file');
42
+ expect(packagePathProblem('slides/q3/open-slide.config.ts')?.code).toBe('blocked-file');
43
+ });
44
+
45
+ it('refuses an extension a deck may not carry', () => {
46
+ expect(packagePathProblem('slides/q3/setup.sh')?.code).toBe('blocked-file');
47
+ expect(packagePathProblem('slides/q3/run.command')?.code).toBe('blocked-file');
48
+ expect(packagePathProblem('slides/q3/Evil.app')?.code).toBe('blocked-file');
49
+ expect(packagePathProblem('slides/q3/tool')?.code).toBe('blocked-file');
50
+ });
51
+
52
+ it('wants one of the shapes for every folder', () => {
53
+ expect(packagePathProblem('slides/q3')?.code).toBe('bad-path');
54
+ expect(packagePathProblem('board/q3')?.code).toBe('bad-path');
55
+ expect(packagePathProblem('board/a/b.json')?.code).toBe('bad-path');
56
+ expect(packagePathProblem('thumbs/q3/1.jpg')?.code).toBe('bad-path');
57
+ expect(packagePathProblem('themes/aero.css')?.code).toBe('bad-path');
58
+ expect(packagePathProblem('extras/Q3.pdf')?.code).toBe('bad-path');
59
+ expect(packagePathProblem('manifest.json/x')?.code).toBe('bad-path');
60
+ });
61
+
62
+ it('names the deck a file belongs to', () => {
63
+ expect(slideIdOfPath('slides/q3-report/index.tsx')).toBe('q3-report');
64
+ expect(slideIdOfPath('board/q3-report.json')).toBe('q3-report');
65
+ expect(slideIdOfPath('thumbs/q3-report/01.jpg')).toBe('q3-report');
66
+ expect(slideIdOfPath('manifest.json')).toBeNull();
67
+ expect(slideIdOfPath('themes/aero.md')).toBeNull();
68
+ });
69
+
70
+ it('ignores what a Mac leaves in a zip', () => {
71
+ expect(isJunkPath('__MACOSX/._index.tsx')).toBe(true);
72
+ expect(isJunkPath('LemonRiver-files/.DS_Store')).toBe(true);
73
+ expect(isJunkPath('LemonRiver-files/slides/q3/index.tsx')).toBe(false);
74
+ });
75
+ });
@@ -0,0 +1,181 @@
1
+ import type { ShareCode } from './model.ts';
2
+
3
+ /** Slide ids are the same shape the editor uses for a deck folder. */
4
+ export const SHARE_SLIDE_ID_RE = /^[a-z0-9_-]+$/i;
5
+
6
+ const SLIDE_EXTENSIONS = new Set([
7
+ 'tsx',
8
+ 'ts',
9
+ 'jsx',
10
+ 'js',
11
+ 'mjs',
12
+ 'json',
13
+ 'css',
14
+ 'md',
15
+ 'txt',
16
+ 'csv',
17
+ 'png',
18
+ 'jpg',
19
+ 'jpeg',
20
+ 'gif',
21
+ 'webp',
22
+ 'svg',
23
+ 'avif',
24
+ 'ico',
25
+ 'bmp',
26
+ 'mp4',
27
+ 'webm',
28
+ 'mov',
29
+ 'mp3',
30
+ 'wav',
31
+ 'm4a',
32
+ 'ogg',
33
+ 'woff',
34
+ 'woff2',
35
+ 'ttf',
36
+ 'otf',
37
+ 'pdf',
38
+ 'xlsx',
39
+ 'xls',
40
+ 'docx',
41
+ 'doc',
42
+ 'pptx',
43
+ 'key',
44
+ 'numbers',
45
+ 'pages',
46
+ ]);
47
+
48
+ const BLOCKED_SLIDE_FILES =
49
+ /^(?:package\.json|package-lock\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb|\.npmrc|vite\.config\..+|lemonriver\.config\..+|open-slide\.config\..+)$/i;
50
+
51
+ export type PathProblem = { code: ShareCode; detail: string };
52
+
53
+ function extensionOf(name: string): string {
54
+ const dot = name.lastIndexOf('.');
55
+ return dot > 0 ? name.slice(dot + 1).toLowerCase() : '';
56
+ }
57
+
58
+ /** `LICENSE`, `OFL.txt` and friends: no extension we would accept otherwise. */
59
+ function looksLikeLicence(name: string): boolean {
60
+ return (
61
+ /^(?:LICENSE|OFL)/i.test(name) ||
62
+ (name === name.toUpperCase() && /^[A-Z0-9][A-Z0-9._-]*$/.test(name))
63
+ );
64
+ }
65
+
66
+ function structuralProblem(rel: string): PathProblem | null {
67
+ if (rel === '') return { code: 'bad-path', detail: 'empty path' };
68
+ if (rel.includes('\0')) return { code: 'bad-path', detail: 'path holds a null byte' };
69
+ if (rel.includes('\\')) return { code: 'bad-path', detail: 'backslash in path' };
70
+ if (rel.startsWith('/') || /^[a-z]:/i.test(rel)) {
71
+ return { code: 'bad-path', detail: 'absolute path' };
72
+ }
73
+ for (const segment of rel.split('/')) {
74
+ if (segment === '') return { code: 'bad-path', detail: 'empty path segment' };
75
+ if (segment === '.' || segment === '..') return { code: 'bad-path', detail: 'path climbs out' };
76
+ // `.` and `..` belong to the rule above; this one is about hidden files.
77
+ if (segment.startsWith('.') && segment !== '..') {
78
+ return { code: 'bad-path', detail: `hidden segment "${segment}"` };
79
+ }
80
+ if (segment.toLowerCase() === 'node_modules') {
81
+ return { code: 'blocked-file', detail: 'node_modules is not shipped' };
82
+ }
83
+ }
84
+ return null;
85
+ }
86
+
87
+ function slideFileProblem(rest: string): PathProblem | null {
88
+ const name = rest.slice(rest.lastIndexOf('/') + 1);
89
+ if (BLOCKED_SLIDE_FILES.test(name)) {
90
+ return { code: 'blocked-file', detail: `${name} would configure the other machine` };
91
+ }
92
+ if (looksLikeLicence(name)) return null;
93
+ const extension = extensionOf(name);
94
+ if (extension === '' || !SLIDE_EXTENSIONS.has(extension)) {
95
+ return { code: 'blocked-file', detail: `"${name}" is not a file a deck may carry` };
96
+ }
97
+ return null;
98
+ }
99
+
100
+ /**
101
+ * One rule for both ends: what may sit under `LemonRiver-files/`. Anything the
102
+ * packer would refuse is also refused on the way in.
103
+ */
104
+ export function packagePathProblem(rel: string): PathProblem | null {
105
+ const structural = structuralProblem(rel);
106
+ if (structural) return structural;
107
+
108
+ const segments = rel.split('/');
109
+ const [head, ...rest] = segments;
110
+
111
+ if (head === 'manifest.json') {
112
+ return segments.length === 1 ? null : { code: 'bad-path', detail: 'manifest.json is a file' };
113
+ }
114
+
115
+ if (head === 'board') {
116
+ if (rest.length !== 1 || !rest[0].endsWith('.json')) {
117
+ return { code: 'bad-path', detail: 'board holds <slideId>.json only' };
118
+ }
119
+ const id = rest[0].slice(0, -'.json'.length);
120
+ if (!SHARE_SLIDE_ID_RE.test(id)) return { code: 'bad-path', detail: `bad slide id "${id}"` };
121
+ return null;
122
+ }
123
+
124
+ if (head === 'themes') {
125
+ if (rest.length !== 1) return { code: 'bad-path', detail: 'themes holds files only' };
126
+ const name = rest[0];
127
+ if (name.endsWith('.demo.tsx')) {
128
+ const id = name.slice(0, -'.demo.tsx'.length);
129
+ if (!SHARE_SLIDE_ID_RE.test(id)) return { code: 'bad-path', detail: `bad theme id "${id}"` };
130
+ return null;
131
+ }
132
+ if (name.endsWith('.md')) {
133
+ const id = name.slice(0, -'.md'.length);
134
+ if (!SHARE_SLIDE_ID_RE.test(id)) return { code: 'bad-path', detail: `bad theme id "${id}"` };
135
+ return null;
136
+ }
137
+ return { code: 'bad-path', detail: 'a theme is <id>.md or <id>.demo.tsx' };
138
+ }
139
+
140
+ if (head === 'thumbs') {
141
+ if (rest.length !== 2 || !/^\d{2,}\.jpg$/.test(rest[1])) {
142
+ return { code: 'bad-path', detail: 'a thumbnail is <slideId>/NN.jpg' };
143
+ }
144
+ if (!SHARE_SLIDE_ID_RE.test(rest[0])) {
145
+ return { code: 'bad-path', detail: `bad slide id "${rest[0]}"` };
146
+ }
147
+ return null;
148
+ }
149
+
150
+ if (head === 'slides') {
151
+ if (rest.length < 2) return { code: 'bad-path', detail: 'a slide holds at least one file' };
152
+ if (!SHARE_SLIDE_ID_RE.test(rest[0])) {
153
+ return { code: 'bad-path', detail: `bad slide id "${rest[0]}"` };
154
+ }
155
+ return slideFileProblem(rest.slice(1).join('/'));
156
+ }
157
+
158
+ return { code: 'bad-path', detail: `"${head}" is not part of a package` };
159
+ }
160
+
161
+ export function isPackagePath(rel: string): boolean {
162
+ return packagePathProblem(rel) === null;
163
+ }
164
+
165
+ /** The deck a package path belongs to, or null for manifest and themes. */
166
+ export function slideIdOfPath(rel: string): string | null {
167
+ const segments = rel.split('/');
168
+ if (segments[0] === 'slides' || segments[0] === 'board' || segments[0] === 'thumbs') {
169
+ if (segments[0] === 'board') {
170
+ return segments[1]?.endsWith('.json') ? segments[1].slice(0, -'.json'.length) : null;
171
+ }
172
+ return segments[1] ?? null;
173
+ }
174
+ return null;
175
+ }
176
+
177
+ /** Ignored on the way in: what a Mac leaves behind when it zips a folder. */
178
+ export function isJunkPath(rel: string): boolean {
179
+ if (rel.startsWith('__MACOSX/') || rel === '__MACOSX') return true;
180
+ return rel.split('/').some((segment) => segment === '.DS_Store');
181
+ }
@@ -0,0 +1,79 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { buildImagePdf, jpegSize, PDF_PAGE_HEIGHT, PDF_PAGE_WIDTH, utf16BeHex } from './pdf';
3
+
4
+ const latin1 = (bytes: Uint8Array) => Buffer.from(bytes).toString('latin1');
5
+ const jpeg = (base64: string) => new Uint8Array(Buffer.from(base64, 'base64'));
6
+
7
+ // Two real 2x2 JPEGs, so the builder reads their true size like it will in a package.
8
+ const JPEG_WHITE = jpeg(
9
+ '/9j/4AAQSkZJRgABAQAASABIAAD/4QBMRXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAAqADAAQAAAABAAAAAgAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8AAEQgAAgACAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/bAEMAAgICAgICAwICAwUDAwMFBgUFBQUGCAYGBgYGCAoICAgICAgKCgoKCgoKCgwMDAwMDA4ODg4ODw8PDw8PDw8PD//bAEMBAgICBAQEBwQEBxALCQsQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEP/dAAQAAf/aAAwDAQACEQMRAD8A/fyiiigD/9k=',
10
+ );
11
+ const JPEG_BLACK = jpeg(
12
+ '/9j/4AAQSkZJRgABAQAASABIAAD/4QBMRXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAAqADAAQAAAABAAAAAgAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8AAEQgAAgACAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/bAEMAAgICAgICAwICAwUDAwMFBgUFBQUGCAYGBgYGCAoICAgICAgKCgoKCgoKCgwMDAwMDA4ODg4ODw8PDw8PDw8PD//bAEMBAgICBAQEBwQEBxALCQsQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEP/dAAQAAf/aAAwDAQACEQMRAD8A/E+iiiugD//Z',
13
+ );
14
+
15
+ function page(bytes: Uint8Array) {
16
+ return { jpeg: bytes, width: 2, height: 2 };
17
+ }
18
+
19
+ describe('buildImagePdf', () => {
20
+ const pdf = buildImagePdf([page(JPEG_WHITE), page(JPEG_BLACK)], { title: '季度报告' });
21
+ const text = latin1(pdf);
22
+
23
+ it('writes one page per image, at the print size', () => {
24
+ expect(text.match(/\/Type \/Page\b/g)).toHaveLength(2);
25
+ expect(text).toContain(`/MediaBox [0 0 ${PDF_PAGE_WIDTH} ${PDF_PAGE_HEIGHT}]`);
26
+ expect(PDF_PAGE_WIDTH).toBe(1440);
27
+ expect(PDF_PAGE_HEIGHT).toBe(810);
28
+ expect(text).toContain('%PDF-');
29
+ });
30
+
31
+ it('points every xref entry at its object', () => {
32
+ const start = text.lastIndexOf('\nxref\n');
33
+ const lines = text.slice(start + 1).split('\n');
34
+ const count = Number(lines[1].split(' ')[1]);
35
+ expect(count).toBeGreaterThan(3);
36
+ for (let id = 1; id < count; id++) {
37
+ const offset = Number(lines[2 + id].slice(0, 10));
38
+ expect(text.slice(offset, offset + String(id).length + 2), `object ${id}`).toBe(`${id} 0`);
39
+ expect(text.slice(offset).startsWith(`${id} 0 obj`), `object ${id} header`).toBe(true);
40
+ }
41
+ });
42
+
43
+ it('declares each image stream with exactly its own byte length', () => {
44
+ for (const bytes of [JPEG_WHITE, JPEG_BLACK]) {
45
+ const at = pdf.findIndex(
46
+ (byte, i) => byte === 0xff && bytes.every((b, k) => pdf[i + k] === b),
47
+ );
48
+ expect(at).toBeGreaterThan(0);
49
+ const before = latin1(pdf.slice(Math.max(0, at - 220), at));
50
+ const match = /\/Length (\d+) >>\nstream\n$/.exec(before);
51
+ expect(match, 'image stream header').not.toBeNull();
52
+ expect(Number(match?.[1])).toBe(bytes.length);
53
+ expect(latin1(pdf.slice(at + bytes.length, at + bytes.length + 10))).toBe('\nendstream');
54
+ }
55
+ });
56
+
57
+ it('reads the frame header of a real JPEG', () => {
58
+ expect(jpegSize(JPEG_WHITE)).toEqual({ width: 2, height: 2 });
59
+ });
60
+
61
+ it('refuses a page that is not a JPEG', () => {
62
+ const png = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3]);
63
+ expect(() => buildImagePdf([{ jpeg: png, width: 2, height: 2 }], { title: 'x' })).toThrow(
64
+ /page 1 is not a JPEG/,
65
+ );
66
+ });
67
+
68
+ it('refuses a page whose size does not match its JPEG', () => {
69
+ expect(() =>
70
+ buildImagePdf([{ jpeg: JPEG_BLACK, width: 1920, height: 1080 }], { title: 'x' }),
71
+ ).toThrow(/is 2x2, not 1920x1080/);
72
+ });
73
+
74
+ it('writes the title as UTF-16BE with a byte-order mark', () => {
75
+ expect(utf16BeHex('季度报告')).toBe('FEFF5B635EA662A5544A');
76
+ expect(text).toContain('/Title <FEFF5B635EA662A5544A>');
77
+ expect(text).toContain('/Producer (LemonRiver)');
78
+ });
79
+ });
@@ -0,0 +1,169 @@
1
+ /** A one-image-per-page PDF, written by hand so the package needs no dependency. */
2
+
3
+ export type PdfPage = { jpeg: Uint8Array; width: number; height: number };
4
+
5
+ export type PdfMeta = { title: string };
6
+
7
+ // The same page size the browser's print export uses for a 1920×1080 slide.
8
+ export const PDF_PAGE_WIDTH = 1440;
9
+ export const PDF_PAGE_HEIGHT = 810;
10
+
11
+ const encoder = new TextEncoder();
12
+
13
+ class ByteWriter {
14
+ private parts: Uint8Array[] = [];
15
+ private size = 0;
16
+
17
+ get length(): number {
18
+ return this.size;
19
+ }
20
+
21
+ push(part: string | Uint8Array): number {
22
+ const bytes = typeof part === 'string' ? encoder.encode(part) : part;
23
+ this.parts.push(bytes);
24
+ const at = this.size;
25
+ this.size += bytes.length;
26
+ return at;
27
+ }
28
+
29
+ toBytes(): Uint8Array {
30
+ const out = new Uint8Array(this.size);
31
+ let at = 0;
32
+ for (const part of this.parts) {
33
+ out.set(part, at);
34
+ at += part.length;
35
+ }
36
+ return out;
37
+ }
38
+ }
39
+
40
+ /** PDF text strings are UTF-16BE with a byte-order mark, written as hex. */
41
+ export function utf16BeHex(text: string): string {
42
+ let hex = 'FEFF';
43
+ for (let i = 0; i < text.length; i++) {
44
+ hex += text.charCodeAt(i).toString(16).padStart(4, '0').toUpperCase();
45
+ }
46
+ return hex;
47
+ }
48
+
49
+ export function isJpeg(bytes: Uint8Array): boolean {
50
+ return bytes.length > 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff;
51
+ }
52
+
53
+ /** Width and height from the frame header, which every JPEG carries. */
54
+ export function jpegSize(bytes: Uint8Array): { width: number; height: number } | null {
55
+ let i = 2;
56
+ while (i + 9 < bytes.length) {
57
+ if (bytes[i] !== 0xff) return null;
58
+ let marker = bytes[i + 1] as number;
59
+ while (marker === 0xff) {
60
+ i += 1;
61
+ marker = bytes[i + 1] as number;
62
+ }
63
+ i += 2;
64
+ const standalone =
65
+ marker === 0xd8 || marker === 0xd9 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7);
66
+ if (standalone) continue;
67
+ const length = ((bytes[i] as number) << 8) | (bytes[i + 1] as number);
68
+ if (length < 2) return null;
69
+ const frame =
70
+ marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc;
71
+ if (frame) {
72
+ const height = ((bytes[i + 3] as number) << 8) | (bytes[i + 4] as number);
73
+ const width = ((bytes[i + 5] as number) << 8) | (bytes[i + 6] as number);
74
+ return width > 0 && height > 0 ? { width, height } : null;
75
+ }
76
+ i += length;
77
+ }
78
+ return null;
79
+ }
80
+
81
+ function checkPage(page: PdfPage, index: number): void {
82
+ if (!isJpeg(page.jpeg)) {
83
+ throw new Error(`page ${index + 1} is not a JPEG`);
84
+ }
85
+ const size = jpegSize(page.jpeg);
86
+ if (!size) throw new Error(`page ${index + 1} has no readable JPEG frame header`);
87
+ if (size.width !== page.width || size.height !== page.height) {
88
+ throw new Error(
89
+ `page ${index + 1} is ${size.width}x${size.height}, not ${page.width}x${page.height}`,
90
+ );
91
+ }
92
+ }
93
+
94
+ function contentStream(): string {
95
+ return `q\n${PDF_PAGE_WIDTH} 0 0 ${PDF_PAGE_HEIGHT} 0 0 cm\n/Im0 Do\nQ\n`;
96
+ }
97
+
98
+ function pad10(value: number): string {
99
+ return String(value).padStart(10, '0');
100
+ }
101
+
102
+ export function buildImagePdf(pages: PdfPage[], meta: PdfMeta): Uint8Array {
103
+ pages.forEach(checkPage);
104
+ const writer = new ByteWriter();
105
+ const offsets: number[] = [];
106
+ const begin = (id: number) => {
107
+ offsets[id] = writer.push(`${id} 0 obj\n`);
108
+ };
109
+ const end = () => writer.push('endobj\n');
110
+
111
+ writer.push('%PDF-1.4\n');
112
+
113
+ begin(1);
114
+ writer.push('<< /Type /Catalog /Pages 2 0 R >>\n');
115
+ end();
116
+
117
+ const kids = pages.map((_, i) => `${3 + i * 3} 0 R`).join(' ');
118
+ begin(2);
119
+ writer.push(`<< /Type /Pages /Kids [${kids}] /Count ${pages.length} >>\n`);
120
+ end();
121
+
122
+ pages.forEach((page, i) => {
123
+ const pageId = 3 + i * 3;
124
+ const imageId = pageId + 1;
125
+ const contentId = pageId + 2;
126
+
127
+ begin(pageId);
128
+ writer.push(
129
+ `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${PDF_PAGE_WIDTH} ${PDF_PAGE_HEIGHT}] ` +
130
+ `/Resources << /XObject << /Im0 ${imageId} 0 R >> >> /Contents ${contentId} 0 R >>\n`,
131
+ );
132
+ end();
133
+
134
+ begin(imageId);
135
+ writer.push(
136
+ `<< /Type /XObject /Subtype /Image /Width ${page.width} /Height ${page.height} ` +
137
+ `/ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length ${page.jpeg.length} >>\nstream\n`,
138
+ );
139
+ writer.push(page.jpeg);
140
+ writer.push('\nendstream\n');
141
+ end();
142
+
143
+ const content = contentStream();
144
+ const contentBytes = encoder.encode(content);
145
+ begin(contentId);
146
+ writer.push(`<< /Length ${contentBytes.length} >>\nstream\n`);
147
+ writer.push(contentBytes);
148
+ writer.push('endstream\n');
149
+ end();
150
+ });
151
+
152
+ const infoId = 3 + pages.length * 3;
153
+ begin(infoId);
154
+ writer.push(`<< /Title <${utf16BeHex(meta.title)}> /Producer (LemonRiver) >>\n`);
155
+ end();
156
+
157
+ const xrefAt = writer.length;
158
+ const count = infoId + 1;
159
+ let xref = `xref\n0 ${count}\n0000000000 65535 f \n`;
160
+ for (let id = 1; id < count; id++) {
161
+ xref += `${pad10(offsets[id] ?? 0)} 00000 n \n`;
162
+ }
163
+ writer.push(xref);
164
+ writer.push(
165
+ `trailer\n<< /Size ${count} /Root 1 0 R /Info ${infoId} 0 R >>\nstartxref\n${xrefAt}\n%%EOF\n`,
166
+ );
167
+
168
+ return writer.toBytes();
169
+ }