From 165765ddb4b7ca356692e6280eab258246f9f60b Mon Sep 17 00:00:00 2001 From: lecstor Date: Tue, 13 Oct 2026 08:20:09 +1000 Subject: [PATCH 1/5] MV3 extension skeleton: GitHub .md adapter, build for chromium+firefox --- .gitignore | 5 + package-lock.json | 2803 +++++++++++++++++++++++++++++++++++ package.json | 30 + scripts/build.mjs | 115 ++ scripts/manifest.mjs | 76 + scripts/verify-packages.mjs | 84 ++ src/adapters/github.ts | 150 ++ src/adapters/registry.ts | 15 + src/adapters/types.ts | 37 + src/background.ts | 42 + src/content.ts | 16 + src/lib/assets.ts | 22 + src/lib/build-target.ts | 55 + src/lib/button.ts | 154 ++ src/lib/bytes.ts | 19 + src/lib/controller.ts | 146 ++ src/lib/download.ts | 32 + src/lib/errors.ts | 140 ++ src/lib/github-url.ts | 165 +++ src/lib/markdown-images.ts | 199 +++ src/lib/messages.ts | 41 + src/lib/mime.ts | 43 + src/lib/render-client.ts | 89 ++ src/lib/service.ts | 11 + src/options/options.css | 128 ++ src/options/options.html | 57 + src/options/options.ts | 51 + tsconfig.json | 20 + vitest.config.ts | 11 + 29 files changed, 4756 insertions(+) create mode 100644 .gitignore create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 scripts/build.mjs create mode 100644 scripts/manifest.mjs create mode 100644 scripts/verify-packages.mjs create mode 100644 src/adapters/github.ts create mode 100644 src/adapters/registry.ts create mode 100644 src/adapters/types.ts create mode 100644 src/background.ts create mode 100644 src/content.ts create mode 100644 src/lib/assets.ts create mode 100644 src/lib/build-target.ts create mode 100644 src/lib/button.ts create mode 100644 src/lib/bytes.ts create mode 100644 src/lib/controller.ts create mode 100644 src/lib/download.ts create mode 100644 src/lib/errors.ts create mode 100644 src/lib/github-url.ts create mode 100644 src/lib/markdown-images.ts create mode 100644 src/lib/messages.ts create mode 100644 src/lib/mime.ts create mode 100644 src/lib/render-client.ts create mode 100644 src/lib/service.ts create mode 100644 src/options/options.css create mode 100644 src/options/options.html create mode 100644 src/options/options.ts create mode 100644 tsconfig.json create mode 100644 vitest.config.ts diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..344b12d --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +node_modules/ +dist/ +.worktrees/ +*.log +.DS_Store diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..106d596 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,2803 @@ +{ + "name": "makespdf-browser-extension", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "makespdf-browser-extension", + "version": "0.1.0", + "license": "MIT", + "dependencies": { + "webextension-polyfill": "^0.12.0" + }, + "devDependencies": { + "@types/node": "^24.0.0", + "@types/webextension-polyfill": "^0.12.3", + "esbuild": "^0.25.0", + "jsdom": "^26.0.0", + "jszip": "^3.10.1", + "typescript": "^5.7.0", + "vitest": "^3.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@asamuzakjp/css-color": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-3.2.0.tgz", + "integrity": "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@csstools/css-calc": "^2.1.3", + "@csstools/css-color-parser": "^3.0.9", + "@csstools/css-parser-algorithms": "^3.0.4", + "@csstools/css-tokenizer": "^3.0.3", + "lru-cache": "^10.4.3" + } + }, + "node_modules/@csstools/color-helpers": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz", + "integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@csstools/css-calc": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz", + "integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz", + "integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^5.1.0", + "@csstools/css-calc": "^2.1.4" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz", + "integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz", + "integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@napi-rs/lzma-linux-x64-gnu": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz", + "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^22.20 || ^24.12 || >=25" + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.64.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.64.5.tgz", + "integrity": "sha512-MrfgRQSpD5hkkRg6XI16B6EDLb+6+xp8xje6bpdSwkYw+qxrBKbUVrRAQu9h82UT+QumSIVQ8HXsXjPd2dlhqw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.64.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.64.5.tgz", + "integrity": "sha512-+uu2p/R9Tzn8GpoQyX1pAo5dmKT1DhXevfaCzqzmPFhnLjHLWw7uWkaVGlxmhwYoRiYYhsGfRcD5cTBpL7rgSw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.64.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.64.5.tgz", + "integrity": "sha512-17dys+YEmzwzzFVHQAVDONg5FALXY9kd99HFEpfk4gJVHYxoh5bGea3D4t1fXXnwkTcOe25wPyd6nWS0I8IdLQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.64.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.64.5.tgz", + "integrity": "sha512-wg0zQEKkEvFZf1UaaX1UELOoPs//OSKUG7D+yITuqOsAvza7LvHTv5Wu4nmMfzNG7EYI2jp2PJC7Id6OETmsYQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.64.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.64.5.tgz", + "integrity": "sha512-CoJmWcpEMuwin+TZ/ev/H9uDyF/uxUKQSWXdmIPn/UBx/uGV9+4ebMp0FwnlhWR9PE1AdzYsKf3bZevhif38+A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.64.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.64.5.tgz", + "integrity": "sha512-PxZnLAaTUAL5xG0W2BXLeYPKrK2b3LIASV2/e/Kf7PZvSLI1iAQIm9B9aJD+YyFIT7hc6qaMV3+OOO35R28LfA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.64.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.64.5.tgz", + "integrity": "sha512-uPo3IvnONjhbFXwWgroBeFwOicuhT7ZwQrnzkzmOtBJzeQbkUJUE1SJDfDI31ijQ5+ZUIA6sPrdUMxTSnxUWAg==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.64.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.64.5.tgz", + "integrity": "sha512-ywI8Jyuc4LyHYTjC0mw4yA1ulvZBkHusdpWnoiEBsmBuHvSnt90btTBGCZ+s/2y+YNNfVAEKy33nPo5UI9zTmg==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.64.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.64.5.tgz", + "integrity": "sha512-tmuXJoQ/3ovSr637aykZMdQteU/CB2APAz2CrvsbibuoHZi1BS1Db13cVViBdEARGwXCLn1DSJ8wsjoThLJPGA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.64.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.64.5.tgz", + "integrity": "sha512-5FMjSYNcUOHx7oW8Qu9KB6jGPpvF/8sG7+BDHwU/Ihh1/6FMJ9ySmsFG4tJ1qbNRuP8OLzCBDso4sF0mQaLuFQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.64.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.64.5.tgz", + "integrity": "sha512-K8ZJ+neLDbUkIrL8dqF/5LtuVCrKwo27kREgOlxjBEjlOXwHvDnHLU8Z/UKv/B49qi7e8hsSDOyoJwhwqhvX4w==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.64.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.64.5.tgz", + "integrity": "sha512-NlVxsq7PFPv0DBKGuNWRDKixQYQCjM53zl04mxEcKMBmJbCBIUm1JdPfIWDRHyOOFzzYPmLQzfeEwh4716ayQg==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.64.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.64.5.tgz", + "integrity": "sha512-ARhRHJYs5eCFet5azfrHD97vOkD8OzNW2RSMlvo5CcBqXaTOLfp0OHDtUQh7/K5AL5fUYoFp2fgC9KDg4vVYMQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.64.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.64.5.tgz", + "integrity": "sha512-atSgreM5C7jpxd9aEXN+6vJ5wTd05iYw+S3FiQpw7VsoEl8B90llbq35ARON+GOHj5QlVQEq2vOKWCHTob/BSQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.64.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.64.5.tgz", + "integrity": "sha512-vmlmwBFGnjVWxSRoVabNkyYuscSmg52Pd0fM8jEbNT3Jmka4A6HcB84x4uAmuumznWfBVaxKOqU6jbEgomWKCA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.64.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.64.5.tgz", + "integrity": "sha512-hhJrP6S9WkbsbcHgUkvCBS5Cn8IdsG8XjlLZyxjnv9+NdoYfbbZE4TWJYr8apdaj1M5t5Y1id2StnEslxpNFyA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.64.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.64.5.tgz", + "integrity": "sha512-NNVCyN9pGrwFmQa4bf+Cnf5aVH3g6ZpnlOg1Cs/H9swIHT9bRixijfzUqyEIWm1WtiAuR1LJ+rJH6zpBm8kgQA==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.64.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.64.5.tgz", + "integrity": "sha512-dR9nd6OKnvSS60Ifz/L7Mj5zzYyoqyRn2NwTuaOONKaa3xsVGXyp8YusMbvFyEOR94DxnwgcbgsFqkHd29ZSzQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.64.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.64.5.tgz", + "integrity": "sha512-1tzsMjaqhsh3bAO6SJiJqh8hIr9sSPRd+i2vPPxJHod8/XYnf9TEnK0z/u3r1z1AkI347X0KbRSg9dWcxeGahw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.64.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.64.5.tgz", + "integrity": "sha512-01mWMQblKoXXsmk28KXtpbA96w7g/aOWUoV3AC16fdHdqkykGalqyyM+5u8M7uP5/MEMiiPv69Hv7iv/hEH/dA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.64.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.64.5.tgz", + "integrity": "sha512-trdnMPb/DNm4V/CgsaoGgr90HfQQ071wfK0KoIs4YpLvjBgVQGXhGabg2Z6nK4EcYNilrb9ZZPcsP6+zpJIdxQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.64.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.64.5.tgz", + "integrity": "sha512-x2LxZlfdfsw99T6/qb9EqE/Qi84JWzibjyOJyhJsgFJy6CafaTiqIXCCnslCGrV5XWNh7fwrS3FbRENcuKnooA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.64.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.64.5.tgz", + "integrity": "sha512-/Qd/9aDQIo0+jmItgBmPIs8195YVbDxRRApn47GyufgbutCDOh7eP5vSKKlI4QNFeaI+wKQAkSMsPnF3EuMpaA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.64.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.64.5.tgz", + "integrity": "sha512-ngUJ/XvOWrqbd2IMsfXfh2xXFLTP3sY7sCKvxbGvYdBZ1KmXFd3ewDZ9n3/GNzAUgzRuhLT/UvJRivbNoAQRBw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.64.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.64.5.tgz", + "integrity": "sha512-IhV6ew/DuzUWwHaYmlh7MrPCV3lKFUq/amTEwysi4r/mwNPAEfAMh5dYWeTSPTeMy2pFHGMEWYtPkHzfX3tG5A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "24.19.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz", + "integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": ">=7.24.0 <7.24.7" + } + }, + "node_modules/@types/webextension-polyfill": { + "version": "0.12.6", + "resolved": "https://registry.npmjs.org/@types/webextension-polyfill/-/webextension-polyfill-0.12.6.tgz", + "integrity": "sha512-XTNQSGiQaipt1iocbpHSjYHd+Ujcya+K5H4H2uH7JwycReTFixoYqGWIKih2Ec072NuEW2lAyXRDYmlEx00+cw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@vitest/expect": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.7.tgz", + "integrity": "sha512-E8eBXaKibuvH2pSZErOjdVb5vF4PbKYcrnluBTYxEk1l/VhhwZg1kZQsdtjq+CsF5CFydf2Rdkz7jDHKSisi3w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/spy": "3.2.7", + "@vitest/utils": "3.2.7", + "chai": "^5.2.0", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-3.2.7.tgz", + "integrity": "sha512-Trr0hYO9CM3Wj6ksWHRhK9IZpIY6wTMO5u/MqXurMxT57sWBaOPEtP3Oq60ihZuh5JsiagKfz95OcxdEP6dBrA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "3.2.7", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.17" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/pretty-format": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.7.tgz", + "integrity": "sha512-KUHlwqVu0sRlhCdyPdQ/wBoTfRahjUky1MubOmYw9fWfIZy1gNoHpuaaQBPAaMaVYdQYHJLurzj8ECCj5OwTqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-3.2.7.tgz", + "integrity": "sha512-sB9y4ovltoQP+WaUPwmSxO9WIg9Ig694Di5PalVPsYHklAdE027mehpWF2SQSVq+k6sFgaivbTjTJwZLSHbedA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "3.2.7", + "pathe": "^2.0.3", + "strip-literal": "^3.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-3.2.7.tgz", + "integrity": "sha512-7C+MwShwtBSI5Buwoyg3s/iY1eHL9PKAf+O1wVh/TdnjXUtkoL/9YQtre90i4MtNXM6edP1wJ2zOBpfCyhIS7g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.7", + "magic-string": "^0.30.17", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-3.2.7.tgz", + "integrity": "sha512-Q2eQGI6d2L/hBtZ0qNuKcAGid68XK6cv1xsoaIma6PaJhHPoqcEJhYpXZ/5myCMqkNgtP6UKuBhbc0nHKnrkuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyspy": "^4.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-3.2.7.tgz", + "integrity": "sha512-x6BDOd7dyo3PFLY3I9/HJ25X/6OurhGXk2/B9gOZNPF7XDVjeBK4k01lQE5uvDpbuheErh91qYuE1E2OEjK3Rw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.7", + "loupe": "^3.1.4", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/cac": { + "version": "6.7.14", + "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", + "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/chai": { + "version": "5.3.3", + "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz", + "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "assertion-error": "^2.0.1", + "check-error": "^2.1.1", + "deep-eql": "^5.0.1", + "loupe": "^3.1.0", + "pathval": "^2.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/check-error": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz", + "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 16" + } + }, + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/cssstyle": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.6.0.tgz", + "integrity": "sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/css-color": "^3.2.0", + "rrweb-cssom": "^0.8.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/data-urls": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz", + "integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, + "node_modules/deep-eql": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz", + "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/entities": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/es-module-lexer": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", + "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", + "dev": true, + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/html-encoding-sniffer": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz", + "integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-encoding": "^3.1.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/immediate": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz", + "integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/js-tokens": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz", + "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsdom": { + "version": "26.1.0", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-26.1.0.tgz", + "integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssstyle": "^4.2.1", + "data-urls": "^5.0.0", + "decimal.js": "^10.5.0", + "html-encoding-sniffer": "^4.0.0", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.6", + "is-potential-custom-element-name": "^1.0.1", + "nwsapi": "^2.2.16", + "parse5": "^7.2.1", + "rrweb-cssom": "^0.8.0", + "saxes": "^6.0.0", + "symbol-tree": "^3.2.4", + "tough-cookie": "^5.1.1", + "w3c-xmlserializer": "^5.0.0", + "webidl-conversions": "^7.0.0", + "whatwg-encoding": "^3.1.1", + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.1.1", + "ws": "^8.18.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "canvas": "^3.0.0" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "node_modules/jszip": { + "version": "3.10.2", + "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.2.tgz", + "integrity": "sha512-3l+rb15IOWtUhU0H5MFqES/T6Kh7abYwjosBey/vD6hDt8zoEffkSC5Ws5SGtgVw3gBx2NEbhTeSW1+kWkpyTQ==", + "dev": true, + "license": "(MIT OR GPL-3.0-or-later)", + "dependencies": { + "lie": "~3.3.0", + "pako": "~1.0.2", + "readable-stream": "~2.3.6", + "setimmediate": "^1.0.5" + } + }, + "node_modules/lie": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz", + "integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "immediate": "~3.0.5" + } + }, + "node_modules/loupe": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz", + "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/nwsapi": { + "version": "2.2.28", + "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.28.tgz", + "integrity": "sha512-IlVB7OS7qrOsVYlpnFIkETjMwT9jwvmocJmmM+GZU/PAB3uGi9Ezd7vcWhWBUnSc0ya4ppmQITOyP1ez9gg8cg==", + "dev": true, + "license": "MIT" + }, + "node_modules/pako": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", + "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==", + "dev": true, + "license": "(MIT AND Zlib)" + }, + "node_modules/parse5": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz", + "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^6.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/pathval": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz", + "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.16" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.30", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.30.tgz", + "integrity": "sha512-zkd+e9S1AQHhmaBKye9zlFHWjOwVgqXl1q3ECYy8561K7qxR2cREf/STLskulBFd78k6AOFeA+ff1TtEzk9bAA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", + "dev": true, + "license": "MIT" + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "dev": true, + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/rollup": { + "version": "4.64.5", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.64.5.tgz", + "integrity": "sha512-EAP5ZHcz2ijbgCWwPkpI7zh6bfsri2Ez5FtCy2dCp1k62duXzfG7DLGGh7RU2QQXWwavT+u4qpvDF/TWOiiGTw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.9" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@napi-rs/lzma-linux-x64-gnu": "1.5.1", + "@rollup/rollup-android-arm-eabi": "4.64.5", + "@rollup/rollup-android-arm64": "4.64.5", + "@rollup/rollup-darwin-arm64": "4.64.5", + "@rollup/rollup-darwin-x64": "4.64.5", + "@rollup/rollup-freebsd-arm64": "4.64.5", + "@rollup/rollup-freebsd-x64": "4.64.5", + "@rollup/rollup-linux-arm-gnueabihf": "4.64.5", + "@rollup/rollup-linux-arm-musleabihf": "4.64.5", + "@rollup/rollup-linux-arm64-gnu": "4.64.5", + "@rollup/rollup-linux-arm64-musl": "4.64.5", + "@rollup/rollup-linux-loong64-gnu": "4.64.5", + "@rollup/rollup-linux-loong64-musl": "4.64.5", + "@rollup/rollup-linux-ppc64-gnu": "4.64.5", + "@rollup/rollup-linux-ppc64-musl": "4.64.5", + "@rollup/rollup-linux-riscv64-gnu": "4.64.5", + "@rollup/rollup-linux-riscv64-musl": "4.64.5", + "@rollup/rollup-linux-s390x-gnu": "4.64.5", + "@rollup/rollup-linux-x64-gnu": "4.64.5", + "@rollup/rollup-linux-x64-musl": "4.64.5", + "@rollup/rollup-openbsd-x64": "4.64.5", + "@rollup/rollup-openharmony-arm64": "4.64.5", + "@rollup/rollup-win32-arm64-msvc": "4.64.5", + "@rollup/rollup-win32-ia32-msvc": "4.64.5", + "@rollup/rollup-win32-x64-gnu": "4.64.5", + "@rollup/rollup-win32-x64-msvc": "4.64.5", + "fsevents": "~2.3.2" + } + }, + "node_modules/rrweb-cssom": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz", + "integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==", + "dev": true, + "license": "MIT" + }, + "node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "dev": true, + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true, + "license": "MIT" + }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, + "node_modules/setimmediate": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", + "integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==", + "dev": true, + "license": "MIT" + }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/std-env": { + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz", + "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==", + "dev": true, + "license": "MIT" + }, + "node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/strip-literal": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-3.1.0.tgz", + "integrity": "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "js-tokens": "^9.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", + "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz", + "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinypool": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz", + "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.0.0 || >=20.0.0" + } + }, + "node_modules/tinyrainbow": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-2.0.0.tgz", + "integrity": "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tinyspy": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-4.0.6.tgz", + "integrity": "sha512-u8KszXvGfU68hVcZpRHKG28T0krMuv2G5nDhiHaMLen/gIuFEgIJhaJuO69qjnXg5paSrbPMFfx3brNuN8eVSg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tldts": { + "version": "6.1.86", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.86.tgz", + "integrity": "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^6.1.86" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "6.1.86", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.86.tgz", + "integrity": "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tough-cookie": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.1.2.tgz", + "integrity": "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^6.1.32" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz", + "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "7.24.6", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", + "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==", + "dev": true, + "license": "MIT" + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "dev": true, + "license": "MIT" + }, + "node_modules/vite": { + "version": "7.3.7", + "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.7.tgz", + "integrity": "sha512-AHEzTORMbi7/7aXp7w7KZ5+DCUdSeLsJz0grY8xHpc9DHdYb0vQu6DqJfm2tOw3gDExNgPgnJTXxM6syYFHaCA==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.27.0 || ^0.28.0", + "fdir": "^6.5.0", + "picomatch": "^4.0.3", + "postcss": "^8.5.6", + "rollup": "^4.43.0", + "tinyglobby": "^0.2.15" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "lightningcss": "^1.21.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vite-node": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-3.2.4.tgz", + "integrity": "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cac": "^6.7.14", + "debug": "^4.4.1", + "es-module-lexer": "^1.7.0", + "pathe": "^2.0.3", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "bin": { + "vite-node": "vite-node.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/vite/node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/vitest": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.7.tgz", + "integrity": "sha512-KrxIJ62Fd89gfysR4WotlgZABiz2dqFPgqGzX7s+CwsqLFomRH7777ZcrOD6+WVAh7khPQP41A+BKbpcJFrdEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/expect": "3.2.7", + "@vitest/mocker": "3.2.7", + "@vitest/pretty-format": "^3.2.7", + "@vitest/runner": "3.2.7", + "@vitest/snapshot": "3.2.7", + "@vitest/spy": "3.2.7", + "@vitest/utils": "3.2.7", + "chai": "^5.2.0", + "debug": "^4.4.1", + "expect-type": "^1.2.1", + "magic-string": "^0.30.17", + "pathe": "^2.0.3", + "picomatch": "^4.0.2", + "std-env": "^3.9.0", + "tinybench": "^2.9.0", + "tinyexec": "^0.3.2", + "tinyglobby": "^0.2.14", + "tinypool": "^1.1.1", + "tinyrainbow": "^2.0.0", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0", + "vite-node": "3.2.4", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@types/debug": "^4.1.12", + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "@vitest/browser": "3.2.7", + "@vitest/ui": "3.2.7", + "happy-dom": "*", + "jsdom": "*" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@types/debug": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + } + } + }, + "node_modules/w3c-xmlserializer": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", + "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/webextension-polyfill": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/webextension-polyfill/-/webextension-polyfill-0.12.0.tgz", + "integrity": "sha512-97TBmpoWJEE+3nFBQ4VocyCdLKfw54rFaJ6EVQYLBCXqCIpLSZkwGgASpv4oPt9gdKCJ80RJlcmNzNn008Ag6Q==", + "license": "MPL-2.0" + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-encoding": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz", + "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==", + "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation", + "dev": true, + "license": "MIT", + "dependencies": { + "iconv-lite": "0.6.3" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-mimetype": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", + "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-url": { + "version": "14.2.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz", + "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tr46": "^5.1.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/ws": { + "version": "8.22.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz", + "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..6768210 --- /dev/null +++ b/package.json @@ -0,0 +1,30 @@ +{ + "name": "makespdf-browser-extension", + "version": "0.1.0", + "private": true, + "description": "Browser extension: download GitHub Markdown files as PDF via makesPDF", + "license": "MIT", + "type": "module", + "engines": { + "node": ">=20" + }, + "scripts": { + "build": "node scripts/build.mjs", + "typecheck": "tsc --noEmit", + "test": "vitest run", + "test:watch": "vitest", + "verify:packages": "node scripts/verify-packages.mjs" + }, + "dependencies": { + "webextension-polyfill": "^0.12.0" + }, + "devDependencies": { + "@types/node": "^24.0.0", + "@types/webextension-polyfill": "^0.12.3", + "esbuild": "^0.25.0", + "jsdom": "^26.0.0", + "jszip": "^3.10.1", + "typescript": "^5.7.0", + "vitest": "^3.0.0" + } +} diff --git a/scripts/build.mjs b/scripts/build.mjs new file mode 100644 index 0000000..119fa2c --- /dev/null +++ b/scripts/build.mjs @@ -0,0 +1,115 @@ +/** + * One build, two loadable packages: node scripts/build.mjs + * + * Produces dist/chromium and dist/firefox, each a complete unpacked + * extension (Chrome: chrome://extensions → Load unpacked; Firefox: + * about:debugging → Load Temporary Add-on), plus a zip of each. + * + * The only source-level difference between the packages is the + * `__BUILD_TARGET__` define, which drives the `X-MakesPDF-Client` header + * (`browser-extension/+`) and the manifest's background key. + */ + +import { build } from "esbuild"; +import { copyFile, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import JSZip from "jszip"; +import { TARGETS, manifestFor } from "./manifest.mjs"; + +const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), ".."); + +/** Recursively add a directory's files to a JSZip archive. */ +async function addDir(zip, dir, prefix) { + for (const entry of await readdir(dir, { withFileTypes: true })) { + const full = join(dir, entry.name); + const rel = prefix ? `${prefix}/${entry.name}` : entry.name; + if (entry.isDirectory()) await addDir(zip, full, rel); + else zip.file(rel, await readFile(full)); + } +} + +/** + * Build every target into `outRoot` (default `/dist`). + * + * Exported so the unit tests can build into a temp directory and pin the + * built artifacts (the client header per package, manifest keys) without + * touching the working tree's dist/. + * + * @returns {Promise} paths written (per target: dir, and zip when requested) + */ +export async function buildAll({ outRoot = join(ROOT, "dist"), targets = TARGETS, zip = false } = {}) { + const pkg = JSON.parse(await readFile(join(ROOT, "package.json"), "utf8")); + await rm(outRoot, { recursive: true, force: true }); + const written = []; + + for (const target of targets) { + const outDir = join(outRoot, target); + await mkdir(join(outDir, "options"), { recursive: true }); + + const common = { + bundle: true, + platform: "browser", + // Both baselines support ES2022 in extension contexts. + target: ["chrome109", "firefox115"], + define: { + __BUILD_TARGET__: JSON.stringify(target), + __EXTENSION_VERSION__: JSON.stringify(pkg.version), + }, + logLevel: "warning", + legalComments: "none", + minify: false, + sourcemap: false, + }; + + // Content scripts are classic scripts (no ES modules in MV3 content + // scripts) — bundle to a single IIFE. + await build({ + ...common, + entryPoints: [join(ROOT, "src/content.ts")], + outfile: join(outDir, "content.js"), + format: "iife", + }); + + // Background runs as a module in both packages (service worker on + // Chrome, event page on Firefox). + await build({ + ...common, + entryPoints: [join(ROOT, "src/background.ts")], + outfile: join(outDir, "background.js"), + format: "esm", + }); + + // Options page: a classic script loaded by options.html. + await build({ + ...common, + entryPoints: [join(ROOT, "src/options/options.ts")], + outfile: join(outDir, "options/options.js"), + format: "iife", + }); + + await copyFile(join(ROOT, "src/options/options.html"), join(outDir, "options/options.html")); + await copyFile(join(ROOT, "src/options/options.css"), join(outDir, "options/options.css")); + await writeFile( + join(outDir, "manifest.json"), + `${JSON.stringify(manifestFor(target, pkg.version), null, 2)}\n`, + ); + written.push(outDir); + + if (zip) { + const archive = new JSZip(); + await addDir(archive, outDir, ""); + const zipPath = join(outRoot, `makespdf-${target}-${pkg.version}.zip`); + await writeFile(zipPath, await archive.generateAsync({ type: "nodebuffer", compression: "DEFLATE" })); + written.push(zipPath); + } + } + + return written; +} + +// Run only when invoked directly, so tests can import buildAll. +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const written = await buildAll({ zip: true }); + for (const path of written) console.log(`built ${path}`); +} diff --git a/scripts/manifest.mjs b/scripts/manifest.mjs new file mode 100644 index 0000000..5e457a3 --- /dev/null +++ b/scripts/manifest.mjs @@ -0,0 +1,76 @@ +/** + * Manifest composition for the two packages this build produces. + * + * Shared by `scripts/build.mjs` and the unit tests, so the invariants the + * tests pin (service worker vs. event page, the Gecko id) are the same ones + * the build writes. + */ + +/** The build targets, in build order. */ +export const TARGETS = ["chromium", "firefox"]; + +/** + * Fields both packages share. The `version` is filled from package.json at + * build time; `background` and (for Firefox) `browser_specific_settings` are + * target-specific and added by `manifestFor`. + * + * Permissions stay minimal for the MVP: + * - `storage`: the options page (API key, page size, theme). + * - content script on github.com: the adapter's page. + * - host permission for makespdf.com: the render POST from the background. + * No ``, no `downloads`: the PDF is saved with an object-URL anchor. + */ +export const BASE_MANIFEST = { + manifest_version: 3, + name: "makesPDF — Markdown to PDF", + description: + "Download GitHub Markdown files as PDF with makesPDF. Renders READMEs and .md files with images intact.", + permissions: ["storage"], + host_permissions: ["https://makespdf.com/*"], + content_scripts: [ + { + matches: ["https://github.com/*"], + js: ["content.js"], + run_at: "document_idle", + }, + ], + options_ui: { + page: "options/options.html", + open_in_tab: true, + }, + action: { + default_title: "makesPDF options", + }, +}; + +/** + * The manifest for one target. + * + * Chrome runs the background as a module service worker; Firefox does not + * support `background.service_worker` and uses a module event page instead + * (Firefox 111+; `strict_min_version` pins the floor). Firefox also needs a + * stable extension id for storage and updates. + */ +export function manifestFor(target, version) { + if (target === "chromium") { + return { + ...BASE_MANIFEST, + version, + background: { service_worker: "background.js", type: "module" }, + }; + } + if (target === "firefox") { + return { + ...BASE_MANIFEST, + version, + background: { scripts: ["background.js"], type: "module" }, + browser_specific_settings: { + gecko: { + id: "browser-extension@makespdf.com", + strict_min_version: "115.0", + }, + }, + }; + } + throw new Error(`unknown build target: ${target}`); +} diff --git a/scripts/verify-packages.mjs b/scripts/verify-packages.mjs new file mode 100644 index 0000000..517ecb1 --- /dev/null +++ b/scripts/verify-packages.mjs @@ -0,0 +1,84 @@ +/** + * Structural verification of a built dist/ tree: node scripts/verify-packages.mjs + * + * This is the "loadable package" gate for CI. It cannot open a browser, so it + * checks the next best thing: every file the manifests reference exists, the + * two manifests differ the way each browser's MV3 requires, and the built + * background bundle carries that package's `X-MakesPDF-Client` value. + */ + +import { readFile, stat } from "node:fs/promises"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { TARGETS, manifestFor } from "./manifest.mjs"; + +const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), ".."); + +const failures = []; +function check(condition, message) { + if (condition) console.log(` ok ${message}`); + else { + failures.push(message); + console.error(` FAIL ${message}`); + } +} + +async function exists(path) { + try { + await stat(path); + return true; + } catch { + return false; + } +} + +const pkg = JSON.parse(await readFile(join(ROOT, "package.json"), "utf8")); +const outRoot = join(ROOT, "dist"); + +for (const target of TARGETS) { + const dir = join(outRoot, target); + console.log(`\n${target}:`); + check(await exists(dir), `${target} package directory exists`); + + const manifest = JSON.parse(await readFile(join(dir, "manifest.json"), "utf8")); + const expected = manifestFor(target, pkg.version); + check(manifest.manifest_version === 3, "manifest is MV3"); + check(manifest.version === pkg.version, `manifest version is ${pkg.version}`); + check( + JSON.stringify(manifest.background) === JSON.stringify(expected.background), + `background matches target (${JSON.stringify(expected.background)})`, + ); + check( + manifest.content_scripts?.[0]?.matches?.includes("https://github.com/*"), + "content script matches github.com", + ); + check(manifest.permissions?.includes("storage"), "storage permission present"); + check( + manifest.host_permissions?.includes("https://makespdf.com/*"), + "makespdf.com host permission present", + ); + check(!JSON.stringify(manifest).includes("all_urls"), "no "); + + if (target === "firefox") { + check(manifest.browser_specific_settings?.gecko?.id, "firefox has a Gecko id"); + } else { + check(!manifest.browser_specific_settings, "chromium has no browser_specific_settings"); + } + + for (const file of ["content.js", "background.js", "options/options.html", "options/options.js", "options/options.css"]) { + check(await exists(join(dir, file)), `${file} exists`); + } + + const background = await readFile(join(dir, "background.js"), "utf8"); + const header = `browser-extension/${pkg.version}+${target}`; + check(background.includes(header), `background bundle carries "${header}"`); + + const content = await readFile(join(dir, "content.js"), "utf8"); + check(!content.includes("__BUILD_TARGET__"), "content bundle has no unresolved __BUILD_TARGET__"); +} + +if (failures.length > 0) { + console.error(`\n${failures.length} check(s) failed`); + process.exit(1); +} +console.log("\nAll package checks passed."); diff --git a/src/adapters/github.ts b/src/adapters/github.ts new file mode 100644 index 0000000..4a7fb94 --- /dev/null +++ b/src/adapters/github.ts @@ -0,0 +1,150 @@ +/** + * The GitHub adapter: the first (and for the MVP, only) Markdown source. + * + * The Markdown fetch and every image fetch run in the content script with + * `credentials: "same-origin"`, so the page's cookies ride along — that is + * what makes private repositories work. The raw route 302s to a tokenized + * raw.githubusercontent.com URL; the fetch follows it (raw.githubusercontent.com + * sends `access-control-allow-origin: *`, verified), and the token in the URL + * carries authorization for private repos. + */ + +import { AssetError, MarkdownFetchError } from "../lib/assets"; +import { base64FromBytes } from "../lib/bytes"; +import { injectDownloadButton } from "../lib/button"; +import { + matchGitHubMarkdown, + sanitizeFilename, + type GitHubMarkdownTarget, +} from "../lib/github-url"; +import { MAX_IMAGE_BYTES } from "../lib/markdown-images"; +import { pickImageMime } from "../lib/mime"; +import type { AdapterContext, AdapterFactory, MarkdownAdapter } from "./types"; + +const FETCH_TIMEOUT_MS = 15_000; + +export class GitHubMarkdownAdapter implements MarkdownAdapter { + private readonly target: GitHubMarkdownTarget; + private readonly document: Document; + private readonly fetchImpl: typeof fetch; + + constructor(target: GitHubMarkdownTarget, context: Pick) { + this.target = target; + this.document = context.document; + this.fetchImpl = context.fetchImpl; + } + + matches(url: URL): boolean { + return matchGitHubMarkdown(url) !== null; + } + + /** + * Fetch the raw Markdown through the page's session. Never scrapes the + * rendered page. The repo home tries README.md then README.markdown; a blob + * view fetches its own raw URL (which works for any ref, including tags and + * SHAs, and for refs containing slashes — GitHub resolves them server-side). + */ + async getMarkdown(): Promise { + const urls = + this.target.kind === "home" + ? [this.target.rawUrl, this.target.rawUrl.replace(/README\.md$/i, "README.markdown")] + : [this.target.rawUrl]; + + for (const url of urls) { + const response = await this.fetchWithTimeout(url); + if (response.ok) return await response.text(); + if (response.status !== 404) { + throw new MarkdownFetchError(`GitHub returned HTTP ${response.status} for this file. Reload the page and try again.`); + } + } + throw new MarkdownFetchError( + this.target.kind === "home" + ? "No README.md was found in this repository." + : "The file could not be fetched from GitHub (HTTP 404).", + ); + } + + /** + * Fetch one relative reference through the page's session and return it as + * a `data:` URI. Leading "/" is repository-root-relative; everything else is + * resolved against the source file's directory (`..`, `./`, nested dirs). + */ + async resolveAsset(relativePath: string): Promise { + const base = relativePath.startsWith("/") ? this.target.rootRawDirUrl : this.target.rawDirUrl; + const relative = relativePath.replace(/^\/+/, ""); + + let resolved: URL; + try { + resolved = new URL(relative, base); + } catch { + throw new AssetError("is not a valid path", relativePath); + } + resolved.search = ""; + resolved.hash = ""; + if (!this.isInsideRepository(resolved)) { + throw new AssetError("points outside the repository", relativePath); + } + + let response: Response; + try { + response = await this.fetchWithTimeout(resolved.toString()); + } catch { + throw new AssetError("could not be fetched", relativePath); + } + if (!response.ok) { + throw new AssetError(`could not be fetched (HTTP ${response.status})`, relativePath); + } + + // Refuse before downloading when the server declares an oversized file. + const declared = Number(response.headers.get("content-length")); + if (Number.isFinite(declared) && declared > MAX_IMAGE_BYTES) { + throw new AssetError("too large to embed, max 5MB", relativePath); + } + const bytes = new Uint8Array(await response.arrayBuffer()); + if (bytes.byteLength > MAX_IMAGE_BYTES) { + throw new AssetError("too large to embed, max 5MB", relativePath); + } + + const mime = pickImageMime(response.headers.get("content-type"), resolved.pathname); + if (!mime) { + throw new AssetError("is not an image", relativePath); + } + return `data:${mime};base64,${base64FromBytes(bytes)}`; + } + + injectButton(onClick: () => void): boolean { + return injectDownloadButton(this.document, this.target, onClick); + } + + suggestedFilename(): string { + return sanitizeFilename(this.target.filename); + } + + private isInsideRepository(resolved: URL): boolean { + return ( + resolved.protocol === "https:" && + resolved.hostname === "github.com" && + resolved.pathname.startsWith(`/${this.target.owner}/${this.target.repo}/raw/`) + ); + } + + private async fetchWithTimeout(url: string): Promise { + return await this.fetchImpl(url, { + credentials: "same-origin", + redirect: "follow", + signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), + }); + } +} + +export const githubAdapterFactory: AdapterFactory = { + id: "github", + matches(url: URL): boolean { + return matchGitHubMarkdown(url) !== null; + }, + create(context: AdapterContext): MarkdownAdapter { + const target = matchGitHubMarkdown(context.url); + if (!target) throw new Error("github adapter created for a non-matching URL"); + return new GitHubMarkdownAdapter(target, context); + }, +}; diff --git a/src/adapters/registry.ts b/src/adapters/registry.ts new file mode 100644 index 0000000..1caf2b0 --- /dev/null +++ b/src/adapters/registry.ts @@ -0,0 +1,15 @@ +/** + * The adapter registry: first factory whose `matches` accepts the URL wins. + * MAK-197's later adapters are additive here — nothing else changes. + */ + +import { githubAdapterFactory } from "./github"; +import type { AdapterContext, AdapterFactory, MarkdownAdapter } from "./types"; + +export const ADAPTER_FACTORIES: readonly AdapterFactory[] = [githubAdapterFactory]; + +/** The adapter for a page, or null when no factory matches. */ +export function findAdapter(context: AdapterContext): MarkdownAdapter | null { + const factory = ADAPTER_FACTORIES.find((candidate) => candidate.matches(context.url)); + return factory ? factory.create(context) : null; +} diff --git a/src/adapters/types.ts b/src/adapters/types.ts new file mode 100644 index 0000000..428671b --- /dev/null +++ b/src/adapters/types.ts @@ -0,0 +1,37 @@ +/** + * The per-page adapter interface. MAK-197 adds further adapters (GitLab, + * Bitbucket, ...) as additive factories over this same shape: URL matching, + * Markdown source, asset resolution, button injection, filename. + */ + +export interface AdapterContext { + /** The page URL the adapter was created for. */ + url: URL; + /** The page document, for button injection. */ + document: Document; + /** `fetch` bound to the page's session; injected for tests. */ + fetchImpl: typeof fetch; +} + +export interface MarkdownAdapter { + /** Whether this adapter serves `url`. */ + matches(url: URL): boolean; + /** The page's Markdown source, fetched through the user's session. */ + getMarkdown(): Promise; + /** + * Resolve one relative asset reference to an embeddable data URI, e.g. a + * `data:image/png;base64,…` string. Rejects with `AssetError` when the + * asset cannot be embedded (fetch failure, size, content type). + */ + resolveAsset(relativePath: string): Promise; + /** Inject the adapter's call-to-action; false when the page has no home for it yet. */ + injectButton(onClick: () => void): boolean; + /** The filename the rendered PDF should be saved as. */ + suggestedFilename(): string; +} + +export interface AdapterFactory { + readonly id: string; + matches(url: URL): boolean; + create(context: AdapterContext): MarkdownAdapter; +} diff --git a/src/background.ts b/src/background.ts new file mode 100644 index 0000000..9ff2868 --- /dev/null +++ b/src/background.ts @@ -0,0 +1,42 @@ +/** + * Background entry: the render POST lives here (extension origin + host + * permission), and the toolbar button opens the options page. The logic lives + * in lib/render-client.ts so it can be unit tested without a browser. + */ + +import browser from "webextension-polyfill"; +import { CLIENT_HEADER } from "./lib/build-target"; +import { RENDER_MESSAGE_TYPE, type RenderRequest } from "./lib/messages"; +import { renderMarkdown, type StoredDefaults } from "./lib/render-client"; + +function isRenderRequest(message: unknown): message is RenderRequest { + return ( + typeof message === "object" && + message !== null && + (message as { type?: unknown }).type === RENDER_MESSAGE_TYPE + ); +} + +browser.runtime.onMessage.addListener((message: unknown) => { + if (!isRenderRequest(message)) return undefined; + return renderMarkdown(message, { + fetchImpl: fetch, + clientHeaderValue: CLIENT_HEADER, + getApiKey: async () => { + const stored = await browser.storage.local.get("apiKey"); + const key: unknown = stored.apiKey; + return typeof key === "string" && key.trim().length > 0 ? key.trim() : null; + }, + getStoredDefaults: async (): Promise => { + const stored = await browser.storage.local.get(["pageSize", "theme"]); + const defaults: StoredDefaults = {}; + if (typeof stored.pageSize === "string" && stored.pageSize) defaults.pageSize = stored.pageSize; + if (typeof stored.theme === "string" && stored.theme) defaults.theme = stored.theme; + return defaults; + }, + }); +}); + +browser.action.onClicked.addListener(() => { + void browser.runtime.openOptionsPage(); +}); diff --git a/src/content.ts b/src/content.ts new file mode 100644 index 0000000..30dd6b1 --- /dev/null +++ b/src/content.ts @@ -0,0 +1,16 @@ +/** + * Content script entry: runs on github.com pages and wires the page + * controller. All the logic lives in lib/controller.ts so it can be unit + * tested with jsdom. + */ + +import browser from "webextension-polyfill"; +import { startController } from "./lib/controller"; +import type { RenderRequest, RenderResponse } from "./lib/messages"; + +startController({ + document, + location: window.location, + sendMessage: (request: RenderRequest) => + browser.runtime.sendMessage(request) as Promise, +}); diff --git a/src/lib/assets.ts b/src/lib/assets.ts new file mode 100644 index 0000000..1bfb45b --- /dev/null +++ b/src/lib/assets.ts @@ -0,0 +1,22 @@ +/** Thrown when a page's Markdown source itself cannot be fetched. */ +export class MarkdownFetchError extends Error { + constructor(message: string) { + super(message); + this.name = "MarkdownFetchError"; + } +} + +/** The standard error an adapter throws when a referenced asset cannot be embedded. */ +export class AssetError extends Error { + /** Short reason shown to the user, e.g. "could not be fetched (HTTP 404)". */ + readonly reason: string; + /** The reference as written in the document. */ + readonly src: string; + + constructor(reason: string, src: string) { + super(`${src}: ${reason}`); + this.name = "AssetError"; + this.reason = reason; + this.src = src; + } +} diff --git a/src/lib/build-target.ts b/src/lib/build-target.ts new file mode 100644 index 0000000..f98120d --- /dev/null +++ b/src/lib/build-target.ts @@ -0,0 +1,55 @@ +/** + * The build target a package was built for. + * + * `__BUILD_TARGET__` is replaced at build time by esbuild (`define` in + * `scripts/build.mjs`); under vitest it is undefined and the fallback keeps + * module imports safe. The target is what labels the `X-MakesPDF-Client` + * header — `chromium` for the Chrome/Edge/Brave package, `firefox` for the + * Firefox package (operator decision 2026-10-09: label by build, not brand). + */ + +export type BuildTarget = "chromium" | "firefox"; + +declare const __BUILD_TARGET__: BuildTarget | undefined; +declare const __EXTENSION_VERSION__: string | undefined; + +// `typeof` on a declare-only identifier is safe when esbuild's define did not +// replace it (tests): it evaluates to the string "undefined". +function readBuildTarget(): BuildTarget { + return typeof __BUILD_TARGET__ === "string" ? __BUILD_TARGET__ : "chromium"; +} + +function readExtensionVersion(): string { + return typeof __EXTENSION_VERSION__ === "string" ? __EXTENSION_VERSION__ : "0.0.0"; +} + +export const BUILD_TARGET: BuildTarget = readBuildTarget(); + +/** + * The extension version this bundle was built from (package.json, via the + * build's `define`; the same value the manifest carries). + */ +export const EXTENSION_VERSION: string = readExtensionVersion(); + +/** + * The `X-MakesPDF-Client` value for one build: + * `browser-extension/+`. `inferClient` on the server accepts + * the `+` in the version pattern and buckets the kind as `browser-extension` + * (operator decision 2026-10-09: label by build, not brand). + * + * The build's `define`s are spelled inline — not via the `EXTENSION_VERSION` / + * `BUILD_TARGET` consts — so esbuild folds the concatenation into the exact + * header literal, and each package's bundle can be checked for it by + * `scripts/verify-packages.mjs` and the build-output test. In the test + * environment (no defines) the condition is false and the sensible fallback + * exercises the same `clientHeader` format. + */ +export const CLIENT_HEADER: string = + typeof __EXTENSION_VERSION__ === "string" && typeof __BUILD_TARGET__ === "string" + ? "browser-extension/" + __EXTENSION_VERSION__ + "+" + __BUILD_TARGET__ + : clientHeader("0.0.0", "chromium"); + +/** The header format; the build substitutes it inline above. */ +export function clientHeader(version: string, build: BuildTarget): string { + return "browser-extension/" + version + "+" + build; +} diff --git a/src/lib/button.ts b/src/lib/button.ts new file mode 100644 index 0000000..92e1fdd --- /dev/null +++ b/src/lib/button.ts @@ -0,0 +1,154 @@ +/** + * The injected "Download PDF" button and its status line. + * + * Injection is idempotent by element id — the controller checks before calling + * and this module removes any existing instance first, so a soft navigation + * can never leave two buttons. On blob views the button sits in the file + * header beside GitHub's Raw link; on a repo home page (no header to join) it + * floats bottom-right. All styling is inline, so GitHub's CSS cannot restyle + * it and the extension ships no stylesheet for the page. + */ + +import type { GitHubMarkdownTarget } from "./github-url"; + +export const BUTTON_ID = "makespdf-download-pdf-button"; +export const STATUS_ID = "makespdf-download-pdf-status"; +export const FLOATING_HOST_ID = "makespdf-download-pdf-host"; + +const BUTTON_TEXT = "Download PDF"; + +const BUTTON_STYLE = [ + "font: 600 12px/20px -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Noto Sans', Helvetica, Arial, sans-serif", + "color: #24292f", + "background-color: #f6f8fa", + "border: 1px solid rgba(31, 35, 40, 0.15)", + "border-radius: 6px", + "padding: 3px 12px", + "cursor: pointer", + "margin-right: 8px", + "white-space: nowrap", +].join(";"); + +const STATUS_STYLE = [ + "font: 400 12px/20px -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Noto Sans', Helvetica, Arial, sans-serif", + "color: #57606a", + "margin-right: 8px", + "max-width: 480px", +].join(";"); + +const FLOATING_STYLE = [ + "position: fixed", + "right: 24px", + "bottom: 24px", + "z-index: 2147483647", + "display: flex", + "align-items: center", + "gap: 8px", + "background: #ffffff", + "border: 1px solid rgba(31, 35, 40, 0.15)", + "border-radius: 8px", + "padding: 6px 8px", + "box-shadow: 0 2px 8px rgba(31, 35, 40, 0.15)", +].join(";"); + +export type ButtonState = "idle" | "busy" | "ok" | "error"; + +/** Remove every element this extension injected into the page. */ +export function removeInjected(doc: Document): void { + for (const id of [BUTTON_ID, STATUS_ID, FLOATING_HOST_ID]) { + doc.getElementById(id)?.remove(); + } +} + +interface InsertionPoint { + parent: Element; + before: Node | null; +} + +/** The header container to join, or null when the page offers none. */ +function findBlobHost(doc: Document): InsertionPoint | null { + const raw = findRawLink(doc); + if (!raw) return null; + // New React blob UI: the Raw link sits in a ButtonGroup; join the group's + // parent so we render as a sibling of the group, not inside it. + const group = raw.closest('[data-component="ButtonGroup"]'); + if (group?.parentElement) return { parent: group.parentElement, before: group }; + const actions = raw.closest(".react-blob-header-edit-and-raw-actions"); + if (actions) return { parent: actions, before: actions.firstChild }; + return raw.parentElement ? { parent: raw.parentElement, before: raw } : null; +} + +/** GitHub's Raw link for the current file, across old and new blob UIs. */ +function findRawLink(doc: Document): HTMLAnchorElement | null { + const candidates = doc.querySelectorAll( + 'a[data-testid="raw-button"], a#raw-url, a[href*="/raw/"]', + ); + for (const anchor of candidates) { + const attribute = anchor.getAttribute("href") ?? ""; + if (/^\/[^/]+\/[^/]+\/raw\//.test(attribute)) return anchor; + if (/^https:\/\/github\.com\/[^/]+\/[^/]+\/raw\//.test(anchor.href)) return anchor; + } + return null; +} + +/** Whether a README is rendered on this page (repo home). */ +function hasRenderedReadme(doc: Document): boolean { + return doc.querySelector('#readme, [data-testid="readme"], .markdown-body') !== null; +} + +/** + * Inject the button for `target`, bound to `onClick`. Returns false when the + * page has no sensible home for it yet (repo home before the README renders) — + * the controller retries on the next DOM change. + */ +export function injectDownloadButton( + doc: Document, + target: GitHubMarkdownTarget, + onClick: () => void, +): boolean { + removeInjected(doc); + + const button = doc.createElement("button"); + button.id = BUTTON_ID; + button.type = "button"; + button.textContent = BUTTON_TEXT; + button.style.cssText = BUTTON_STYLE; + button.addEventListener("click", onClick); + + const status = doc.createElement("span"); + status.id = STATUS_ID; + status.setAttribute("role", "status"); + status.setAttribute("aria-live", "polite"); + status.style.cssText = STATUS_STYLE; + + const host = findBlobHost(doc); + if (host) { + host.parent.insertBefore(button, host.before); + host.parent.insertBefore(status, host.before); + return true; + } + + // Repo home (or a blob view whose header is not rendered yet): float. + if (target.kind === "home" && !hasRenderedReadme(doc)) return false; + const floating = doc.createElement("div"); + floating.id = FLOATING_HOST_ID; + floating.style.cssText = FLOATING_STYLE; + floating.append(status, button); + (doc.body ?? doc.documentElement).appendChild(floating); + return true; +} + +/** Update the button and status line for a state change. */ +export function renderButtonState(doc: Document, state: ButtonState, message?: string): void { + const button = doc.getElementById(BUTTON_ID); + if (button instanceof HTMLButtonElement) { + button.disabled = state === "busy"; + button.textContent = state === "busy" ? "Rendering PDF…" : BUTTON_TEXT; + button.style.opacity = state === "busy" ? "0.6" : "1"; + } + const status = doc.getElementById(STATUS_ID); + if (status) { + status.textContent = message ?? ""; + status.style.color = state === "error" ? "#cf222e" : state === "ok" ? "#1a7f37" : "#57606a"; + } +} diff --git a/src/lib/bytes.ts b/src/lib/bytes.ts new file mode 100644 index 0000000..f276989 --- /dev/null +++ b/src/lib/bytes.ts @@ -0,0 +1,19 @@ +/** Base64 ↔ bytes helpers usable in service workers and content scripts alike. */ + +/** Encode bytes as base64, chunked so large payloads don't blow the call stack. */ +export function base64FromBytes(bytes: Uint8Array): string { + let binary = ""; + const CHUNK = 0x8000; + for (let i = 0; i < bytes.length; i += CHUNK) { + binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK)); + } + return btoa(binary); +} + +/** Decode base64 (as produced by `base64FromBytes`) back to bytes. */ +export function bytesFromBase64(base64: string): Uint8Array { + const binary = atob(base64); + const bytes = new Uint8Array(new ArrayBuffer(binary.length)); + for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); + return bytes; +} diff --git a/src/lib/controller.ts b/src/lib/controller.ts new file mode 100644 index 0000000..abb6294 --- /dev/null +++ b/src/lib/controller.ts @@ -0,0 +1,146 @@ +/** + * The page controller: watches for GitHub's soft navigations, keeps exactly + * one injected button bound to the current page, and runs the export. + * + * GitHub is a Turbo app: the URL changes without a page load and the content + * area is replaced wholesale. Rather than patching `history` (a content + * script's patch does not intercept the page's calls), the controller listens + * for Turbo's own events and re-checks on DOM mutations and a coarse interval. + * Every check is cheap and idempotent: at most one button exists, and it is + * replaced when it belongs to a previous URL. + */ + +import { findAdapter } from "../adapters/registry"; +import { MarkdownFetchError } from "./assets"; +import { BUTTON_ID, removeInjected, renderButtonState } from "./button"; +import { downloadBase64Pdf, suggestedTitleFromFilename } from "./download"; +import { matchGitHubMarkdown } from "./github-url"; +import { prepareExportMarkdown } from "./markdown-images"; +import { RENDER_MESSAGE_TYPE, type RenderRequest, type RenderResponse } from "./messages"; + +/** How often the URL is re-checked even without a DOM mutation. */ +const POLL_INTERVAL_MS = 1_500; + +/** Mutation bursts are coalesced before re-checking. */ +const MUTATION_DEBOUNCE_MS = 150; + +export interface ControllerOptions { + document: Document; + location: Location; + /** Sends the render request to the background; injected for tests. */ + sendMessage: (request: RenderRequest) => Promise; + /** Page-session fetch; defaults to the global fetch. */ + fetchImpl?: typeof fetch; +} + +/** + * Wire the controller up. Returns a cleanup function that removes listeners + * and the injected UI (used by tests; the content script runs for the page's + * lifetime). + */ +export function startController(options: ControllerOptions): () => void { + const doc = options.document; + const fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis); + let busy = false; + let buttonHref: string | null = null; + let debounce: ReturnType | null = null; + + const runExport = async (onClickAdapter: NonNullable>): Promise => { + if (busy) return; + busy = true; + renderButtonState(doc, "busy"); + try { + const markdown = await onClickAdapter.getMarkdown(); + const prepared = await prepareExportMarkdown(markdown, (src) => onClickAdapter.resolveAsset(src)); + if (!prepared.ok) { + renderButtonState(doc, "error", prepared.message); + return; + } + + const filename = onClickAdapter.suggestedFilename(); + const response = await options.sendMessage({ + type: RENDER_MESSAGE_TYPE, + markdown: prepared.markdown, + title: suggestedTitleFromFilename(filename), + filename, + }); + if (!response.ok) { + renderButtonState(doc, "error", response.message); + return; + } + + downloadBase64Pdf(response.base64, response.filename, doc); + renderButtonState(doc, "ok", `Saved ${response.filename}`); + } catch (error) { + renderButtonState( + doc, + "error", + error instanceof MarkdownFetchError + ? error.message + : "Could not fetch the Markdown source from GitHub. Reload the page and try again.", + ); + } finally { + busy = false; + } + }; + + const sync = (): void => { + const href = options.location.href; + let url: URL | null = null; + try { + url = new URL(href); + } catch { + url = null; + } + if (!url || matchGitHubMarkdown(url) === null) { + removeInjected(doc); + buttonHref = null; + return; + } + + if (doc.getElementById(BUTTON_ID)) { + if (buttonHref === href) return; // the button already belongs to this URL + // A soft navigation kept the header element: the old handler closes over + // the previous page's target. Replace it. + removeInjected(doc); + buttonHref = null; + } + + const adapter = findAdapter({ url, document: doc, fetchImpl }); + if (!adapter) return; + if (adapter.injectButton(() => void runExport(adapter))) buttonHref = href; + }; + + const schedule = (): void => { + if (debounce !== null) return; + debounce = setTimeout(() => { + debounce = null; + sync(); + }, MUTATION_DEBOUNCE_MS); + }; + + const onNavigationEvent = (): void => schedule(); + const onPageShow = (): void => sync(); + + doc.addEventListener("turbo:load", onNavigationEvent); + doc.addEventListener("turbo:render", onNavigationEvent); + doc.addEventListener("pjax:end", onNavigationEvent); + globalThis.addEventListener?.("pageshow", onPageShow); + const observer = new MutationObserver(schedule); + observer.observe(doc.documentElement, { childList: true, subtree: true }); + const interval = setInterval(sync, POLL_INTERVAL_MS); + + sync(); + + return () => { + doc.removeEventListener("turbo:load", onNavigationEvent); + doc.removeEventListener("turbo:render", onNavigationEvent); + doc.removeEventListener("pjax:end", onNavigationEvent); + globalThis.removeEventListener?.("pageshow", onPageShow); + observer.disconnect(); + clearInterval(interval); + if (debounce !== null) clearTimeout(debounce); + removeInjected(doc); + buttonHref = null; + }; +} diff --git a/src/lib/download.ts b/src/lib/download.ts new file mode 100644 index 0000000..91f8325 --- /dev/null +++ b/src/lib/download.ts @@ -0,0 +1,32 @@ +/** + * Save the rendered PDF with an object-URL anchor. + * + * An anchor needs no `downloads` permission (and works identically in Chrome + * and Firefox), which keeps the MVP's permission set minimal. The blob URL is + * revoked on a delay: revoking immediately can cancel the download in some + * browsers. + */ + +import { bytesFromBase64 } from "./bytes"; +import { sanitizeFilename } from "./github-url"; + +/** The document title for `/md` options: the suggested filename without ".pdf". */ +export function suggestedTitleFromFilename(filename: string): string { + return filename.replace(/\.pdf$/i, ""); +} + +export function downloadBase64Pdf(base64: string, filename: string, doc: Document): void { + const bytes = bytesFromBase64(base64); + const blob = new Blob([bytes], { type: "application/pdf" }); + const url = URL.createObjectURL(blob); + + const anchor = doc.createElement("a"); + anchor.href = url; + anchor.download = sanitizeFilename(filename); + anchor.style.display = "none"; + (doc.body ?? doc.documentElement).appendChild(anchor); + anchor.click(); + anchor.remove(); + + setTimeout(() => URL.revokeObjectURL(url), 60_000); +} diff --git a/src/lib/errors.ts b/src/lib/errors.ts new file mode 100644 index 0000000..6d4f7d7 --- /dev/null +++ b/src/lib/errors.ts @@ -0,0 +1,140 @@ +/** + * Map a failed `/api/v1/md` response onto a user-facing message. + * + * Wording follows the VS Code and Zed clients (MAK-191's precedent): a saved + * key that fails is the user's to fix, anonymous 401s point at sign-up, 429 + * carries the server's tip (which names both upgrade paths) and a sign-up + * hint when the server sent none, and 400/413 surface the server's own + * wording rather than inventing a substitute. + */ + +import { SIGNUP_URL } from "./service"; + +export type RenderErrorKind = + | "auth" + | "rate-limit" + | "bad-request" + | "payload-too-large" + | "server" + | "network" + | "unknown"; + +export interface MappedError { + kind: RenderErrorKind; + message: string; +} + +interface ErrorBody { + error?: unknown; + details?: unknown; + hint?: unknown; + tip?: unknown; + limit?: unknown; + actual?: unknown; +} + +const asString = (value: unknown): string | undefined => + typeof value === "string" && value.trim().length > 0 ? value : undefined; + +const asNumber = (value: unknown): number | undefined => + typeof value === "number" && Number.isFinite(value) ? value : undefined; + +/** Parse an error body without ever throwing; `{}` for anything unreadable. */ +export function parseErrorBody(text: string): ErrorBody { + try { + const parsed: unknown = JSON.parse(text); + return parsed !== null && typeof parsed === "object" ? (parsed as ErrorBody) : {}; + } catch { + return {}; + } +} + +export interface ErrorMapOptions { + /** Whether the request carried a user-configured API key. */ + hasKey: boolean; +} + +export function mapHttpError(status: number, bodyText: string, options: ErrorMapOptions): MappedError { + const body = parseErrorBody(bodyText); + + if (status === 401 || status === 403) { + if (options.hasKey) { + return { + kind: "auth", + message: "Authentication failed. Check the API key in the makesPDF extension options.", + }; + } + return { + kind: "auth", + message: + `This server requires an account. Create one at ${SIGNUP_URL} ` + + "and save your API key in the extension options.", + }; + } + + if (status === 429) { + const tip = asString(body.tip); + if (tip) return { kind: "rate-limit", message: `Rate limited. ${tip}` }; + return { + kind: "rate-limit", + message: options.hasKey + ? "Rate limited. Wait a few minutes and try again." + : `Rate limited. Wait a few minutes and try again, or sign up at ${SIGNUP_URL} for higher limits.`, + }; + } + + if (status === 400) { + const code = asString(body.error); + if (code === "page-cap-exceeded") { + const limit = asNumber(body.limit); + const actual = asNumber(body.actual); + return { + kind: "bad-request", + message: + `Document is too long for an anonymous render (${actual ?? "many"} pages, ` + + `cap ${limit ?? "the anonymous cap"}). Sign up for higher limits.`, + }; + } + const details = Array.isArray(body.details) ? body.details.filter((d): d is string => typeof d === "string") : []; + return { + kind: "bad-request", + message: `makesPDF rejected the document: ${code ?? details[0] ?? "Bad request"}`, + }; + } + + if (status === 413) { + const code = asString(body.error); + return { + kind: "payload-too-large", + message: + `makesPDF rejected the document: ${code ?? "Payload too large"}. ` + + "Remove some images or split the file and try again.", + }; + } + + if (status >= 500) { + const code = asString(body.error); + return { + kind: "server", + message: `makesPDF returned an error (HTTP ${status})${code ? `: ${code}` : ""}. Try again in a moment.`, + }; + } + + const code = asString(body.error) ?? bodyText.trim(); + return { + kind: "unknown", + message: `makesPDF request failed (HTTP ${status})${code ? `: ${code.slice(0, 200)}` : ""}.`, + }; +} + +/** Map a thrown fetch/network error onto the same shape. */ +export function mapFetchError(error: unknown): MappedError { + const name = error instanceof Error ? error.name : ""; + if (name === "TimeoutError" || name === "AbortError") { + return { kind: "network", message: "makesPDF did not respond in time. Try again." }; + } + return { + kind: "network", + message: "Could not reach makesPDF. Check your connection and try again.", + }; +} diff --git a/src/lib/github-url.ts b/src/lib/github-url.ts new file mode 100644 index 0000000..9b2c4e1 --- /dev/null +++ b/src/lib/github-url.ts @@ -0,0 +1,165 @@ +/** + * URL matching for GitHub Markdown views, and the raw URLs derived from them. + * + * Two shapes are supported: + * - blob file views https://github.com///blob//.md + * - repo home README https://github.com// + * + * The Markdown source is never scraped from the rendered page: the raw URL is + * derived from the page URL by swapping `/blob/` for `/raw/`, which GitHub + * resolves server-side — including for refs that contain `/`, which a client + * cannot split from the file path reliably. `rawDirUrl` is the same URL + * truncated to the file's directory, used as the base for relative images. + */ + +export interface GitHubMarkdownTarget { + kind: "blob" | "home"; + owner: string; + repo: string; + /** Absolute https URL the Markdown source is fetched from. */ + rawUrl: string; + /** Raw URL of the source file's directory, ending in "/" — base for relative assets. */ + rawDirUrl: string; + /** + * Repo-root raw URL at the same revision, ending in "/" — base for + * `/`-rooted asset paths. Best effort: the revision is taken as the first + * path segment after `/blob/`, which is wrong only for slash-containing + * refs combined with root-relative image paths. + */ + rootRawDirUrl: string; + /** Suggested download filename, e.g. "README.pdf". */ + filename: string; +} + +/** + * Paths that can appear at the first two segments of a github.com URL without + * the first being a repository owner. Not an allow-list opportunity — GitHub + * owns new top-level routes over time — but it keeps the button off Settings, + * Explore and friends. + */ +const RESERVED_FIRST_SEGMENTS = new Set([ + "about", + "account", + "apps", + "codespaces", + "collections", + "contact", + "customer-stories", + "dashboard", + "discussions", + "enterprise", + "explore", + "features", + "gist", + "issues", + "join", + "login", + "logout", + "manifest.json", + "marketplace", + "new", + "notifications", + "organizations", + "orgs", + "pricing", + "pulls", + "readme", + "search", + "security", + "settings", + "signup", + "site", + "sponsors", + "stars", + "team", + "teams", + "topics", + "trending", + "users", + "watching", +]); + +/** Repo names GitHub allows: alphanumerics, `-`, `_`, `.` (not `.`/`..`). */ +function isRepoName(segment: string): boolean { + if (segment === "." || segment === "..") return false; + return /^[A-Za-z0-9._-]+$/.test(segment); +} + +const MARKDOWN_FILE_RE = /\.(?:md|markdown)$/i; + +/** Characters a filename cannot carry across common filesystems/browsers. */ +const UNSAFE_FILENAME_RE = /[\\/:*?"<>|\u0000-\u001f]/g; + +/** A download-safe filename: no separators, no control characters, non-empty. */ +export function sanitizeFilename(name: string): string { + const cleaned = name.replace(UNSAFE_FILENAME_RE, "-").replace(/\s+/g, " ").trim(); + return cleaned.length > 0 ? cleaned : "document.pdf"; +} + +/** The file stem of a markdown file segment, percent-decoded and sanitized. */ +function stemFor(filenameSegment: string): string { + let decoded = filenameSegment; + try { + decoded = decodeURIComponent(filenameSegment); + } catch { + // Malformed escapes: fall back to the raw segment. + } + return sanitizeFilename(decoded.replace(MARKDOWN_FILE_RE, "")); +} + +/** + * Match a github.com URL against the supported Markdown views. Returns the + * target (with raw URLs precomputed) or null when the page has no Markdown + * source this extension can fetch. + */ +export function matchGitHubMarkdown(input: URL | string): GitHubMarkdownTarget | null { + let url: URL; + try { + url = typeof input === "string" ? new URL(input) : input; + } catch { + return null; + } + if (url.protocol !== "https:" || url.hostname !== "github.com") return null; + + const segments = url.pathname.split("/").filter((segment) => segment.length > 0); + if (segments.length < 2) return null; + const owner = segments[0] ?? ""; + const repo = segments[1] ?? ""; + if (RESERVED_FIRST_SEGMENTS.has(owner.toLowerCase())) return null; + if (owner.length === 0 || !isRepoName(repo)) return null; + + const base = `${url.origin}/${owner}/${repo}`; + + // Repo home: the rendered README lives here. HEAD follows the default branch. + if (segments.length === 2) { + return { + kind: "home", + owner, + repo, + rawUrl: `${base}/raw/HEAD/README.md`, + rawDirUrl: `${base}/raw/HEAD/`, + rootRawDirUrl: `${base}/raw/HEAD/`, + filename: `${sanitizeFilename(repo)}.pdf`, + }; + } + + // Blob file view. A trailing slash is a directory (tree) view, not a file. + if (segments[2] !== "blob" || segments.length < 4) return null; + if (url.pathname.endsWith("/")) return null; + const fileSegment = segments[segments.length - 1] ?? ""; + if (!MARKDOWN_FILE_RE.test(fileSegment)) return null; + + const pathAfterBlob = segments.slice(3).join("/"); + const rawUrl = `${base}/raw/${pathAfterBlob}`; + const firstRefSegment = segments[3] ?? ""; + + return { + kind: "blob", + owner, + repo, + rawUrl, + rawDirUrl: rawUrl.slice(0, rawUrl.lastIndexOf("/") + 1), + rootRawDirUrl: `${base}/raw/${firstRefSegment}/`, + filename: `${stemFor(fileSegment)}.pdf`, + }; +} diff --git a/src/lib/markdown-images.ts b/src/lib/markdown-images.ts new file mode 100644 index 0000000..9e4dca9 --- /dev/null +++ b/src/lib/markdown-images.ts @@ -0,0 +1,199 @@ +/** + * Find relative image references in Markdown and inline them as `data:` URIs + * before the export is sent to makesPDF. + * + * Follows the VS Code plugin's MAK-191 precedent: a PDF silently missing an + * image is worse than no PDF, so any reference that cannot be embedded stops + * the export with a message naming the reference(s). References inside fenced + * code blocks and inline code spans are literal text and are never touched. + * + * The server's `/md` image rules are mirrored here: at most 20 images are + * embedded per document and at most 5 MB per image; anything over is a stop, + * not a silent drop. + */ + +import { AssetError } from "./assets"; + +/** The service's per-image cap; a larger asset would be skipped server-side. */ +export const MAX_IMAGE_BYTES = 5 * 1024 * 1024; + +/** The service's per-document image cap (`MAX_IMAGE_COUNT` server-side). */ +export const MAX_IMAGE_COUNT = 20; + +/** At most this many failed references are named; the rest are counted. */ +const MAX_NAMED_FAILURES = 10; + +export interface ImageFailure { + /** The reference as written, minus `<…>` brackets and surrounding space. */ + src: string; + /** Short reason, e.g. "could not be fetched (HTTP 404)". */ + reason: string; +} + +export interface InlineResult { + markdown: string; + /** References that could not be embedded, in document order. */ + failures: ImageFailure[]; +} + +export type PreparedExport = + | { ok: true; markdown: string } + | { ok: false; message: string }; + +// Markdown image: ![alt](src "optional title"). Group 2 is the src (possibly +// wrapped in <…>); group 3 is the optional title with its leading whitespace. +const MD_IMAGE = /!\[([^\]]*)\]\(\s*(<[^>]+>|[^)\s]+)((?:\s+(?:"[^"]*"|'[^']*'))?)\s*\)/g; +// HTML . Group 1 is everything up to and including `src=`, +// group 3/4 is the quoted value (double/single). `[\s/]+` before `src`, not a +// bare `\b`, so `data-src=` is not mistaken for the real attribute. +const HTML_IMAGE_SRC = /(]*?[\s/]+src\s*=\s*)("([^"]*)"|'([^']*)')/gi; + +/** + * Whether a src is a path relative to the repository. Skips anything with a + * URL scheme (http:, https:, data:, mailto:), protocol-relative (`//host/x`) + * and fragment-only refs. Those are left for the server (or the renderer), not + * fetched through the user's session. + */ +export function isRelativeAsset(src: string): boolean { + if (!src) return false; + if (/^[a-z][a-z0-9+.-]+:/i.test(src)) return false; + if (src.startsWith("//") || src.startsWith("#")) return false; + return true; +} + +/** Strip surrounding <…> angle brackets and whitespace from a src token. */ +function cleanSrc(raw: string): string { + const trimmed = raw.trim(); + return trimmed.startsWith("<") && trimmed.endsWith(">") ? trimmed.slice(1, -1).trim() : trimmed; +} + +/** + * Replace fenced code blocks and inline code spans with sentinel tokens so the + * image scan never touches them, returning a `restore` to swap them back in. + */ +function maskCode(input: string): { masked: string; restore: (value: string) => string } { + const stash: string[] = []; + const keep = (match: string) => { + const token = `\u0000CODE${stash.length}\u0000`; + stash.push(match); + return token; + }; + const masked = input + .replace(/```[\s\S]*?```/g, keep) + .replace(/~~~[\s\S]*?~~~/g, keep) + .replace(/``[^`]*``/g, keep) + .replace(/`[^`\n]*`/g, keep); + const restore = (value: string) => + value.replace(/\u0000CODE(\d+)\u0000/g, (_token, index: string) => stash[Number(index)] ?? ""); + return { masked, restore }; +} + +/** All image src tokens in document order, code masked out. */ +function collectRefs(source: string): { masked: string; restore: (value: string) => string; refs: string[] } { + const { masked, restore } = maskCode(source); + const refs: string[] = []; + for (const match of masked.matchAll(MD_IMAGE)) refs.push(cleanSrc(match[2] ?? "")); + for (const match of masked.matchAll(HTML_IMAGE_SRC)) refs.push(cleanSrc(match[3] ?? match[4] ?? "")); + return { masked, restore, refs }; +} + +/** Unique relative image references, in document order. */ +export function findRelativeRefs(source: string): string[] { + const seen = new Set(); + const out: string[] = []; + for (const ref of collectRefs(source).refs) { + if (!ref || !isRelativeAsset(ref) || seen.has(ref)) continue; + seen.add(ref); + out.push(ref); + } + return out; +} + +/** + * Replace relative image references with base64 `data:` URIs produced by + * `resolve`. Rejections carrying an `AssetError` name their reason; anything + * else is reported as "could not be fetched". + */ +export async function inlineRelativeImages( + source: string, + resolve: (src: string) => Promise, +): Promise { + const { masked, restore, refs } = collectRefs(source); + const candidates = findRelativeRefs(source); + + const uris = new Map(); + const failureByRef = new Map(); + await Promise.all( + candidates.map(async (src) => { + try { + uris.set(src, await resolve(src)); + } catch (error) { + failureByRef.set(src, error instanceof AssetError ? error.reason : "could not be fetched"); + } + }), + ); + + const failures: ImageFailure[] = candidates + .filter((src) => failureByRef.has(src)) + .map((src) => ({ src, reason: failureByRef.get(src) ?? "could not be fetched" })); + + if (uris.size === 0) return { markdown: source, failures }; + + let out = masked.replace(MD_IMAGE, (whole, alt: string, url: string, title: string | undefined) => { + const uri = uris.get(cleanSrc(url)); + return uri ? `![${alt}](${uri}${title ?? ""})` : whole; + }); + out = out.replace(HTML_IMAGE_SRC, (whole, prefix: string, _quoted: string, doubleQuoted: string | undefined, singleQuoted: string | undefined) => { + const uri = uris.get(cleanSrc(doubleQuoted ?? singleQuoted ?? "")); + if (!uri) return whole; + const quote = doubleQuoted !== undefined ? '"' : "'"; + return `${prefix}${quote}${uri}${quote}`; + }); + + return { markdown: restore(out), failures }; +} + +/** + * The error that stops an export, or null when every relative image embedded. + * Names each failed reference (up to MAX_NAMED_FAILURES) with its reason. + */ +export function formatImageFailure(failures: ImageFailure[]): string | null { + if (failures.length === 0) return null; + const names = failures + .slice(0, MAX_NAMED_FAILURES) + .map((failure) => `${failure.src} (${failure.reason})`); + const more = failures.length - names.length; + const listed = more > 0 ? `${names.join(", ")} and ${more} more` : names.join(", "); + const one = failures.length === 1; + return ( + `Export stopped, no PDF was written: ${failures.length} ` + + `image${one ? "" : "s"} could not be embedded: ${listed}. ` + + `Fix or remove ${one ? "the reference" : "these references"} and export again.` + ); +} + +/** + * The pre-flight every export runs: enforce the document cap, inline relative + * images, and report a stop message when any could not be embedded. A caller + * with `ok: false` must not send a request: a PDF silently missing an image is + * worse than no PDF. + */ +export async function prepareExportMarkdown( + source: string, + resolve: (src: string) => Promise, +): Promise { + const refs = findRelativeRefs(source); + if (refs.length > MAX_IMAGE_COUNT) { + return { + ok: false, + message: + `Export stopped, no PDF was written: the document references ${refs.length} ` + + `images that must be embedded, but at most ${MAX_IMAGE_COUNT} can be. ` + + "Remove some images and export again.", + }; + } + + const { markdown, failures } = await inlineRelativeImages(source, resolve); + const error = formatImageFailure(failures); + return error ? { ok: false, message: error } : { ok: true, markdown }; +} diff --git a/src/lib/messages.ts b/src/lib/messages.ts new file mode 100644 index 0000000..5ff357b --- /dev/null +++ b/src/lib/messages.ts @@ -0,0 +1,41 @@ +/** + * Shared message shapes between the content script and the background. + * + * The content script assembles the final Markdown (relative images already + * inlined as `data:` URIs) and asks the background to POST it, because only + * the background sits on the extension origin with a `makespdf.com` host + * permission — a content-script fetch would be subject to GitHub's CORS. + */ + +import type { RenderErrorKind } from "./errors"; + +export const RENDER_MESSAGE_TYPE = "makespdf:render" as const; + +export interface RenderRequest { + type: typeof RENDER_MESSAGE_TYPE; + markdown: string; + /** Document title for `/md` options, the file stem (no extension). */ + title: string; + /** Suggested download filename, e.g. "README.pdf". */ + filename: string; +} + +export interface RenderSuccess { + ok: true; + /** The PDF bytes, base64-encoded. */ + base64: string; + /** Sanitized filename the content script should save as. */ + filename: string; + /** `X-Pages` response header, when the server sent one. */ + pages: string | null; + /** `X-Render-Ms` response header, when the server sent one. */ + renderMs: string | null; +} + +export interface RenderFailure { + ok: false; + kind: RenderErrorKind; + message: string; +} + +export type RenderResponse = RenderSuccess | RenderFailure; diff --git a/src/lib/mime.ts b/src/lib/mime.ts new file mode 100644 index 0000000..5756840 --- /dev/null +++ b/src/lib/mime.ts @@ -0,0 +1,43 @@ +/** Content-type helpers for fetched assets. */ + +/** File-extension → MIME map, the same set the VS Code plugin embeds. */ +export const IMAGE_MIME_BY_EXT: Readonly> = { + ".png": "image/png", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".gif": "image/gif", + ".webp": "image/webp", + ".svg": "image/svg+xml", + ".bmp": "image/bmp", + ".avif": "image/avif", + ".ico": "image/x-icon", + ".tif": "image/tiff", + ".tiff": "image/tiff", + ".apng": "image/apng", +}; + +/** The MIME type for a URL path's extension, or null when unknown. */ +export function mimeFromPath(path: string): string | null { + const leaf = path.split("/").pop() ?? ""; + const dot = leaf.lastIndexOf("."); + if (dot < 0) return null; + return IMAGE_MIME_BY_EXT[leaf.slice(dot).toLowerCase()] ?? null; +} + +/** Lowercase a Content-Type and drop its parameters; null when empty. */ +export function normalizeContentType(raw: string | null): string | null { + if (!raw) return null; + const value = raw.split(";")[0]?.trim().toLowerCase() ?? ""; + return value.length > 0 ? value : null; +} + +/** + * The content type to store an image under: the response's own `image/*` + * type when it has one (it can differ from the extension), otherwise the + * extension's type (GitHub serves some SVGs as `text/plain`), otherwise null. + */ +export function pickImageMime(contentType: string | null, path: string): string | null { + const normalized = normalizeContentType(contentType); + if (normalized && normalized.startsWith("image/")) return normalized; + return mimeFromPath(path); +} diff --git a/src/lib/render-client.ts b/src/lib/render-client.ts new file mode 100644 index 0000000..604d7f0 --- /dev/null +++ b/src/lib/render-client.ts @@ -0,0 +1,89 @@ +/** + * The render request, run in the background. + * + * Only the background can POST to makespdf.com without CORS trouble: it sits + * on the extension origin with a `makespdf.com` host permission. The call is + * anonymous unless the user saved an API key in the options — the server's + * promo carve-out serves anonymous `/md` renders — and the + * `X-MakesPDF-Client` header labels the build (`+chromium` / `+firefox`). + */ + +import { base64FromBytes } from "./bytes"; +import { CLIENT_HEADER } from "./build-target"; +import { mapFetchError, mapHttpError } from "./errors"; +import { sanitizeFilename } from "./github-url"; +import type { RenderRequest, RenderResponse } from "./messages"; +import { MD_ENDPOINT } from "./service"; + +/** Whole-request ceiling; the server renders in about a second. */ +const RENDER_TIMEOUT_MS = 60_000; + +export interface StoredDefaults { + pageSize?: string; + theme?: string; +} + +export interface RenderDeps { + fetchImpl: typeof fetch; + /** + * The `X-MakesPDF-Client` value; defaults to this bundle's baked header. + * Injecting it lets the tests pin a header per package. + */ + clientHeaderValue?: string; + /** The saved API key, or null when the user has none (anonymous render). */ + getApiKey: () => Promise; + /** Page size / theme defaults from the options page. */ + getStoredDefaults?: () => Promise; +} + +/** POST the assembled Markdown to `/api/v1/md` and return the PDF as base64. */ +export async function renderMarkdown(input: RenderRequest, deps: RenderDeps): Promise { + const apiKey = await deps.getApiKey(); + const defaults = (await deps.getStoredDefaults?.()) ?? {}; + + const options: Record = { title: input.title }; + if (defaults.pageSize) options.pageSize = defaults.pageSize; + if (defaults.theme) options.theme = defaults.theme; + + const headers: Record = { + "Content-Type": "application/json", + "X-MakesPDF-Client": deps.clientHeaderValue ?? CLIENT_HEADER, + }; + // An absent key is the anonymous path; an empty `Bearer ` would read as a + // failed auth attempt server-side. + if (apiKey) headers.Authorization = `Bearer ${apiKey}`; + + let response: Response; + try { + response = await deps.fetchImpl(MD_ENDPOINT, { + method: "POST", + headers, + body: JSON.stringify({ markdown: input.markdown, options }), + signal: AbortSignal.timeout(RENDER_TIMEOUT_MS), + }); + } catch (error) { + return { ok: false, ...mapFetchError(error) }; + } + + if (!response.ok) { + const bodyText = await safeText(response); + return { ok: false, ...mapHttpError(response.status, bodyText, { hasKey: apiKey !== null }) }; + } + + const bytes = new Uint8Array(await response.arrayBuffer()); + return { + ok: true, + base64: base64FromBytes(bytes), + filename: sanitizeFilename(input.filename), + pages: response.headers.get("X-Pages"), + renderMs: response.headers.get("X-Render-Ms"), + }; +} + +async function safeText(response: Response): Promise { + try { + return await response.text(); + } catch { + return ""; + } +} diff --git a/src/lib/service.ts b/src/lib/service.ts new file mode 100644 index 0000000..3dc0e6d --- /dev/null +++ b/src/lib/service.ts @@ -0,0 +1,11 @@ +/** The makesPDF service this extension talks to. */ +export const SERVICE_URL = "https://makespdf.com"; + +/** Where a user creates an account (anonymous renders need none). */ +export const SIGNUP_URL = `${SERVICE_URL}/signup`; + +/** Where a user mints an API key for keyed (untracked-limit) renders. */ +export const API_KEYS_URL = `${SERVICE_URL}/settings/api-keys`; + +/** The Markdown → PDF endpoint (`POST`, JSON in, PDF bytes out). */ +export const MD_ENDPOINT = `${SERVICE_URL}/api/v1/md`; diff --git a/src/options/options.css b/src/options/options.css new file mode 100644 index 0000000..f5f81bd --- /dev/null +++ b/src/options/options.css @@ -0,0 +1,128 @@ +:root { + color-scheme: light dark; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans", Helvetica, Arial, sans-serif; +} + +body { + margin: 0; + background: #f6f8fa; + color: #1f2328; +} + +main { + max-width: 560px; + margin: 0 auto; + padding: 24px 20px 40px; +} + +h1 { + font-size: 20px; + margin: 0 0 4px; +} + +h2 { + font-size: 15px; + margin: 0 0 8px; +} + +.lede { + color: #57606a; + margin: 0 0 20px; +} + +label { + display: block; + font-weight: 600; + font-size: 13px; + margin-bottom: 6px; +} + +input[type="password"], +select { + width: 100%; + box-sizing: border-box; + font: inherit; + padding: 6px 10px; + border: 1px solid rgba(31, 35, 40, 0.15); + border-radius: 6px; + background: #ffffff; + color: inherit; +} + +.hint { + font-size: 12px; + color: #57606a; + margin: 6px 0 20px; +} + +.row { + display: flex; + gap: 16px; + margin-bottom: 20px; +} + +.field { + flex: 1; +} + +.actions { + display: flex; + align-items: center; + gap: 12px; + margin-bottom: 24px; +} + +button { + font: inherit; + font-weight: 600; + padding: 6px 16px; + border: 1px solid rgba(31, 35, 40, 0.15); + border-radius: 6px; + background: #1f883d; + color: #ffffff; + cursor: pointer; +} + +button:hover { + background: #1a7f37; +} + +#status { + font-size: 13px; + color: #57606a; +} + +.privacy { + border-top: 1px solid #d8dee4; + padding-top: 16px; + font-size: 13px; + color: #57606a; +} + +a { + color: #0969da; +} + +@media (prefers-color-scheme: dark) { + body { + background: #0d1117; + color: #e6edf3; + } + + input[type="password"], + select { + background: #161b22; + border-color: #30363d; + } + + .lede, + .hint, + #status, + .privacy { + color: #8b949e; + } + + .privacy { + border-color: #30363d; + } +} diff --git a/src/options/options.html b/src/options/options.html new file mode 100644 index 0000000..35d370c --- /dev/null +++ b/src/options/options.html @@ -0,0 +1,57 @@ + + + + + + makesPDF options + + + +
+

makesPDF

+

Download GitHub Markdown files as PDF. Open any .md file on GitHub and press Download PDF.

+ + + +

+ Stored in this browser only, never synced. Anonymous renders work without a key (stricter limits, nothing stored). + Create an API key. +

+ +
+
+ + +
+
+ + +
+
+ +
+ + +
+ +
+

Privacy

+

+ To render a PDF, the Markdown text of the file you export — including any relative images embedded in it — is sent + to makesPDF. Anonymous renders are not stored. Renders made with an API key are kept as a 7-day artifact on your + account. No other page data leaves your browser. +

+

Privacy policy

+
+
+ + diff --git a/src/options/options.ts b/src/options/options.ts new file mode 100644 index 0000000..a4b7c42 --- /dev/null +++ b/src/options/options.ts @@ -0,0 +1,51 @@ +/** + * Options page: API key, page size and theme defaults. + * + * The key is stored in `storage.local` — this browser only, never synced — + * and is the only credential this extension holds. Leaving it empty means + * anonymous renders (no key sent), which the service serves under its promo + * carve-out with stricter limits. + */ + +import browser from "webextension-polyfill"; + +const DEFAULT_PAGE_SIZE = "A4"; +const DEFAULT_THEME = "default"; + +function input(id: string): HTMLInputElement { + const element = document.getElementById(id); + if (!(element instanceof HTMLInputElement)) throw new Error(`missing input #${id}`); + return element; +} + +function select(id: string): HTMLSelectElement { + const element = document.getElementById(id); + if (!(element instanceof HTMLSelectElement)) throw new Error(`missing select #${id}`); + return element; +} + +async function load(): Promise { + const stored = await browser.storage.local.get(["apiKey", "pageSize", "theme"]); + input("api-key").value = typeof stored.apiKey === "string" ? stored.apiKey : ""; + select("page-size").value = + typeof stored.pageSize === "string" && stored.pageSize ? stored.pageSize : DEFAULT_PAGE_SIZE; + select("theme").value = typeof stored.theme === "string" && stored.theme ? stored.theme : DEFAULT_THEME; +} + +function setStatus(message: string): void { + const status = document.getElementById("status"); + if (status) status.textContent = message; +} + +async function save(): Promise { + const apiKey = input("api-key").value.trim(); + const pageSize = select("page-size").value || DEFAULT_PAGE_SIZE; + const theme = select("theme").value || DEFAULT_THEME; + await browser.storage.local.set({ apiKey, pageSize, theme }); + setStatus(apiKey ? "Saved. Renders will use your API key." : "Saved. Renders are anonymous."); +} + +document.addEventListener("DOMContentLoaded", () => { + void load(); + document.getElementById("save")?.addEventListener("click", () => void save()); +}); diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..7eb7d04 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "module": "ESNext", + "moduleResolution": "Bundler", + "types": ["node"], + "strict": true, + "noUncheckedIndexedAccess": true, + "noImplicitOverride": true, + "noFallthroughCasesInSwitch": true, + "forceConsistentCasingInFileNames": true, + "isolatedModules": true, + "verbatimModuleSyntax": true, + "resolveJsonModule": true, + "skipLibCheck": true, + "noEmit": true + }, + "include": ["src", "tests", "vitest.config.ts"] +} diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 0000000..6683d76 --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,11 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + environment: "node", + include: ["tests/**/*.test.ts"], + // The build-output test runs esbuild for both packages; give it room. + testTimeout: 60_000, + hookTimeout: 60_000, + }, +}); From 808c5a310100df9f8bc46da3114db17782c009f3 Mon Sep 17 00:00:00 2001 From: lecstor Date: Tue, 13 Oct 2026 08:32:15 +1000 Subject: [PATCH 2/5] Extension logic, tests, build, CI, README and smoke fixtures --- .github/workflows/ci.yml | 21 +++ README.md | 124 +++++++++++++++++ smoke/chromium-smoke.mjs | 135 +++++++++++++++++++ smoke/fixture.md | 22 +++ smoke/logo.png | Bin 0 -> 214 bytes smoke/second.md | 6 + src/lib/markdown-images.ts | 20 ++- tests/build-output.test.ts | 93 +++++++++++++ tests/build-target.test.ts | 25 ++++ tests/button.test.ts | 105 +++++++++++++++ tests/bytes.test.ts | 22 +++ tests/controller.test.ts | 246 ++++++++++++++++++++++++++++++++++ tests/errors.test.ts | 88 ++++++++++++ tests/github-adapter.test.ts | 161 ++++++++++++++++++++++ tests/github-url.test.ts | 92 +++++++++++++ tests/markdown-images.test.ts | 140 +++++++++++++++++++ tests/render-client.test.ts | 154 +++++++++++++++++++++ tsconfig.json | 1 + 18 files changed, 1450 insertions(+), 5 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 README.md create mode 100644 smoke/chromium-smoke.mjs create mode 100644 smoke/fixture.md create mode 100644 smoke/logo.png create mode 100644 smoke/second.md create mode 100644 tests/build-output.test.ts create mode 100644 tests/build-target.test.ts create mode 100644 tests/button.test.ts create mode 100644 tests/bytes.test.ts create mode 100644 tests/controller.test.ts create mode 100644 tests/errors.test.ts create mode 100644 tests/github-adapter.test.ts create mode 100644 tests/github-url.test.ts create mode 100644 tests/markdown-images.test.ts create mode 100644 tests/render-client.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..30ad610 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,21 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + - run: npm ci + - run: npm run typecheck + - run: npm test + - run: npm run build + - run: npm run verify:packages diff --git a/README.md b/README.md new file mode 100644 index 0000000..2bb3d5a --- /dev/null +++ b/README.md @@ -0,0 +1,124 @@ +# makesPDF browser extension + +Download GitHub Markdown files as PDF with [makesPDF](https://makespdf.com). +On a `.md` / `.markdown` file view — and on a repo home page's rendered README +— the extension injects a **Download PDF** button that saves +`.pdf`. + +Manifest V3, TypeScript, one build producing a Chrome/Chromium package and a +Firefox package. + +## Install (development) + +```bash +npm install +npm run build +``` + +- **Chrome / Edge / Brave**: `chrome://extensions` → enable Developer mode → + **Load unpacked** → `dist/chromium`. +- **Firefox**: `about:debugging#/runtime/this-firefox` → **Load Temporary + Add-on** → `dist/firefox/manifest.json`. + +`npm run build` also writes `dist/makespdf-chromium-.zip` and +`dist/makespdf-firefox-.zip` for distribution. + +## Usage + +1. Open any Markdown file on GitHub (`github.com///blob//.md`) + or a repository home page with a README. +2. Press **Download PDF** in the file header (repo home: bottom-right). +3. The PDF downloads as `.pdf`. + +Works on public and private repositories: the Markdown and its relative images +are fetched through the browser's own GitHub session. Renders are **anonymous +by default**; add an API key in the options for your own rate limits. + +## Options + +The toolbar icon opens the options page (`chrome://extensions` → Details → +Extension options in Chrome; `about:addons` → Preferences in Firefox): + +- **API key** — stored in `storage.local`: this browser only, never synced. + Leave empty to render anonymously. Create one at + . +- **Page size** — `A3`, `A4` (default), `A5`, `Letter`, `Legal`. +- **Theme** — `default` or `github`. + +## Privacy + +To render a PDF, the Markdown text of the file you export — including any +relative images embedded in it as `data:` URIs — is sent to makesPDF +(`https://makespdf.com/api/v1/md`). Anonymous renders are not stored. Renders +made with an API key are kept as a 7-day artifact on your account. No other +page data leaves your browser. Nothing is sent until you press **Download +PDF**. + +The extension requests the minimum permissions it can: + +| Permission | Why | +| --- | --- | +| `storage` | The options page's API key and defaults. | +| content script on `https://github.com/*` | The button, the Markdown fetch and the image fetches run in the page's session. | +| host permission for `https://makespdf.com/*` | The background POSTs the render request. | + +No ``, no `downloads` permission (the PDF is saved with an +object-URL anchor), no analytics. + +## How it works + +``` +content script (github.com) background (extension origin) +─────────────────────────── ───────────────────────────── +match page → adapter +fetch raw Markdown (session cookies) +find relative images → fetch (session) → data: +/─────────── render request ──────────▶ POST https://makespdf.com/api/v1/md + X-MakesPDF-Client: browser-extension/+ + Authorization: Bearer (only if saved) +◀────────── base64 PDF ──────────────── anonymous when no key +object-URL anchor → .pdf +``` + +- **GitHub soft navigation** (Turbo) is handled by re-checking on Turbo + events, DOM mutations and a coarse interval; injection is idempotent, so a + navigation never leaves two buttons or a button bound to the previous file. +- **Relative images** are resolved against the file's directory + (`./`, `../`, nested dirs; `/`-rooted against the repo root) and inlined as + `data:` URIs. `/md`'s limits are mirrored: **5 MB per image, 20 images per + document**. If any image cannot be embedded the export stops and names it — + a PDF silently missing an image is worse than no PDF (the VS Code plugin's + MAK-191 precedent). Absolute `https:` images are left for the server. +- **Errors** mirror the wording of the VS Code/Zed clients: 401 with a saved + key blames the key, anonymous 401 points at sign-up, 429 carries the + server's tip, and 400/413 surface the server's message. +- **Adapters** (`src/adapters/`) are additive — MAK-197's later sources + implement the same `MarkdownAdapter` interface + (`matches`, `getMarkdown`, `resolveAsset`, `injectButton`, + `suggestedFilename`) and register in `src/adapters/registry.ts`. + +## Development + +```bash +npm run typecheck # tsc --noEmit +npm test # vitest: URL matching, path resolution, image + # limits, error mapping, header per package, + # built-package contents +npm run build # dist/chromium + dist/firefox (+ zips) +npm run verify:packages # structural checks over dist/ (loadability gate) +``` + +Unit tests cover URL matching (including refs containing `/`), relative path +resolution, the image limits and failure messages, the HTTP error mapping, the +`X-MakesPDF-Client` value per package (pinned both as a function and as a +literal in each built bundle), and the injected button's idempotence across +soft navigation. + +### Limitations (MVP) + +- GitHub only; `.md`/`.markdown` file views and repo-home READMEs. +- At most 20 relative images per document; more stops the export. +- Root-relative image paths (`/img.png`) are resolved at the first path + segment after `/blob/` as the ref — refs containing `/` combined with + root-relative images can resolve to the wrong directory. +- No extension icons yet (store builds need them). diff --git a/smoke/chromium-smoke.mjs b/smoke/chromium-smoke.mjs new file mode 100644 index 0000000..d0a7ba1 --- /dev/null +++ b/smoke/chromium-smoke.mjs @@ -0,0 +1,135 @@ +/** + * Chromium smoke for the built extension — the scripted half of the manual + * smoke the PR records. Not part of CI (it needs a real browser and the + * production service). + * + * npm run build + * node smoke/chromium-smoke.mjs + * + * It loads dist/chromium into a persistent Chromium context, opens the public + * fixture on GitHub (smoke/fixture.md), clicks the injected button and checks + * the downloaded PDF; then soft-navigates to smoke/second.md and checks the + * button stays singular and still works; then checks the repo-home button. + * + * Playwright is not a dependency of this repo. The script resolves it from + * `node_modules`, then from a sibling makesPDF checkout (which has it), and + * finally from `PLAYWRIGHT_HOME` if set. + */ + +import { createRequire } from "node:module"; +import { mkdirSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import assert from "node:assert/strict"; + +const ROOT = join(dirname(fileURLToPath(import.meta.url)), ".."); +const REPO = "https://github.com/makesPDF/makespdf-browser-extension"; +const EXTENSION = process.env.EXTENSION_DIR ?? join(ROOT, "dist/chromium"); +const OUT = process.env.SMOKE_OUT ?? join(tmpdir(), `makespdf-smoke-${process.pid}`); + +function loadPlaywright() { + const anchors = [join(ROOT, "package.json"), process.env.PLAYWRIGHT_HOME, "/Users/jason/dev/pdf/makesPDF/package.json"].filter( + Boolean, + ); + for (const anchor of anchors) { + const require = createRequire(anchor); + for (const moduleName of ["playwright", "@playwright/test"]) { + try { + return require(moduleName); + } catch { + // try the next module/anchor + } + } + } + throw new Error("playwright not found; set PLAYWRIGHT_HOME to a project that has it installed"); +} + +const { chromium } = loadPlaywright(); +mkdirSync(OUT, { recursive: true }); + +const context = await chromium.launchPersistentContext(join(OUT, "profile"), { + channel: "chromium", + headless: true, + acceptDownloads: true, + args: [`--disable-extensions-except=${EXTENSION}`, `--load-extension=${EXTENSION}`], +}); + +const page = await context.newPage(); +const pageErrors = []; +const consoleMessages = []; +page.on("pageerror", (error) => pageErrors.push(String(error))); +page.on("console", (message) => consoleMessages.push(`page ${message.type()}: ${message.text()}`)); +context.on("serviceworker", (worker) => { + worker.on("console", (message) => consoleMessages.push(`sw ${message.type()}: ${message.text()}`)); +}); + +let failed = false; +const step = (message) => console.log(`→ ${message}`); +const ok = (message) => console.log(` ✓ ${message}`); + +try { + step("blob view of smoke/fixture.md"); + await page.goto(`${REPO}/blob/main/smoke/fixture.md`, { waitUntil: "domcontentloaded" }); + await page.waitForSelector("#makespdf-download-pdf-button", { timeout: 45_000 }); + assert.equal(await page.locator("#makespdf-download-pdf-button").count(), 1, "exactly one button"); + ok("button injected"); + + step("click Download PDF"); + const firstDownload = page.waitForEvent("download", { timeout: 180_000 }); + await page.click("#makespdf-download-pdf-button"); + await page.waitForFunction( + () => { + const status = document.getElementById("makespdf-download-pdf-status"); + return Boolean(status && status.textContent && status.textContent !== "Rendering PDF…"); + }, + { timeout: 170_000 }, + ); + console.log(` status: ${await page.textContent("#makespdf-download-pdf-status")}`); + const download = await firstDownload; + assert.equal(download.suggestedFilename(), "fixture.pdf", "suggested filename"); + await download.saveAs(join(OUT, "fixture.pdf")); + const bytes = readFileSync(join(OUT, "fixture.pdf")); + assert.equal(bytes.subarray(0, 5).toString(), "%PDF-", "PDF magic bytes"); + assert.ok(bytes.length > 5_000, `PDF is ${bytes.length} bytes`); + const status = await page.textContent("#makespdf-download-pdf-status"); + assert.match(status ?? "", /^Saved fixture\.pdf/, `status: ${status}`); + ok(`${bytes.length} bytes, status "${status}"`); + + step("soft-navigate to smoke/second.md"); + await page.click('a[href$="second.md"]'); + await page.waitForURL(/second\.md/, { timeout: 30_000 }); + await page.waitForSelector("#makespdf-download-pdf-button", { timeout: 30_000 }); + await new Promise((resolve) => setTimeout(resolve, 1_000)); + assert.equal(await page.locator("#makespdf-download-pdf-button").count(), 1, "still exactly one button"); + ok("no duplicate button after soft navigation"); + + const secondDownload = page.waitForEvent("download", { timeout: 180_000 }); + await page.click("#makespdf-download-pdf-button"); + const second = await secondDownload; + assert.equal(second.suggestedFilename(), "second.pdf", "second suggested filename"); + await second.saveAs(join(OUT, "second.pdf")); + const secondBytes = readFileSync(join(OUT, "second.pdf")); + assert.equal(secondBytes.subarray(0, 5).toString(), "%PDF-"); + ok(`${secondBytes.length} bytes as second.pdf`); + + step("repo home README"); + await page.goto(REPO, { waitUntil: "domcontentloaded" }); + await page.waitForSelector("#makespdf-download-pdf-host #makespdf-download-pdf-button", { timeout: 45_000 }); + ok("home button present"); +} catch (error) { + failed = true; + console.error(`\nSMOKE FAILED: ${error instanceof Error ? error.message : String(error)}`); +} finally { + if (pageErrors.length > 0) { + failed = true; + console.error("page errors:", pageErrors); + } + if (consoleMessages.length > 0) { + console.log("console output:", consoleMessages); + } + await context.close(); +} + +if (failed) process.exit(1); +console.log(`\nSMOKE PASSED (artifacts in ${OUT})`); diff --git a/smoke/fixture.md b/smoke/fixture.md new file mode 100644 index 0000000..82103e5 --- /dev/null +++ b/smoke/fixture.md @@ -0,0 +1,22 @@ +# Smoke fixture + +A public Markdown file with the things the manual smoke exercises: a relative +image (Markdown form), a relative image (HTML form), a Mermaid diagram, and a +link to a second file for soft-navigation checks. + +![logo](./logo.png) + +logo + +```mermaid +graph LR + A[GitHub .md] --> B[makesPDF] --> C[PDF] +``` + +Image-like text inside code is literal and must NOT be inlined: + +``` +![not real](./does-not-exist.png) +``` + +Next: [second.md](./second.md) diff --git a/smoke/logo.png b/smoke/logo.png new file mode 100644 index 0000000000000000000000000000000000000000..4d5ea5df5dc914a8ffa90d1e166f4a447b342f49 GIT binary patch literal 214 zcmeAS@N?(olHy`uVBq!ia0vp^2|(3zV?TqG5zrh)CJ_q+^_B6GA&|HC7T=$z WnvI?2J@ return { masked, restore }; } -/** All image src tokens in document order, code masked out. */ +/** + * All image src tokens in document order, code masked out. The two syntaxes + * are scanned separately, then merged by position so order (and therefore + * which failures are named first) follows the document even when Markdown and + * HTML references interleave. + */ function collectRefs(source: string): { masked: string; restore: (value: string) => string; refs: string[] } { const { masked, restore } = maskCode(source); - const refs: string[] = []; - for (const match of masked.matchAll(MD_IMAGE)) refs.push(cleanSrc(match[2] ?? "")); - for (const match of masked.matchAll(HTML_IMAGE_SRC)) refs.push(cleanSrc(match[3] ?? match[4] ?? "")); - return { masked, restore, refs }; + const found: { index: number; src: string }[] = []; + for (const match of masked.matchAll(MD_IMAGE)) { + found.push({ index: match.index, src: cleanSrc(match[2] ?? "") }); + } + for (const match of masked.matchAll(HTML_IMAGE_SRC)) { + found.push({ index: match.index, src: cleanSrc(match[3] ?? match[4] ?? "") }); + } + found.sort((a, b) => a.index - b.index); + return { masked, restore, refs: found.map((entry) => entry.src) }; } /** Unique relative image references, in document order. */ diff --git a/tests/build-output.test.ts b/tests/build-output.test.ts new file mode 100644 index 0000000..f55b820 --- /dev/null +++ b/tests/build-output.test.ts @@ -0,0 +1,93 @@ +import { readFile, mkdtemp, rm } from "node:fs/promises"; +import { existsSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { buildAll } from "../scripts/build.mjs"; +import { clientHeader } from "../src/lib/build-target"; + +/** + * The one-build-two-packages contract: build both targets the way + * `npm run build` does, then pin what each package actually contains — the + * per-package `X-MakesPDF-Client` literal and the two MV3 background shapes. + */ + +const pkg = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8")) as { + version: string; +}; + +let outRoot: string; +let manifests: Record>; +let backgrounds: Record; + +beforeAll(async () => { + outRoot = await mkdtemp(join(tmpdir(), "makespdf-build-")); + await buildAll({ outRoot, targets: ["chromium", "firefox"], zip: false }); + manifests = { + chromium: JSON.parse(await readFile(join(outRoot, "chromium/manifest.json"), "utf8")), + firefox: JSON.parse(await readFile(join(outRoot, "firefox/manifest.json"), "utf8")), + }; + backgrounds = { + chromium: await readFile(join(outRoot, "chromium/background.js"), "utf8"), + firefox: await readFile(join(outRoot, "firefox/background.js"), "utf8"), + }; +}); + +afterAll(async () => { + if (outRoot) await rm(outRoot, { recursive: true, force: true }); +}); + +describe("built packages", () => { + it("produces both packages with the full file set", () => { + for (const target of ["chromium", "firefox"]) { + for (const file of [ + "manifest.json", + "content.js", + "background.js", + "options/options.html", + "options/options.js", + "options/options.css", + ]) { + expect(existsSync(join(outRoot, target, file)), `${target}/${file}`).toBe(true); + } + } + }); + + it("pins the chromium package's X-MakesPDF-Client literal in its bundle", () => { + const header = clientHeader(pkg.version, "chromium"); + expect(header).toBe(`browser-extension/${pkg.version}+chromium`); + expect(backgrounds.chromium).toContain(header); + expect(backgrounds.chromium).not.toContain(`+firefox`); + }); + + it("pins the firefox package's X-MakesPDF-Client literal in its bundle", () => { + const header = clientHeader(pkg.version, "firefox"); + expect(header).toBe(`browser-extension/${pkg.version}+firefox`); + expect(backgrounds.firefox).toContain(header); + expect(backgrounds.firefox).not.toContain(`+chromium`); + }); + + it("ships a module service worker on chromium and a module event page on firefox", () => { + expect(manifests.chromium?.background).toEqual({ service_worker: "background.js", type: "module" }); + expect(manifests.firefox?.background).toEqual({ scripts: ["background.js"], type: "module" }); + expect(manifests.firefox?.browser_specific_settings).toMatchObject({ + gecko: { id: "browser-extension@makespdf.com" }, + }); + expect(manifests.chromium?.browser_specific_settings).toBeUndefined(); + }); + + it("carries the minimal permission set on both packages", () => { + for (const target of ["chromium", "firefox"]) { + const manifest = manifests[target]; + expect(manifest?.manifest_version).toBe(3); + expect(manifest?.version).toBe(pkg.version); + expect(manifest?.permissions).toEqual(["storage"]); + expect(manifest?.host_permissions).toEqual(["https://makespdf.com/*"]); + expect(JSON.stringify(manifest)).not.toContain("all_urls"); + expect(JSON.stringify(manifest)).not.toContain("downloads"); + expect(manifest?.content_scripts).toEqual([ + { matches: ["https://github.com/*"], js: ["content.js"], run_at: "document_idle" }, + ]); + } + }); +}); diff --git a/tests/build-target.test.ts b/tests/build-target.test.ts new file mode 100644 index 0000000..d5e3348 --- /dev/null +++ b/tests/build-target.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from "vitest"; +import { CLIENT_HEADER, clientHeader } from "../src/lib/build-target"; + +/** + * The header value each package must send (operator decision 2026-10-09). + * The build-output test additionally requires this exact string in each + * package's built background bundle. + */ +describe("clientHeader", () => { + it("pins the chromium package's value", () => { + expect(clientHeader("1.0.0", "chromium")).toBe("browser-extension/1.0.0+chromium"); + }); + + it("pins the firefox package's value", () => { + expect(clientHeader("1.0.0", "firefox")).toBe("browser-extension/1.0.0+firefox"); + }); + + it("keeps the version's own dots and the '+' build separator", () => { + expect(clientHeader("0.1.0-beta.2", "chromium")).toBe("browser-extension/0.1.0-beta.2+chromium"); + }); + + it("falls back to the chromium label outside a build (tests/dev)", () => { + expect(CLIENT_HEADER).toBe("browser-extension/0.0.0+chromium"); + }); +}); diff --git a/tests/button.test.ts b/tests/button.test.ts new file mode 100644 index 0000000..0937e31 --- /dev/null +++ b/tests/button.test.ts @@ -0,0 +1,105 @@ +// @vitest-environment jsdom +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { BUTTON_ID, FLOATING_HOST_ID, STATUS_ID, injectDownloadButton, removeInjected, renderButtonState } from "../src/lib/button"; +import { matchGitHubMarkdown, type GitHubMarkdownTarget } from "../src/lib/github-url"; + +function target(url: string): GitHubMarkdownTarget { + const matched = matchGitHubMarkdown(url); + if (!matched) throw new Error(`not a target: ${url}`); + return matched; +} + +const BLOB_TARGET = target("https://github.com/acme/docs/blob/main/readme.md"); +const HOME_TARGET = target("https://github.com/acme/docs"); + +function blobDom(): void { + document.body.innerHTML = ` +
+
+ Raw +
+
`; +} + +beforeEach(() => { + document.body.innerHTML = ""; +}); + +describe("injectDownloadButton", () => { + it("joins the blob header next to the Raw button", () => { + blobDom(); + const onClick = vi.fn(); + expect(injectDownloadButton(document, BLOB_TARGET, onClick)).toBe(true); + + const button = document.getElementById(BUTTON_ID); + expect(button).not.toBeNull(); + expect(button?.textContent).toBe("Download PDF"); + expect(document.getElementById(STATUS_ID)).not.toBeNull(); + expect(document.getElementById(FLOATING_HOST_ID)).toBeNull(); + + // Rendered as a sibling immediately before GitHub's button group, so the + // button and status sit left of GitHub's actions without breaking them. + const group = document.querySelector('[data-component="ButtonGroup"]'); + expect(button?.nextElementSibling?.id).toBe(STATUS_ID); + expect(button?.parentElement).toBe(group?.parentElement); + expect(group?.previousElementSibling?.id).toBe(STATUS_ID); + + button?.dispatchEvent(new MouseEvent("click", { bubbles: true })); + expect(onClick).toHaveBeenCalledTimes(1); + }); + + it("is idempotent: re-injecting leaves exactly one button", () => { + blobDom(); + injectDownloadButton(document, BLOB_TARGET, () => {}); + injectDownloadButton(document, BLOB_TARGET, () => {}); + expect(document.querySelectorAll(`#${BUTTON_ID}`).length).toBe(1); + expect(document.querySelectorAll(`#${STATUS_ID}`).length).toBe(1); + }); + + it("falls back to a floating host when the header has no Raw link", () => { + expect(injectDownloadButton(document, BLOB_TARGET, () => {})).toBe(true); + const host = document.getElementById(FLOATING_HOST_ID); + expect(host).not.toBeNull(); + expect(host?.querySelector(`#${BUTTON_ID}`)).not.toBeNull(); + }); + + it("waits on a repo home page until a README is rendered", () => { + expect(injectDownloadButton(document, HOME_TARGET, () => {})).toBe(false); + document.body.innerHTML = '
hi
'; + expect(injectDownloadButton(document, HOME_TARGET, () => {})).toBe(true); + expect(document.getElementById(FLOATING_HOST_ID)).not.toBeNull(); + }); + + it("removeInjected clears the button, status and floating host", () => { + injectDownloadButton(document, BLOB_TARGET, () => {}); + removeInjected(document); + expect(document.getElementById(BUTTON_ID)).toBeNull(); + expect(document.getElementById(STATUS_ID)).toBeNull(); + expect(document.getElementById(FLOATING_HOST_ID)).toBeNull(); + }); +}); + +describe("renderButtonState", () => { + it("shows a disabled Rendering label while busy and restores it after", () => { + blobDom(); + injectDownloadButton(document, BLOB_TARGET, () => {}); + renderButtonState(document, "busy"); + const button = document.getElementById(BUTTON_ID) as HTMLButtonElement; + expect(button.textContent).toBe("Rendering PDF…"); + expect(button.disabled).toBe(true); + + renderButtonState(document, "ok", "Saved readme.pdf"); + expect(button.textContent).toBe("Download PDF"); + expect(button.disabled).toBe(false); + expect(document.getElementById(STATUS_ID)?.textContent).toBe("Saved readme.pdf"); + }); + + it("uses the error colour for errors", () => { + blobDom(); + injectDownloadButton(document, BLOB_TARGET, () => {}); + renderButtonState(document, "error", "Export stopped"); + const status = document.getElementById(STATUS_ID) as HTMLElement; + expect(status.textContent).toBe("Export stopped"); + expect(status.style.color).toBe("rgb(207, 34, 46)"); + }); +}); diff --git a/tests/bytes.test.ts b/tests/bytes.test.ts new file mode 100644 index 0000000..e5ce36e --- /dev/null +++ b/tests/bytes.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from "vitest"; +import { base64FromBytes, bytesFromBase64 } from "../src/lib/bytes"; + +describe("base64 helpers", () => { + it("round-trips small payloads", () => { + const bytes = new Uint8Array([0, 1, 2, 250, 255]); + expect(bytesFromBase64(base64FromBytes(bytes))).toEqual(bytes); + }); + + it("round-trips payloads larger than one encode chunk", () => { + const bytes = new Uint8Array(0x8000 * 2 + 17); + for (let i = 0; i < bytes.length; i++) bytes[i] = i % 251; + const encoded = base64FromBytes(bytes); + expect(encoded.length).toBeGreaterThan(0x10000); + expect(bytesFromBase64(encoded)).toEqual(bytes); + }); + + it("round-trips an empty payload", () => { + expect(base64FromBytes(new Uint8Array(0))).toBe(""); + expect(bytesFromBase64("")).toEqual(new Uint8Array(0)); + }); +}); diff --git a/tests/controller.test.ts b/tests/controller.test.ts new file mode 100644 index 0000000..5a483a1 --- /dev/null +++ b/tests/controller.test.ts @@ -0,0 +1,246 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { BUTTON_ID, FLOATING_HOST_ID, STATUS_ID } from "../src/lib/button"; +import { startController, type ControllerOptions } from "../src/lib/controller"; +import { RENDER_MESSAGE_TYPE, type RenderRequest, type RenderResponse } from "../src/lib/messages"; + +const BLOB_A = "https://github.com/acme/docs/blob/main/readme.md"; +const BLOB_B = "https://github.com/acme/docs/blob/main/guide/setup.md"; +const RAW_A = "https://github.com/acme/docs/raw/main/readme.md"; +const RAW_B = "https://github.com/acme/docs/raw/main/guide/setup.md"; +const IMG_A = "https://github.com/acme/docs/raw/main/img/shot.png"; + +const PNG_BYTES = new Uint8Array([0x89, 0x50, 0x4e, 0x47]); + +function blobDom(): void { + document.body.innerHTML = ` +
+
+ Raw +
+
`; +} + +function textResponse(body: string, status = 200): Response { + return new Response(body, { status, headers: { "content-type": "text/plain; charset=utf-8" } }); +} + +function imageResponse(): Response { + return new Response(PNG_BYTES, { status: 200, headers: { "content-type": "image/png" } }); +} + +type Route = () => Response | Error; + +function routerFetch(routes: Record) { + const calls: string[] = []; + const fetchImpl = (async (input: RequestInfo | URL) => { + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + calls.push(url); + const route = routes[url]; + if (!route) throw new Error(`unexpected fetch: ${url}`); + const result = route(); + if (result instanceof Error) throw result; + return result; + }) as typeof fetch; + return { fetchImpl, calls }; +} + +interface Harness { + location: Location; + cleanup: () => void; + requests: RenderRequest[]; + button: () => HTMLElement | null; + click: () => void; +} + +function start(options: { + href: string; + routes: Record; + respond?: (request: RenderRequest) => RenderResponse; +}): Harness { + const location = { href: options.href } as Location; + const { fetchImpl, calls } = routerFetch(options.routes); + const requests: RenderRequest[] = []; + const controllerOptions: ControllerOptions = { + document, + location, + fetchImpl, + sendMessage: async (request) => { + requests.push(request); + if (calls.length === 0) throw new Error("sendMessage called before any fetch"); + return ( + options.respond?.(request) ?? { + ok: true, + base64: "AQID", + filename: request.filename, + pages: null, + renderMs: null, + } + ); + }, + }; + const cleanup = startController(controllerOptions); + return { + location, + cleanup, + requests, + button: () => document.getElementById(BUTTON_ID), + click: () => { + document.getElementById(BUTTON_ID)?.dispatchEvent(new MouseEvent("click", { bubbles: true })); + }, + }; +} + +let createObjectURL: ReturnType; +let revokeObjectURL: ReturnType; +let anchorClick: ReturnType; + +beforeEach(() => { + vi.useFakeTimers(); + document.body.innerHTML = ""; + createObjectURL = vi.fn(() => "blob:fake-url"); + revokeObjectURL = vi.fn(); + (URL as unknown as { createObjectURL: unknown }).createObjectURL = createObjectURL; + (URL as unknown as { revokeObjectURL: unknown }).revokeObjectURL = revokeObjectURL; + anchorClick = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {}); +}); + +afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); +}); + +describe("startController", () => { + it("injects a button on a markdown blob page and not elsewhere", () => { + blobDom(); + const harness = start({ href: BLOB_A, routes: { [RAW_A]: () => textResponse("# A") } }); + expect(harness.button()).not.toBeNull(); + harness.cleanup(); + + document.body.innerHTML = ""; + const other = start({ href: "https://github.com/acme/docs/blob/main/index.ts", routes: {} }); + expect(other.button()).toBeNull(); + other.cleanup(); + }); + + it("keeps exactly one button across a soft navigation and rebinds it to the new file", async () => { + blobDom(); + const harness = start({ + href: BLOB_A, + routes: { [RAW_A]: () => textResponse("# A"), [RAW_B]: () => textResponse("# B") }, + }); + expect(harness.button()).not.toBeNull(); + + harness.location.href = BLOB_B; + document.dispatchEvent(new Event("turbo:load")); + await vi.advanceTimersByTimeAsync(200); + + expect(document.querySelectorAll(`#${BUTTON_ID}`).length).toBe(1); + expect(document.querySelectorAll(`#${STATUS_ID}`).length).toBe(1); + + // The re-injected button must export the NEW file. + harness.click(); + await vi.advanceTimersByTimeAsync(0); + expect(harness.requests[0]?.markdown).toBe("# B"); + + harness.cleanup(); + }); + + it("re-injects after GitHub replaces the DOM without changing the URL", async () => { + blobDom(); + const harness = start({ href: BLOB_A, routes: { [RAW_A]: () => textResponse("# A") } }); + document.getElementById(BUTTON_ID)?.remove(); + document.getElementById(STATUS_ID)?.remove(); + blobDom(); + document.dispatchEvent(new Event("turbo:render")); + await vi.advanceTimersByTimeAsync(200); + expect(document.querySelectorAll(`#${BUTTON_ID}`).length).toBe(1); + harness.cleanup(); + }); + + it("inlines relative images and saves the PDF", async () => { + blobDom(); + const harness = start({ + href: BLOB_A, + routes: { + [RAW_A]: () => textResponse('![shot](./img/shot.png)\n\n# A'), + [IMG_A]: () => imageResponse(), + }, + }); + harness.click(); + await vi.advanceTimersByTimeAsync(0); + + expect(harness.requests).toHaveLength(1); + expect(harness.requests[0]).toEqual({ + type: RENDER_MESSAGE_TYPE, + markdown: '![shot](data:image/png;base64,iVBORw==)\n\n# A', + title: "readme", + filename: "readme.pdf", + }); + expect(createObjectURL).toHaveBeenCalledTimes(1); + expect(anchorClick).toHaveBeenCalledTimes(1); + expect(document.getElementById(STATUS_ID)?.textContent).toBe("Saved readme.pdf"); + harness.cleanup(); + }); + + it("stops before the request and names the image when an image fetch fails", async () => { + blobDom(); + const harness = start({ + href: BLOB_A, + routes: { + [RAW_A]: () => textResponse("![shot](./img/shot.png)"), + [IMG_A]: () => new Response("not found", { status: 404 }), + }, + }); + harness.click(); + await vi.advanceTimersByTimeAsync(0); + + expect(harness.requests).toHaveLength(0); + expect(createObjectURL).not.toHaveBeenCalled(); + const status = document.getElementById(STATUS_ID)?.textContent ?? ""; + expect(status).toContain("./img/shot.png"); + expect(status).toContain("could not be fetched (HTTP 404)"); + harness.cleanup(); + }); + + it("shows the background's failure message", async () => { + blobDom(); + const harness = start({ + href: BLOB_A, + routes: { [RAW_A]: () => textResponse("# A") }, + respond: () => ({ ok: false, kind: "auth", message: "Authentication failed. Check the API key." }), + }); + harness.click(); + await vi.advanceTimersByTimeAsync(0); + + expect(document.getElementById(STATUS_ID)?.textContent).toBe("Authentication failed. Check the API key."); + expect(createObjectURL).not.toHaveBeenCalled(); + harness.cleanup(); + }); + + it("waits for the README before injecting on a repo home page", async () => { + const harness = start({ + href: "https://github.com/acme/docs", + routes: { "https://github.com/acme/docs/raw/HEAD/README.md": () => textResponse("# Home") }, + }); + expect(harness.button()).toBeNull(); + + document.body.innerHTML = '
hi
'; + await vi.advanceTimersByTimeAsync(200); + expect(document.querySelectorAll(`#${BUTTON_ID}`).length).toBe(1); + expect(document.getElementById(FLOATING_HOST_ID)).not.toBeNull(); + harness.cleanup(); + }); + + it("removes the button when navigating away from a markdown view", async () => { + blobDom(); + const harness = start({ href: BLOB_A, routes: {} }); + expect(harness.button()).not.toBeNull(); + + harness.location.href = "https://github.com/acme/docs/blob/main/index.ts"; + document.dispatchEvent(new Event("turbo:load")); + await vi.advanceTimersByTimeAsync(200); + expect(harness.button()).toBeNull(); + harness.cleanup(); + }); +}); diff --git a/tests/errors.test.ts b/tests/errors.test.ts new file mode 100644 index 0000000..80d0627 --- /dev/null +++ b/tests/errors.test.ts @@ -0,0 +1,88 @@ +import { describe, expect, it } from "vitest"; +import { mapFetchError, mapHttpError } from "../src/lib/errors"; +import { SIGNUP_URL } from "../src/lib/service"; + +describe("mapHttpError", () => { + it("401 with a saved key blames the key", () => { + const mapped = mapHttpError(401, JSON.stringify({ error: "Authentication required." }), { hasKey: true }); + expect(mapped.kind).toBe("auth"); + expect(mapped.message).toBe("Authentication failed. Check the API key in the makesPDF extension options."); + }); + + it("401 anonymously points at sign-up", () => { + const mapped = mapHttpError(401, "", { hasKey: false }); + expect(mapped.kind).toBe("auth"); + expect(mapped.message).toContain(SIGNUP_URL); + }); + + it("403 behaves like 401", () => { + expect(mapHttpError(403, "", { hasKey: true }).kind).toBe("auth"); + }); + + it("429 anonymous carries the server's tip, which names sign-up", () => { + const tip = "Anonymous renders are capped. Higher limits: https://makespdf.com/signup"; + const mapped = mapHttpError(429, JSON.stringify({ error: "rate-limited", tip }), { hasKey: false }); + expect(mapped.kind).toBe("rate-limit"); + expect(mapped.message).toBe(`Rate limited. ${tip}`); + }); + + it("429 anonymous without a tip still hints at sign-up", () => { + const mapped = mapHttpError(429, "", { hasKey: false }); + expect(mapped.kind).toBe("rate-limit"); + expect(mapped.message).toContain("sign up"); + expect(mapped.message).toContain(SIGNUP_URL); + }); + + it("429 with a key does not push sign-up", () => { + const mapped = mapHttpError(429, "", { hasKey: true }); + expect(mapped.message).toBe("Rate limited. Wait a few minutes and try again."); + }); + + it("400 page-cap-exceeded spells out the cap", () => { + const mapped = mapHttpError( + 400, + JSON.stringify({ error: "page-cap-exceeded", limit: 20, actual: 34 }), + { hasKey: false }, + ); + expect(mapped.kind).toBe("bad-request"); + expect(mapped.message).toContain("34 pages"); + expect(mapped.message).toContain("cap 20"); + }); + + it("400 otherwise surfaces the server's error code", () => { + const mapped = mapHttpError(400, JSON.stringify({ error: "Invalid request" }), { hasKey: true }); + expect(mapped.kind).toBe("bad-request"); + expect(mapped.message).toContain("Invalid request"); + }); + + it("413 surfaces the server's own wording", () => { + const mapped = mapHttpError(413, JSON.stringify({ error: "Payload too large" }), { hasKey: false }); + expect(mapped.kind).toBe("payload-too-large"); + expect(mapped.message).toContain("Payload too large"); + }); + + it("5xx is a server error", () => { + const mapped = mapHttpError(500, JSON.stringify({ error: "boom" }), { hasKey: false }); + expect(mapped.kind).toBe("server"); + expect(mapped.message).toContain("HTTP 500"); + }); + + it("survives a non-JSON body", () => { + const mapped = mapHttpError(400, "nope", { hasKey: false }); + expect(mapped.kind).toBe("bad-request"); + expect(mapped.message).toContain("Bad request"); + }); +}); + +describe("mapFetchError", () => { + it("maps an abort/timeout to a timed-out message", () => { + const error = new Error("timed out"); + error.name = "TimeoutError"; + expect(mapFetchError(error).message).toContain("did not respond in time"); + }); + + it("maps anything else to a connectivity message", () => { + expect(mapFetchError(new TypeError("Failed to fetch")).kind).toBe("network"); + expect(mapFetchError(new TypeError("Failed to fetch")).message).toContain("Could not reach makesPDF"); + }); +}); diff --git a/tests/github-adapter.test.ts b/tests/github-adapter.test.ts new file mode 100644 index 0000000..3c3356f --- /dev/null +++ b/tests/github-adapter.test.ts @@ -0,0 +1,161 @@ +// @vitest-environment jsdom +import { describe, expect, it } from "vitest"; +import { GitHubMarkdownAdapter } from "../src/adapters/github"; +import { AssetError, MarkdownFetchError } from "../src/lib/assets"; +import { matchGitHubMarkdown } from "../src/lib/github-url"; + +const PNG_BYTES = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); + +interface Captured { + url: string; + init?: RequestInit; +} + +/** A fake fetch that records calls and replies with the next queued response. */ +function fakeFetch(responses: (Response | Error)[]): { fetchImpl: typeof fetch; calls: Captured[] } { + const calls: Captured[] = []; + const fetchImpl = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + calls.push({ url, init }); + const next = responses.shift(); + if (next instanceof Error) throw next; + if (!next) throw new Error(`unexpected fetch: ${url}`); + return next; + }) as typeof fetch; + return { fetchImpl, calls }; +} + +function imageResponse(body: Uint8Array = PNG_BYTES, contentType = "image/png", headers: Record = {}) { + return new Response(body as unknown as BodyInit, { status: 200, headers: { "content-type": contentType, ...headers } }); +} + +function adapterFor( + url: string, + fetchImpl: typeof fetch, +): GitHubMarkdownAdapter { + const target = matchGitHubMarkdown(url); + if (!target) throw new Error(`not a markdown url: ${url}`); + return new GitHubMarkdownAdapter(target, { document: document, fetchImpl }); +} + +describe("GitHubMarkdownAdapter.resolveAsset", () => { + it("resolves ./ and bare paths against the file's directory", async () => { + const { fetchImpl, calls } = fakeFetch([imageResponse()]); + const adapter = adapterFor("https://github.com/acme/docs/blob/main/guide/setup.md", fetchImpl); + const uri = await adapter.resolveAsset("./img/diagram.png"); + expect(calls[0]?.url).toBe("https://github.com/acme/docs/raw/main/guide/img/diagram.png"); + expect(uri).toBe("data:image/png;base64,iVBORw0KGgo="); + }); + + it("resolves ../ segments", async () => { + const { fetchImpl, calls } = fakeFetch([imageResponse()]); + const adapter = adapterFor("https://github.com/acme/docs/blob/main/guide/setup.md", fetchImpl); + await adapter.resolveAsset("../images/shot.png"); + expect(calls[0]?.url).toBe("https://github.com/acme/docs/raw/main/images/shot.png"); + }); + + it("resolves /-rooted paths against the repository root at the same ref", async () => { + const { fetchImpl, calls } = fakeFetch([imageResponse()]); + const adapter = adapterFor("https://github.com/acme/docs/blob/main/guide/setup.md", fetchImpl); + await adapter.resolveAsset("/assets/logo.png"); + expect(calls[0]?.url).toBe("https://github.com/acme/docs/raw/main/assets/logo.png"); + }); + + it("strips query strings and fragments", async () => { + const { fetchImpl, calls } = fakeFetch([imageResponse()]); + const adapter = adapterFor("https://github.com/acme/docs/blob/main/readme.md", fetchImpl); + await adapter.resolveAsset("./shot.png?raw=true#top"); + expect(calls[0]?.url).toBe("https://github.com/acme/docs/raw/main/shot.png"); + }); + + it("fetches with the page session (credentials same-origin, redirects followed)", async () => { + const { fetchImpl, calls } = fakeFetch([imageResponse()]); + const adapter = adapterFor("https://github.com/acme/docs/blob/main/readme.md", fetchImpl); + await adapter.resolveAsset("shot.png"); + expect(calls[0]?.init?.credentials).toBe("same-origin"); + expect(calls[0]?.init?.redirect).toBe("follow"); + }); + + it("rejects a path that escapes the repository", async () => { + const { fetchImpl } = fakeFetch([]); + const adapter = adapterFor("https://github.com/acme/docs/blob/main/readme.md", fetchImpl); + await expect(adapter.resolveAsset("../../../../etc/passwd")).rejects.toThrow(AssetError); + }); + + it("names an HTTP failure", async () => { + const { fetchImpl } = fakeFetch([new Response("nope", { status: 404 })]); + const adapter = adapterFor("https://github.com/acme/docs/blob/main/readme.md", fetchImpl); + await expect(adapter.resolveAsset("missing.png")).rejects.toMatchObject({ + reason: "could not be fetched (HTTP 404)", + }); + }); + + it("names a network failure", async () => { + const { fetchImpl } = fakeFetch([new TypeError("Failed to fetch")]); + const adapter = adapterFor("https://github.com/acme/docs/blob/main/readme.md", fetchImpl); + await expect(adapter.resolveAsset("missing.png")).rejects.toMatchObject({ reason: "could not be fetched" }); + }); + + it("refuses an image over the 5 MB cap before reading the body", async () => { + const { fetchImpl } = fakeFetch([ + imageResponse(PNG_BYTES, "image/png", { "content-length": String(5 * 1024 * 1024 + 1) }), + ]); + const adapter = adapterFor("https://github.com/acme/docs/blob/main/readme.md", fetchImpl); + await expect(adapter.resolveAsset("huge.png")).rejects.toMatchObject({ reason: "too large to embed, max 5MB" }); + }); + + it("falls back to the extension's MIME type when GitHub serves an SVG as text/plain", async () => { + const svg = new TextEncoder().encode(""); + const { fetchImpl } = fakeFetch([imageResponse(svg, "text/plain; charset=utf-8")]); + const adapter = adapterFor("https://github.com/acme/docs/blob/main/readme.md", fetchImpl); + const uri = await adapter.resolveAsset("logo.svg"); + expect(uri.startsWith("data:image/svg+xml;base64,")).toBe(true); + }); + + it("refuses a response that is not an image and has no image extension", async () => { + const { fetchImpl } = fakeFetch([imageResponse(new TextEncoder().encode("hello"), "text/plain")]); + const adapter = adapterFor("https://github.com/acme/docs/blob/main/readme.md", fetchImpl); + await expect(adapter.resolveAsset("notes.txt")).rejects.toMatchObject({ reason: "is not an image" }); + }); +}); + +describe("GitHubMarkdownAdapter.getMarkdown", () => { + it("fetches the raw URL from the file view", async () => { + const { fetchImpl, calls } = fakeFetch([ + new Response("# Title\n", { status: 200, headers: { "content-type": "text/plain" } }), + ]); + const adapter = adapterFor("https://github.com/acme/docs/blob/main/readme.md", fetchImpl); + await expect(adapter.getMarkdown()).resolves.toBe("# Title\n"); + expect(calls[0]?.url).toBe("https://github.com/acme/docs/raw/main/readme.md"); + }); + + it("tries README.markdown when README.md is missing on the repo home", async () => { + const { fetchImpl, calls } = fakeFetch([ + new Response("not found", { status: 404 }), + new Response("# Hi\n", { status: 200 }), + ]); + const adapter = adapterFor("https://github.com/acme/docs", fetchImpl); + await expect(adapter.getMarkdown()).resolves.toBe("# Hi\n"); + expect(calls.map((call) => call.url)).toEqual([ + "https://github.com/acme/docs/raw/HEAD/README.md", + "https://github.com/acme/docs/raw/HEAD/README.markdown", + ]); + }); + + it("reports a missing README clearly", async () => { + const { fetchImpl } = fakeFetch([ + new Response("not found", { status: 404 }), + new Response("not found", { status: 404 }), + ]); + const adapter = adapterFor("https://github.com/acme/docs", fetchImpl); + const pending = adapter.getMarkdown(); + await expect(pending).rejects.toThrow(MarkdownFetchError); + await expect(pending).rejects.toThrow("No README.md"); + }); + + it("reports a non-404 failure with its status", async () => { + const { fetchImpl } = fakeFetch([new Response("boom", { status: 500 })]); + const adapter = adapterFor("https://github.com/acme/docs/blob/main/readme.md", fetchImpl); + await expect(adapter.getMarkdown()).rejects.toThrow("HTTP 500"); + }); +}); diff --git a/tests/github-url.test.ts b/tests/github-url.test.ts new file mode 100644 index 0000000..b02f9b6 --- /dev/null +++ b/tests/github-url.test.ts @@ -0,0 +1,92 @@ +import { describe, expect, it } from "vitest"; +import { matchGitHubMarkdown, sanitizeFilename } from "../src/lib/github-url"; + +describe("matchGitHubMarkdown", () => { + it("matches a blob view of a .md file", () => { + const target = matchGitHubMarkdown("https://github.com/makesPDF/makespdf-vscode-plugin/blob/main/README.md"); + expect(target).toEqual({ + kind: "blob", + owner: "makesPDF", + repo: "makespdf-vscode-plugin", + rawUrl: "https://github.com/makesPDF/makespdf-vscode-plugin/raw/main/README.md", + rawDirUrl: "https://github.com/makesPDF/makespdf-vscode-plugin/raw/main/", + rootRawDirUrl: "https://github.com/makesPDF/makespdf-vscode-plugin/raw/main/", + filename: "README.pdf", + }); + }); + + it("matches .markdown case-insensitively and nested directories", () => { + const target = matchGitHubMarkdown("https://github.com/acme/docs/blob/v2.1.0/guide/Intro.MARKDOWN"); + expect(target?.rawUrl).toBe("https://github.com/acme/docs/raw/v2.1.0/guide/Intro.MARKDOWN"); + expect(target?.rawDirUrl).toBe("https://github.com/acme/docs/raw/v2.1.0/guide/"); + expect(target?.filename).toBe("Intro.pdf"); + }); + + it("keeps refs containing slashes in the raw URL", () => { + const target = matchGitHubMarkdown("https://github.com/acme/docs/blob/feature/new-flow/docs/setup.md"); + expect(target?.rawUrl).toBe("https://github.com/acme/docs/raw/feature/new-flow/docs/setup.md"); + expect(target?.rawDirUrl).toBe("https://github.com/acme/docs/raw/feature/new-flow/docs/"); + }); + + it("ignores query strings and fragments", () => { + const target = matchGitHubMarkdown("https://github.com/acme/docs/blob/main/readme.md?plain=1#L10"); + expect(target?.rawUrl).toBe("https://github.com/acme/docs/raw/main/readme.md"); + expect(target?.filename).toBe("readme.pdf"); + }); + + it("percent-decodes the suggested filename and sanitizes it", () => { + const target = matchGitHubMarkdown("https://github.com/acme/docs/blob/main/My%20Notes%20%2F%20Draft.md"); + expect(target?.filename).toBe("My Notes - Draft.pdf"); + }); + + it("does not match non-markdown blob files", () => { + expect(matchGitHubMarkdown("https://github.com/acme/docs/blob/main/index.ts")).toBeNull(); + expect(matchGitHubMarkdown("https://github.com/acme/docs/blob/main/readme.md.txt")).toBeNull(); + }); + + it("does not match tree (directory) views, even when the directory is named *.md", () => { + expect(matchGitHubMarkdown("https://github.com/acme/docs/tree/main/docs")).toBeNull(); + expect(matchGitHubMarkdown("https://github.com/acme/docs/blob/main/notes.md/")).toBeNull(); + }); + + it("matches the repo home page and points at the default-branch README", () => { + const target = matchGitHubMarkdown("https://github.com/makesPDF/makespdf-browser-extension"); + expect(target).toEqual({ + kind: "home", + owner: "makesPDF", + repo: "makespdf-browser-extension", + rawUrl: "https://github.com/makesPDF/makespdf-browser-extension/raw/HEAD/README.md", + rawDirUrl: "https://github.com/makesPDF/makespdf-browser-extension/raw/HEAD/", + rootRawDirUrl: "https://github.com/makesPDF/makespdf-browser-extension/raw/HEAD/", + filename: "makespdf-browser-extension.pdf", + }); + expect(matchGitHubMarkdown("https://github.com/makesPDF/makespdf-browser-extension/")?.kind).toBe("home"); + }); + + it("does not match GitHub's own top-level routes", () => { + for (const path of ["/settings/profile", "/explore", "/notifications", "/orgs/acme", "/marketplace", "/search?q=x"]) { + expect(matchGitHubMarkdown(`https://github.com${path}`)).toBeNull(); + } + }); + + it("does not match other hosts, schemes or shapes", () => { + expect(matchGitHubMarkdown("https://gist.github.com/acme/1234")).toBeNull(); + expect(matchGitHubMarkdown("http://github.com/acme/docs/blob/main/readme.md")).toBeNull(); + expect(matchGitHubMarkdown("https://github.com/acme")).toBeNull(); + expect(matchGitHubMarkdown("https://github.com/acme/docs/blob/main")).toBeNull(); + expect(matchGitHubMarkdown("https://github.com/acme/docs/issues/12")).toBeNull(); + expect(matchGitHubMarkdown("not a url")).toBeNull(); + }); +}); + +describe("sanitizeFilename", () => { + it("strips path separators and reserved characters", () => { + expect(sanitizeFilename('a/b\\c:d*e?f"gi|j.pdf')).toBe("a-b-c-d-e-f-g-h-i-j.pdf"); + }); + + it("collapses whitespace and never returns an empty name", () => { + expect(sanitizeFilename(" spaced name.md ")).toBe("spaced name.md"); + expect(sanitizeFilename("///")).toBe("---"); + expect(sanitizeFilename("")).toBe("document.pdf"); + }); +}); diff --git a/tests/markdown-images.test.ts b/tests/markdown-images.test.ts new file mode 100644 index 0000000..a06f92e --- /dev/null +++ b/tests/markdown-images.test.ts @@ -0,0 +1,140 @@ +import { describe, expect, it } from "vitest"; +import { AssetError } from "../src/lib/assets"; +import { + MAX_IMAGE_COUNT, + findRelativeRefs, + formatImageFailure, + inlineRelativeImages, + prepareExportMarkdown, +} from "../src/lib/markdown-images"; + +const okResolve = async (src: string) => `data:image/png;base64,RESOLVED(${src})`; + +describe("findRelativeRefs", () => { + it("finds Markdown and HTML image references in document order", () => { + const markdown = [ + "![one](./a.png)", + '', + "![three]()", + "![four](d.png \"title\")", + ].join("\n\n"); + expect(findRelativeRefs(markdown)).toEqual(["./a.png", "b.png", "c.png", "d.png"]); + }); + + it("ignores absolute URLs, data URIs, protocol-relative and fragment refs", () => { + const markdown = [ + "![remote](https://example.com/x.png)", + "![proto](//cdn.example.com/x.png)", + "![inline](data:image/png;base64,AAAA)", + "![anchor](#section)", + ].join("\n"); + expect(findRelativeRefs(markdown)).toEqual([]); + }); + + it("ignores image-like text inside fenced and inline code", () => { + const markdown = [ + "```", + "![not real](./fenced.png)", + "```", + "`![also not](./inline.png)`", + "![real](./real.png)", + ].join("\n"); + expect(findRelativeRefs(markdown)).toEqual(["./real.png"]); + }); + + it("deduplicates repeated references", () => { + expect(findRelativeRefs("![a](x.png)\n![b](x.png)")).toEqual(["x.png"]); + }); +}); + +describe("inlineRelativeImages", () => { + it("replaces both syntaxes with the resolved data URI", async () => { + const markdown = '![shot](./img/shot.png)\n\nshot'; + const { markdown: out, failures } = await inlineRelativeImages(markdown, okResolve); + expect(failures).toEqual([]); + expect(out).toBe( + '![shot](data:image/png;base64,RESOLVED(./img/shot.png))\n\nshot', + ); + }); + + it("preserves a Markdown title after the URL", async () => { + const { markdown: out } = await inlineRelativeImages('![shot](shot.png "the title")', okResolve); + expect(out).toBe('![shot](data:image/png;base64,RESOLVED(shot.png) "the title")'); + }); + + it("leaves absolute references untouched", async () => { + const markdown = "![remote](https://example.com/x.png)"; + const { markdown: out, failures } = await inlineRelativeImages(markdown, okResolve); + expect(out).toBe(markdown); + expect(failures).toEqual([]); + }); + + it("reports an AssetError's reason against the reference", async () => { + const resolve = async (src: string) => { + throw new AssetError("could not be fetched (HTTP 404)", src); + }; + const { failures } = await inlineRelativeImages("![a](missing.png)\n![b](also.png)", resolve); + expect(failures).toEqual([ + { src: "missing.png", reason: "could not be fetched (HTTP 404)" }, + { src: "also.png", reason: "could not be fetched (HTTP 404)" }, + ]); + }); + + it("reports a non-AssetError rejection as a fetch failure", async () => { + const resolve = async () => { + throw new TypeError("Failed to fetch"); + }; + const { failures } = await inlineRelativeImages("![a](x.png)", resolve); + expect(failures).toEqual([{ src: "x.png", reason: "could not be fetched" }]); + }); +}); + +describe("formatImageFailure", () => { + it("returns null when nothing failed", () => { + expect(formatImageFailure([])).toBeNull(); + }); + + it("names a single failed reference, following the VS Code plugin's wording", () => { + expect(formatImageFailure([{ src: "img/shot.png", reason: "could not be fetched (HTTP 404)" }])).toBe( + "Export stopped, no PDF was written: 1 image could not be embedded: " + + "img/shot.png (could not be fetched (HTTP 404)). " + + "Fix or remove the reference and export again.", + ); + }); + + it("names several and counts the rest beyond ten", () => { + const failures = Array.from({ length: 12 }, (_, i) => ({ src: `img/${i}.png`, reason: "could not be fetched" })); + const message = formatImageFailure(failures); + expect(message).toContain("12 images could not be embedded"); + expect(message).toContain("img/0.png (could not be fetched)"); + expect(message).toContain("and 2 more"); + }); +}); + +describe("prepareExportMarkdown", () => { + it("stops with a named count above the 20-image cap", async () => { + const markdown = Array.from({ length: MAX_IMAGE_COUNT + 1 }, (_, i) => `![img](img/${i}.png)`).join("\n"); + const result = await prepareExportMarkdown(markdown, okResolve); + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.message).toContain(`references ${MAX_IMAGE_COUNT + 1} images`); + expect(result.message).toContain(`at most ${MAX_IMAGE_COUNT} can be`); + } + }); + + it("passes exactly at the cap", async () => { + const markdown = Array.from({ length: MAX_IMAGE_COUNT }, (_, i) => `![img](img/${i}.png)`).join("\n"); + const result = await prepareExportMarkdown(markdown, okResolve); + expect(result.ok).toBe(true); + }); + + it("stops with the image message when any reference fails", async () => { + const resolve = async (src: string) => { + if (src === "bad.png") throw new AssetError("too large to embed, max 5MB", src); + return "data:image/png;base64,AA=="; + }; + const result = await prepareExportMarkdown("![ok](good.png)\n![bad](bad.png)", resolve); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.message).toContain("bad.png (too large to embed, max 5MB)"); + }); +}); diff --git a/tests/render-client.test.ts b/tests/render-client.test.ts new file mode 100644 index 0000000..54bbf90 --- /dev/null +++ b/tests/render-client.test.ts @@ -0,0 +1,154 @@ +import { describe, expect, it } from "vitest"; +import { clientHeader } from "../src/lib/build-target"; +import { RENDER_MESSAGE_TYPE, type RenderRequest } from "../src/lib/messages"; +import { renderMarkdown } from "../src/lib/render-client"; +import { MD_ENDPOINT } from "../src/lib/service"; + +const REQUEST: RenderRequest = { + type: RENDER_MESSAGE_TYPE, + markdown: "# Title\n\n![shot](./img/shot.png)", + title: "README", + filename: "README.pdf", +}; + +interface Captured { + url: string; + init?: RequestInit; +} + +function captureFetch(...responses: (Response | Error)[]) { + const calls: Captured[] = []; + const fetchImpl = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + calls.push({ url, init }); + const next = responses.shift(); + if (next instanceof Error) throw next; + if (!next) throw new Error(`unexpected fetch: ${url}`); + return next; + }) as typeof fetch; + return { fetchImpl, calls }; +} + +function pdfResponse() { + return new Response(new Uint8Array([1, 2, 3]), { + status: 200, + headers: { "content-type": "application/pdf", "X-Pages": "2", "X-Render-Ms": "180" }, + }); +} + +describe("renderMarkdown", () => { + it("POSTs the markdown and options to /api/v1/md with the anonymous client header (chromium build)", async () => { + const { fetchImpl, calls } = captureFetch(pdfResponse()); + const result = await renderMarkdown(REQUEST, { + fetchImpl, + clientHeaderValue: clientHeader("0.1.0", "chromium"), + getApiKey: async () => null, + getStoredDefaults: async () => ({ pageSize: "A4", theme: "github" }), + }); + + expect(calls[0]?.url).toBe(MD_ENDPOINT); + expect(calls[0]?.init?.method).toBe("POST"); + const headers = calls[0]?.init?.headers as Record; + expect(headers["X-MakesPDF-Client"]).toBe("browser-extension/0.1.0+chromium"); + expect(headers.Authorization).toBeUndefined(); + expect(JSON.parse(String(calls[0]?.init?.body))).toEqual({ + markdown: REQUEST.markdown, + options: { title: "README", pageSize: "A4", theme: "github" }, + }); + + expect(result).toEqual({ + ok: true, + base64: "AQID", + filename: "README.pdf", + pages: "2", + renderMs: "180", + }); + }); + + it("pins the firefox build's header", async () => { + const { fetchImpl, calls } = captureFetch(pdfResponse()); + await renderMarkdown(REQUEST, { + fetchImpl, + clientHeaderValue: clientHeader("0.1.0", "firefox"), + getApiKey: async () => null, + }); + const headers = calls[0]?.init?.headers as Record; + expect(headers["X-MakesPDF-Client"]).toBe("browser-extension/0.1.0+firefox"); + }); + + it("sends a saved API key as a Bearer token, and omits page defaults when none are stored", async () => { + const { fetchImpl, calls } = captureFetch(pdfResponse()); + await renderMarkdown(REQUEST, { + fetchImpl, + clientHeaderValue: clientHeader("0.1.0", "chromium"), + getApiKey: async () => "secret-key", + }); + const headers = calls[0]?.init?.headers as Record; + expect(headers.Authorization).toBe("Bearer secret-key"); + expect(JSON.parse(String(calls[0]?.init?.body))).toEqual({ + markdown: REQUEST.markdown, + options: { title: "README" }, + }); + }); + + it("maps a 401 with a saved key to the key message", async () => { + const { fetchImpl } = captureFetch( + new Response(JSON.stringify({ error: "Authentication required." }), { status: 401 }), + ); + const result = await renderMarkdown(REQUEST, { + fetchImpl, + clientHeaderValue: clientHeader("0.1.0", "chromium"), + getApiKey: async () => "stale", + }); + expect(result).toEqual({ + ok: false, + kind: "auth", + message: "Authentication failed. Check the API key in the makesPDF extension options.", + }); + }); + + it("maps an anonymous 429 to a rate-limit message with the sign-up hint", async () => { + const { fetchImpl } = captureFetch(new Response("", { status: 429 })); + const result = await renderMarkdown(REQUEST, { + fetchImpl, + clientHeaderValue: clientHeader("0.1.0", "chromium"), + getApiKey: async () => null, + }); + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.kind).toBe("rate-limit"); + expect(result.message).toContain("sign up"); + } + }); + + it("maps a 413 to the payload message", async () => { + const { fetchImpl } = captureFetch(new Response(JSON.stringify({ error: "Payload too large" }), { status: 413 })); + const result = await renderMarkdown(REQUEST, { + fetchImpl, + clientHeaderValue: clientHeader("0.1.0", "chromium"), + getApiKey: async () => null, + }); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.kind).toBe("payload-too-large"); + }); + + it("maps a thrown fetch to a network message", async () => { + const { fetchImpl } = captureFetch(new TypeError("Failed to fetch")); + const result = await renderMarkdown(REQUEST, { + fetchImpl, + clientHeaderValue: clientHeader("0.1.0", "chromium"), + getApiKey: async () => null, + }); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.kind).toBe("network"); + }); + + it("sanitizes the returned filename", async () => { + const { fetchImpl } = captureFetch(pdfResponse()); + const result = await renderMarkdown( + { ...REQUEST, filename: 'weird/name:".pdf' }, + { fetchImpl, clientHeaderValue: clientHeader("0.1.0", "chromium"), getApiKey: async () => null }, + ); + expect(result.ok && result.filename).toBe("weird-name--.pdf"); + }); +}); diff --git a/tsconfig.json b/tsconfig.json index 7eb7d04..b4ad5a9 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -12,6 +12,7 @@ "forceConsistentCasingInFileNames": true, "isolatedModules": true, "verbatimModuleSyntax": true, + "allowJs": true, "resolveJsonModule": true, "skipLibCheck": true, "noEmit": true From 7631cfde2e581a3c93a0f8a30f583ed68c96492e Mon Sep 17 00:00:00 2001 From: lecstor Date: Tue, 13 Oct 2026 08:48:06 +1000 Subject: [PATCH 3/5] Bind fetch to the global scope; smoke fixtures and scripted Chromium smoke MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Native fetch throws Illegal invocation when invoked as a property of an object (background deps, adapter instance) — found by the real-browser smoke. boundFetch() is now the single place fetch is bound. Chromium smoke (scripted, against production): button injected on a blob view, real anonymous render downloaded as fixture.pdf, soft navigation to second.md leaves exactly one working button, repo-home README button present. Firefox half remains manual. --- README.md | 17 +++++++++++++++++ smoke/chromium-smoke.mjs | 19 ++++++++++++++----- src/adapters/github.ts | 7 +++++-- src/adapters/types.ts | 4 +++- src/background.ts | 3 ++- src/lib/controller.ts | 5 +++-- src/lib/fetch.ts | 15 +++++++++++++++ src/lib/render-client.ts | 9 +++++++-- tests/github-adapter.test.ts | 11 +++++++++++ tests/render-client.test.ts | 14 ++++++++++++++ 10 files changed, 91 insertions(+), 13 deletions(-) create mode 100644 src/lib/fetch.ts diff --git a/README.md b/README.md index 2bb3d5a..fc9958b 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,23 @@ npm run build # dist/chromium + dist/firefox (+ zips) npm run verify:packages # structural checks over dist/ (loadability gate) ``` +### Manual smoke + +`smoke/` holds the public fixture (`fixture.md` + `logo.png`, plus +`second.md` for soft navigation) and a scripted Chromium pass over the built +package: + +```bash +node smoke/chromium-smoke.mjs # needs Playwright available; see the script +SMOKE_REF= node smoke/chromium-smoke.mjs # while the fixture is unmerged +``` + +It loads `dist/chromium`, clicks the button on the fixture, checks the +downloaded PDF, soft-navigates to `second.md` and checks the button stays +singular. The Firefox half of the manual smoke (`about:debugging` → Load +Temporary Add-on → `dist/firefox`) is still manual: a private-repo file with +relative images, and the same fixture flow. + Unit tests cover URL matching (including refs containing `/`), relative path resolution, the image limits and failure messages, the HTTP error mapping, the `X-MakesPDF-Client` value per package (pinned both as a function and as a diff --git a/smoke/chromium-smoke.mjs b/smoke/chromium-smoke.mjs index d0a7ba1..c879e18 100644 --- a/smoke/chromium-smoke.mjs +++ b/smoke/chromium-smoke.mjs @@ -25,6 +25,12 @@ import assert from "node:assert/strict"; const ROOT = join(dirname(fileURLToPath(import.meta.url)), ".."); const REPO = "https://github.com/makesPDF/makespdf-browser-extension"; +// Which ref to smoke. `main` once the fixtures are merged; point SMOKE_REF at +// the task branch while the fixture only exists there (slash-containing refs +// are exactly the case the raw-URL derivation must survive). +const REF = process.env.SMOKE_REF ?? "main"; +// A public repo whose README sits on its default branch, for the repo-home check. +const README_REPO = "https://github.com/makesPDF/makespdf-vscode-plugin"; const EXTENSION = process.env.EXTENSION_DIR ?? join(ROOT, "dist/chromium"); const OUT = process.env.SMOKE_OUT ?? join(tmpdir(), `makespdf-smoke-${process.pid}`); @@ -58,11 +64,14 @@ const context = await chromium.launchPersistentContext(join(OUT, "profile"), { const page = await context.newPage(); const pageErrors = []; const consoleMessages = []; +const watchWorker = (worker) => { + worker.on("console", (message) => consoleMessages.push(`sw ${message.type()}: ${message.text()}`)); + worker.on("close", () => consoleMessages.push("sw closed")); +}; page.on("pageerror", (error) => pageErrors.push(String(error))); page.on("console", (message) => consoleMessages.push(`page ${message.type()}: ${message.text()}`)); -context.on("serviceworker", (worker) => { - worker.on("console", (message) => consoleMessages.push(`sw ${message.type()}: ${message.text()}`)); -}); +for (const worker of context.serviceWorkers()) watchWorker(worker); +context.on("serviceworker", watchWorker); let failed = false; const step = (message) => console.log(`→ ${message}`); @@ -70,7 +79,7 @@ const ok = (message) => console.log(` ✓ ${message}`); try { step("blob view of smoke/fixture.md"); - await page.goto(`${REPO}/blob/main/smoke/fixture.md`, { waitUntil: "domcontentloaded" }); + await page.goto(`${REPO}/blob/${REF}/smoke/fixture.md`, { waitUntil: "domcontentloaded" }); await page.waitForSelector("#makespdf-download-pdf-button", { timeout: 45_000 }); assert.equal(await page.locator("#makespdf-download-pdf-button").count(), 1, "exactly one button"); ok("button injected"); @@ -114,7 +123,7 @@ try { ok(`${secondBytes.length} bytes as second.pdf`); step("repo home README"); - await page.goto(REPO, { waitUntil: "domcontentloaded" }); + await page.goto(README_REPO, { waitUntil: "domcontentloaded" }); await page.waitForSelector("#makespdf-download-pdf-host #makespdf-download-pdf-button", { timeout: 45_000 }); ok("home button present"); } catch (error) { diff --git a/src/adapters/github.ts b/src/adapters/github.ts index 4a7fb94..42b8b9f 100644 --- a/src/adapters/github.ts +++ b/src/adapters/github.ts @@ -12,6 +12,7 @@ import { AssetError, MarkdownFetchError } from "../lib/assets"; import { base64FromBytes } from "../lib/bytes"; import { injectDownloadButton } from "../lib/button"; +import { boundFetch, type FetchLike } from "../lib/fetch"; import { matchGitHubMarkdown, sanitizeFilename, @@ -26,12 +27,14 @@ const FETCH_TIMEOUT_MS = 15_000; export class GitHubMarkdownAdapter implements MarkdownAdapter { private readonly target: GitHubMarkdownTarget; private readonly document: Document; - private readonly fetchImpl: typeof fetch; + private readonly fetchImpl: FetchLike; constructor(target: GitHubMarkdownTarget, context: Pick) { this.target = target; this.document = context.document; - this.fetchImpl = context.fetchImpl; + // Bound here: calling `this.fetchImpl(…)` would otherwise invoke native + // fetch with the adapter as `this` and throw Illegal invocation. + this.fetchImpl = boundFetch(context.fetchImpl); } matches(url: URL): boolean { diff --git a/src/adapters/types.ts b/src/adapters/types.ts index 428671b..387f7a8 100644 --- a/src/adapters/types.ts +++ b/src/adapters/types.ts @@ -4,13 +4,15 @@ * Markdown source, asset resolution, button injection, filename. */ +import type { FetchLike } from "../lib/fetch"; + export interface AdapterContext { /** The page URL the adapter was created for. */ url: URL; /** The page document, for button injection. */ document: Document; /** `fetch` bound to the page's session; injected for tests. */ - fetchImpl: typeof fetch; + fetchImpl: FetchLike; } export interface MarkdownAdapter { diff --git a/src/background.ts b/src/background.ts index 9ff2868..db1b526 100644 --- a/src/background.ts +++ b/src/background.ts @@ -6,6 +6,7 @@ import browser from "webextension-polyfill"; import { CLIENT_HEADER } from "./lib/build-target"; +import { boundFetch } from "./lib/fetch"; import { RENDER_MESSAGE_TYPE, type RenderRequest } from "./lib/messages"; import { renderMarkdown, type StoredDefaults } from "./lib/render-client"; @@ -20,7 +21,7 @@ function isRenderRequest(message: unknown): message is RenderRequest { browser.runtime.onMessage.addListener((message: unknown) => { if (!isRenderRequest(message)) return undefined; return renderMarkdown(message, { - fetchImpl: fetch, + fetchImpl: boundFetch(), clientHeaderValue: CLIENT_HEADER, getApiKey: async () => { const stored = await browser.storage.local.get("apiKey"); diff --git a/src/lib/controller.ts b/src/lib/controller.ts index abb6294..396ae5d 100644 --- a/src/lib/controller.ts +++ b/src/lib/controller.ts @@ -14,6 +14,7 @@ import { findAdapter } from "../adapters/registry"; import { MarkdownFetchError } from "./assets"; import { BUTTON_ID, removeInjected, renderButtonState } from "./button"; import { downloadBase64Pdf, suggestedTitleFromFilename } from "./download"; +import { boundFetch, type FetchLike } from "./fetch"; import { matchGitHubMarkdown } from "./github-url"; import { prepareExportMarkdown } from "./markdown-images"; import { RENDER_MESSAGE_TYPE, type RenderRequest, type RenderResponse } from "./messages"; @@ -30,7 +31,7 @@ export interface ControllerOptions { /** Sends the render request to the background; injected for tests. */ sendMessage: (request: RenderRequest) => Promise; /** Page-session fetch; defaults to the global fetch. */ - fetchImpl?: typeof fetch; + fetchImpl?: FetchLike; } /** @@ -40,7 +41,7 @@ export interface ControllerOptions { */ export function startController(options: ControllerOptions): () => void { const doc = options.document; - const fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis); + const fetchImpl = boundFetch(options.fetchImpl); let busy = false; let buttonHref: string | null = null; let debounce: ReturnType | null = null; diff --git a/src/lib/fetch.ts b/src/lib/fetch.ts new file mode 100644 index 0000000..7994af1 --- /dev/null +++ b/src/lib/fetch.ts @@ -0,0 +1,15 @@ +/** + * Fetch plumbing. + * + * Native `fetch` is unforgiving about its receiver: calling `deps.fetchImpl(…)` + * or `this.fetchImpl(…)` invokes it with the wrong `this` and throws + * `TypeError: Illegal invocation` in workers. Every fetch handed to, or used + * by, this extension is bound to the global scope exactly once here. + */ + +export type FetchLike = typeof fetch; + +/** `fetchImpl` bound to the global scope, falling back to the ambient fetch. */ +export function boundFetch(fetchImpl?: FetchLike): FetchLike { + return (fetchImpl ?? globalThis.fetch).bind(globalThis); +} diff --git a/src/lib/render-client.ts b/src/lib/render-client.ts index 604d7f0..22e69f4 100644 --- a/src/lib/render-client.ts +++ b/src/lib/render-client.ts @@ -11,6 +11,7 @@ import { base64FromBytes } from "./bytes"; import { CLIENT_HEADER } from "./build-target"; import { mapFetchError, mapHttpError } from "./errors"; +import { boundFetch, type FetchLike } from "./fetch"; import { sanitizeFilename } from "./github-url"; import type { RenderRequest, RenderResponse } from "./messages"; import { MD_ENDPOINT } from "./service"; @@ -24,7 +25,7 @@ export interface StoredDefaults { } export interface RenderDeps { - fetchImpl: typeof fetch; + fetchImpl: FetchLike; /** * The `X-MakesPDF-Client` value; defaults to this bundle's baked header. * Injecting it lets the tests pin a header per package. @@ -53,15 +54,19 @@ export async function renderMarkdown(input: RenderRequest, deps: RenderDeps): Pr // failed auth attempt server-side. if (apiKey) headers.Authorization = `Bearer ${apiKey}`; + const fetchImpl = boundFetch(deps.fetchImpl); let response: Response; try { - response = await deps.fetchImpl(MD_ENDPOINT, { + response = await fetchImpl(MD_ENDPOINT, { method: "POST", headers, body: JSON.stringify({ markdown: input.markdown, options }), signal: AbortSignal.timeout(RENDER_TIMEOUT_MS), }); } catch (error) { + // Visible in the background's own console (chrome://extensions → service + // worker); the user sees the mapped message. + console.error("makesPDF render request failed", error); return { ok: false, ...mapFetchError(error) }; } diff --git a/tests/github-adapter.test.ts b/tests/github-adapter.test.ts index 3c3356f..81cfcfe 100644 --- a/tests/github-adapter.test.ts +++ b/tests/github-adapter.test.ts @@ -76,6 +76,17 @@ describe("GitHubMarkdownAdapter.resolveAsset", () => { expect(calls[0]?.init?.redirect).toBe("follow"); }); + it("calls fetch with the global receiver, not the adapter (native fetch throws otherwise)", async () => { + let receiver: unknown = "unset"; + const fetchImpl = function (this: unknown) { + receiver = this; + return Promise.resolve(imageResponse()); + } as unknown as typeof fetch; + const adapter = adapterFor("https://github.com/acme/docs/blob/main/readme.md", fetchImpl); + await adapter.resolveAsset("shot.png"); + expect(receiver).toBe(globalThis); + }); + it("rejects a path that escapes the repository", async () => { const { fetchImpl } = fakeFetch([]); const adapter = adapterFor("https://github.com/acme/docs/blob/main/readme.md", fetchImpl); diff --git a/tests/render-client.test.ts b/tests/render-client.test.ts index 54bbf90..020630d 100644 --- a/tests/render-client.test.ts +++ b/tests/render-client.test.ts @@ -143,6 +143,20 @@ describe("renderMarkdown", () => { if (!result.ok) expect(result.kind).toBe("network"); }); + it("calls fetch with the global receiver, not the deps object (native fetch throws otherwise)", async () => { + let receiver: unknown = "unset"; + const fetchImpl = function (this: unknown) { + receiver = this; + return Promise.resolve(pdfResponse()); + } as unknown as typeof fetch; + await renderMarkdown(REQUEST, { + fetchImpl, + clientHeaderValue: clientHeader("0.1.0", "chromium"), + getApiKey: async () => null, + }); + expect(receiver).toBe(globalThis); + }); + it("sanitizes the returned filename", async () => { const { fetchImpl } = captureFetch(pdfResponse()); const result = await renderMarkdown( From 8effe0491ef401fb034a5931f95246e339ab365d Mon Sep 17 00:00:00 2001 From: lecstor Date: Tue, 13 Oct 2026 08:48:41 +1000 Subject: [PATCH 4/5] README: reference-style images are a known MVP gap --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index fc9958b..9d8df32 100644 --- a/README.md +++ b/README.md @@ -134,6 +134,9 @@ soft navigation. ### Limitations (MVP) - GitHub only; `.md`/`.markdown` file views and repo-home READMEs. +- Inline images only: `![alt](./x.png)` and ``. Reference-style + images (`![alt][id]` with `[id]: ./x.png`) are not inlined yet, so the + server drops the unfetchable relative URL (it reports a layout warning). - At most 20 relative images per document; more stops the export. - Root-relative image paths (`/img.png`) are resolved at the first path segment after `/blob/` as the ref — refs containing `/` combined with From 98f49f748e6c49f4ce1c69f23fc39df13486db46 Mon Sep 17 00:00:00 2001 From: Jason Galea Date: Tue, 13 Oct 2026 09:17:23 +1000 Subject: [PATCH 5/5] Phase-2 review fixes: README case variants, whole-document image cap, Firefox Xray base64; scripted Firefox smoke MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adversarial review findings, each with a regression test: - Repo-home READMEs: the raw route is a case-sensitive path lookup, so README.md/readme.md/Readme.md/…markdown are all tried. - The 20-image pre-flight now counts every img src (relative, absolute, data:), because the server's cap counts the whole document and skips the extras without a trace. - The home button always floats; a rendered README's own /raw/ link is page content, not the header's Raw button, and must not become an insertion point. - base64FromBytes no longer spreads a typed array: in Firefox content scripts that spread trips the Xray compartment check ('Permission denied to access property "constructor"'), which broke every image inlining. Found by the Firefox smoke. - smoke/firefox-smoke.mjs drives the real Firefox over Marionette (web-ext temporary install) and runs the same flow as the Chromium smoke; it caught the Xray bug end to end. --- README.md | 17 +- smoke/firefox-smoke.mjs | 297 ++++++++++++++++++++++++++++++++++ src/adapters/github.ts | 26 ++- src/lib/button.ts | 9 +- src/lib/bytes.ts | 14 +- src/lib/markdown-images.ts | 22 ++- tests/button.test.ts | 14 ++ tests/github-adapter.test.ts | 21 ++- tests/markdown-images.test.ts | 19 ++- 9 files changed, 414 insertions(+), 25 deletions(-) create mode 100644 smoke/firefox-smoke.mjs diff --git a/README.md b/README.md index 9d8df32..3df4bf4 100644 --- a/README.md +++ b/README.md @@ -121,9 +121,20 @@ SMOKE_REF= node smoke/chromium-smoke.mjs # while the fixture is unmerg It loads `dist/chromium`, clicks the button on the fixture, checks the downloaded PDF, soft-navigates to `second.md` and checks the button stays -singular. The Firefox half of the manual smoke (`about:debugging` → Load -Temporary Add-on → `dist/firefox`) is still manual: a private-repo file with -relative images, and the same fixture flow. +singular. + +The Firefox package has the same scripted smoke, driven through the real +Firefox over Marionette (`web-ext run` installs `dist/firefox` temporarily — +Playwright cannot load extensions in its Firefox): + +```bash +node smoke/firefox-smoke.mjs # needs FIREFOX_BIN; see the script +SMOKE_REF= node smoke/firefox-smoke.mjs # while the fixture is unmerged +``` + +It runs the same flow end to end (render, download, soft navigation, repo +home). Still manual on top of both scripts: a **private-repo** file with +relative images. Unit tests cover URL matching (including refs containing `/`), relative path resolution, the image limits and failure messages, the HTTP error mapping, the diff --git a/smoke/firefox-smoke.mjs b/smoke/firefox-smoke.mjs new file mode 100644 index 0000000..06d7d05 --- /dev/null +++ b/smoke/firefox-smoke.mjs @@ -0,0 +1,297 @@ +/** + * Firefox smoke for the built extension — the scripted half of the manual + * smoke the PR records. Not part of CI (it needs a real browser, web-ext and + * the production service). + * + * npm run build + * node smoke/firefox-smoke.mjs + * + * Playwright cannot load extensions in its Firefox, so this drives the real + * Firefox instead: `web-ext run` installs dist/firefox as a temporary add-on + * (unsigned, no store), and a small Marionette client (enabled through the + * profile's user.js) checks the same flow the Chromium smoke checks — the + * injected button, a real anonymous render downloaded as fixture.pdf, a soft + * navigation that leaves exactly one button, and the repo-home button. + * + * Environment: + * FIREFOX_BIN Firefox binary (default /Applications/Firefox.app/...) + * EXTENSION_DIR built package to load (default dist/firefox) + * SMOKE_REF ref of the fixtures (default main; point at the task + * branch while the fixtures are unmerged) + * SMOKE_OUT artifact directory (default a fresh temp dir) + * + * web-ext is resolved with `npx --yes web-ext` (it is not a repo dependency, + * like Playwright for the Chromium smoke). + */ + +import { spawn } from "node:child_process"; +import net from "node:net"; +import { existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import assert from "node:assert/strict"; + +const ROOT = join(dirname(fileURLToPath(import.meta.url)), ".."); +const EXTENSION = process.env.EXTENSION_DIR ?? join(ROOT, "dist/firefox"); +const FIREFOX_BIN = process.env.FIREFOX_BIN ?? "/Applications/Firefox.app/Contents/MacOS/firefox"; +const REF = process.env.SMOKE_REF ?? "main"; +const OUT = process.env.SMOKE_OUT ?? mkdtempSync(join(tmpdir(), "makespdf-ff-smoke-")); +const PROFILE = join(OUT, "profile"); +const DOWNLOADS = join(OUT, "downloads"); +const LOG = join(OUT, "web-ext.log"); +const PORT = 2828; +const REPO = "https://github.com/makesPDF/makespdf-browser-extension"; +const README_REPO = "https://github.com/makesPDF/makespdf-vscode-plugin"; + +mkdirSync(PROFILE, { recursive: true }); +mkdirSync(DOWNLOADS, { recursive: true }); +writeFileSync( + join(PROFILE, "user.js"), + [ + 'user_pref("marionette.enabled", true);', + `user_pref("marionette.port", ${PORT});`, + 'user_pref("browser.download.folderList", 2);', + `user_pref("browser.download.dir", "${DOWNLOADS}");`, + 'user_pref("browser.download.useDownloadDir", true);', + 'user_pref("browser.download.alwaysOpenPanel", false);', + 'user_pref("browser.download.start_downloads_in_tmp_dir", false);', + 'user_pref("browser.helperApps.neverAsk.saveToDisk", "application/pdf,image/png,text/plain,application/octet-stream");', + 'user_pref("browser.shell.checkDefaultBrowser", false);', + "", + ].join("\n"), +); + +const logFd = openSync(LOG, "w"); +const child = spawn( + "npx", + [ + "--yes", "web-ext", "run", + "--source-dir", EXTENSION, + "--firefox", FIREFOX_BIN, + "--firefox-profile", PROFILE, + "--keep-profile-changes", + "--args=--headless", + "--args=--marionette", + "--no-reload", + "--no-input", + "--verbose", + ], + { detached: true, stdio: ["ignore", logFd, logFd] }, +); + +let childExited = false; +let childCode = null; +child.on("exit", (code) => { + childExited = true; + childCode = code; +}); + +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +async function waitForPort(timeoutMs) { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + if (childExited) throw new Error(`web-ext exited early (code ${childCode})`); + const open = await new Promise((resolve) => { + const socket = net.connect({ host: "127.0.0.1", port: PORT }, () => { + socket.destroy(); + resolve(true); + }); + socket.on("error", () => resolve(false)); + }); + if (open) return; + await sleep(500); + } + throw new Error("timed out waiting for the Marionette port"); +} + +/** Minimal Marionette client: length-prefixed JSON, commands [0, id, name, params]. */ +class Marionette { + constructor() { + this.buf = Buffer.alloc(0); + this.nextId = 1; + this.pending = new Map(); + } + + connect() { + return new Promise((resolve, reject) => { + this.socket = net.connect({ host: "127.0.0.1", port: PORT }); + this.socket.on("connect", resolve); + this.socket.on("error", reject); + this.socket.on("data", (chunk) => this.onData(chunk)); + }); + } + + onData(chunk) { + this.buf = Buffer.concat([this.buf, chunk]); + for (;;) { + const colon = this.buf.indexOf(0x3a); + if (colon < 0) return; + const length = Number.parseInt(this.buf.subarray(0, colon).toString("utf8"), 10); + if (!Number.isFinite(length)) throw new Error("bad Marionette frame"); + const start = colon + 1; + if (this.buf.length < start + length) return; + const payload = JSON.parse(this.buf.subarray(start, start + length).toString("utf8")); + this.buf = this.buf.subarray(start + length); + if (Array.isArray(payload) && payload[0] === 1) { + const [, id, error, result] = payload; + const entry = this.pending.get(id); + if (!entry) continue; + this.pending.delete(id); + if (error) entry.reject(new Error(`${error.error}: ${error.message}`)); + else entry.resolve(result); + } + } + } + + send(command, params = {}) { + const id = this.nextId++; + const bytes = Buffer.from(JSON.stringify([0, id, command, params]), "utf8"); + this.socket.write(`${bytes.length}:`); + this.socket.write(bytes); + return new Promise((resolve, reject) => { + this.pending.set(id, { resolve, reject }); + }); + } +} + +let failed = false; +const step = (message) => console.log(`→ ${message}`); +const ok = (message) => console.log(` ✓ ${message}`); + +try { + step(`loading ${EXTENSION} into Firefox (${FIREFOX_BIN})`); + await waitForPort(120_000); + await sleep(2_000); + + const marionette = new Marionette(); + await marionette.connect(); + await sleep(500); + await marionette.send("WebDriver:NewSession", { capabilities: { alwaysMatch: {} } }); + + // ExecuteScript results are WebDriver primitives ({value: …}); the script + // body must `return` explicitly. + const script = async (source) => { + const result = await marionette.send("WebDriver:ExecuteScript", { script: source, args: [] }); + return result !== null && typeof result === "object" && "value" in result ? result.value : result; + }; + const navigate = (url) => marionette.send("WebDriver:Navigate", { url }); + + const pollScript = async (source, label, timeoutMs = 45_000) => { + const deadline = Date.now() + timeoutMs; + for (;;) { + let value; + try { + value = await script(source); + } catch (error) { + value = `error: ${error.message}`; + } + if (value !== null && value !== false && value !== 0 && value !== "" && !String(value).startsWith("error:")) { + return value; + } + if (Date.now() > deadline) throw new Error(`timed out waiting for: ${label} (last: ${String(value)})`); + await sleep(1_000); + } + }; + + const statusText = `((document.getElementById('makespdf-download-pdf-status') || {}).textContent || '')`; + const buttonCount = `return document.querySelectorAll('#makespdf-download-pdf-button').length;`; + + step(`blob view of smoke/fixture.md at ${REF}`); + await navigate(`${REPO}/blob/${REF}/smoke/fixture.md`); + await pollScript(buttonCount, "button injected"); + assert.equal(await script(buttonCount), 1, "exactly one button"); + ok("button injected"); + + step("click Download PDF"); + await script(`document.getElementById('makespdf-download-pdf-button').click(); return true;`); + // Watch button/status transitions so a failure names the phase it stopped in. + const probe = `return JSON.stringify({ + button: ((document.getElementById('makespdf-download-pdf-button') || {}).textContent || null), + status: ((document.getElementById('makespdf-download-pdf-status') || {}).textContent || null) + });`; + let lastState = ""; + let saved = ""; + const probeDeadline = Date.now() + 150_000; + for (;;) { + const state = await script(probe); + if (state !== lastState) { + console.log(` state: ${state}`); + lastState = state; + } + const parsed = JSON.parse(state); + if ((parsed.status || "").startsWith("Saved")) { + saved = parsed.status; + break; + } + if ((parsed.status || "").length > 0) throw new Error(`export reported an error: ${parsed.status}`); + if (Date.now() > probeDeadline) throw new Error(`no render result after 150s; last state: ${state}`); + await sleep(2_000); + } + ok(`status: ${saved}`); + + const firstPath = join(DOWNLOADS, "fixture.pdf"); + const deadline = Date.now() + 30_000; + while (!existsSync(firstPath)) { + if (Date.now() > deadline) throw new Error(`fixture.pdf not in ${DOWNLOADS}`); + await sleep(500); + } + const bytes = readFileSync(firstPath); + assert.equal(bytes.subarray(0, 5).toString(), "%PDF-", "PDF magic bytes"); + assert.ok(bytes.length > 5_000, `PDF is ${bytes.length} bytes`); + ok(`fixture.pdf ${bytes.length} bytes`); + + step("soft-navigate to smoke/second.md"); + await script(`document.querySelector('a[href$="second.md"]').click(); return true;`); + await pollScript(`return location.pathname.endsWith('second.md') ? 'yes' : '';`, "URL changed"); + await sleep(1_000); + assert.equal(await script(buttonCount), 1, "still exactly one button"); + ok("no duplicate button after soft navigation"); + + await script(`document.getElementById('makespdf-download-pdf-button').click(); return true;`); + const secondSaved = await pollScript( + `return (() => { const t = ${statusText}; return t.startsWith('Saved second') ? t : ''; })();`, + "second download status", + 180_000, + ); + ok(`status: ${secondSaved}`); + const secondPath = join(DOWNLOADS, "second.pdf"); + const secondDeadline = Date.now() + 30_000; + while (!existsSync(secondPath)) { + if (Date.now() > secondDeadline) throw new Error(`second.pdf not in ${DOWNLOADS}`); + await sleep(500); + } + assert.equal(readFileSync(secondPath).subarray(0, 5).toString(), "%PDF-"); + ok(`second.pdf ${readFileSync(secondPath).length} bytes`); + + step("repo home README"); + await navigate(README_REPO); + await pollScript( + `return document.querySelectorAll('#makespdf-download-pdf-host #makespdf-download-pdf-button').length;`, + "home button present", + ); + ok("home button present"); + + await marionette.send("WebDriver:DeleteSession"); + marionette.socket.end(); +} catch (error) { + failed = true; + console.error(`\nFIREFOX SMOKE FAILED: ${error instanceof Error ? error.message : String(error)}`); + try { + console.error("--- web-ext log tail ---"); + console.error(readFileSync(LOG, "utf8").split("\n").slice(-25).join("\n")); + } catch { + // log may not exist + } +} finally { + try { + process.kill(-child.pid, "SIGTERM"); + } catch { + // already gone + } + await sleep(1_000); +} + +if (failed) process.exit(1); +console.log(`\nFIREFOX SMOKE PASSED (artifacts in ${OUT})`); diff --git a/src/adapters/github.ts b/src/adapters/github.ts index 42b8b9f..f7f86b0 100644 --- a/src/adapters/github.ts +++ b/src/adapters/github.ts @@ -24,6 +24,23 @@ import type { AdapterContext, AdapterFactory, MarkdownAdapter } from "./types"; const FETCH_TIMEOUT_MS = 15_000; +/** + * Repo-home README filenames, in the order tried. + * + * GitHub's rendered home page finds a README under any of these spellings, but + * the raw route is a case-sensitive path lookup — `sindresorhus/awesome`'s + * lowercase `readme.md` 404s at `/raw/HEAD/README.md` — so the raw fetch has + * to try the common cases itself. + */ +const HOME_README_CANDIDATES = [ + "README.md", + "readme.md", + "Readme.md", + "README.markdown", + "readme.markdown", + "Readme.markdown", +] as const; + export class GitHubMarkdownAdapter implements MarkdownAdapter { private readonly target: GitHubMarkdownTarget; private readonly document: Document; @@ -43,14 +60,15 @@ export class GitHubMarkdownAdapter implements MarkdownAdapter { /** * Fetch the raw Markdown through the page's session. Never scrapes the - * rendered page. The repo home tries README.md then README.markdown; a blob - * view fetches its own raw URL (which works for any ref, including tags and - * SHAs, and for refs containing slashes — GitHub resolves them server-side). + * rendered page. The repo home tries the common README filename cases (the + * raw route is case-sensitive); a blob view fetches its own raw URL (which + * works for any ref, including tags and SHAs, and for refs containing + * slashes — GitHub resolves them server-side). */ async getMarkdown(): Promise { const urls = this.target.kind === "home" - ? [this.target.rawUrl, this.target.rawUrl.replace(/README\.md$/i, "README.markdown")] + ? HOME_README_CANDIDATES.map((name) => `${this.target.rawDirUrl}${name}`) : [this.target.rawUrl]; for (const url of urls) { diff --git a/src/lib/button.ts b/src/lib/button.ts index 92e1fdd..d8aa76d 100644 --- a/src/lib/button.ts +++ b/src/lib/button.ts @@ -65,7 +65,12 @@ interface InsertionPoint { before: Node | null; } -/** The header container to join, or null when the page offers none. */ +/** + * The blob header container to join, or null when the page offers none. + * Blob views only: a repo home page's rendered README can itself link to + * `/owner/repo/raw/...`, which would look like a header Raw link and plant the + * button inside the README — the home button always floats instead. + */ function findBlobHost(doc: Document): InsertionPoint | null { const raw = findRawLink(doc); if (!raw) return null; @@ -121,7 +126,7 @@ export function injectDownloadButton( status.setAttribute("aria-live", "polite"); status.style.cssText = STATUS_STYLE; - const host = findBlobHost(doc); + const host = target.kind === "blob" ? findBlobHost(doc) : null; if (host) { host.parent.insertBefore(button, host.before); host.parent.insertBefore(status, host.before); diff --git a/src/lib/bytes.ts b/src/lib/bytes.ts index f276989..7e04a45 100644 --- a/src/lib/bytes.ts +++ b/src/lib/bytes.ts @@ -1,11 +1,21 @@ /** Base64 ↔ bytes helpers usable in service workers and content scripts alike. */ -/** Encode bytes as base64, chunked so large payloads don't blow the call stack. */ +/** + * Encode bytes as base64, chunked so large payloads don't blow the call stack. + * + * The code units are read into a plain array first: spreading the typed array + * itself (`String.fromCharCode(...bytes.subarray(…))`) trips Firefox's Xray + * compartment check inside content scripts with `Permission denied to access + * property "constructor"` (found by the MAK-200 Firefox smoke). + */ export function base64FromBytes(bytes: Uint8Array): string { let binary = ""; const CHUNK = 0x8000; for (let i = 0; i < bytes.length; i += CHUNK) { - binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK)); + const end = Math.min(i + CHUNK, bytes.length); + const codes: number[] = []; + for (let j = i; j < end; j++) codes.push(bytes[j] ?? 0); + binary += String.fromCharCode(...codes); } return btoa(binary); } diff --git a/src/lib/markdown-images.ts b/src/lib/markdown-images.ts index a128457..82ada0c 100644 --- a/src/lib/markdown-images.ts +++ b/src/lib/markdown-images.ts @@ -107,18 +107,27 @@ function collectRefs(source: string): { masked: string; restore: (value: string) return { masked, restore, refs: found.map((entry) => entry.src) }; } -/** Unique relative image references, in document order. */ -export function findRelativeRefs(source: string): string[] { +/** + * Unique image references in document order, whatever their scheme — these + * are the `img` srcs the server sees after the export, so they are also the + * ones its per-document image cap counts. + */ +export function collectImageRefs(source: string): string[] { const seen = new Set(); const out: string[] = []; for (const ref of collectRefs(source).refs) { - if (!ref || !isRelativeAsset(ref) || seen.has(ref)) continue; + if (!ref || seen.has(ref)) continue; seen.add(ref); out.push(ref); } return out; } +/** Unique relative image references, in document order. */ +export function findRelativeRefs(source: string): string[] { + return collectImageRefs(source).filter(isRelativeAsset); +} + /** * Replace relative image references with base64 `data:` URIs produced by * `resolve`. Rejections carrying an `AssetError` name their reason; anything @@ -192,13 +201,16 @@ export async function prepareExportMarkdown( source: string, resolve: (src: string) => Promise, ): Promise { - const refs = findRelativeRefs(source); + // The server's cap counts every image src in the document (inlined data: + // URIs and absolute URLs included) and drops the ones past it without a + // trace, so the pre-flight counts the same set: relative and absolute. + const refs = collectImageRefs(source); if (refs.length > MAX_IMAGE_COUNT) { return { ok: false, message: `Export stopped, no PDF was written: the document references ${refs.length} ` + - `images that must be embedded, but at most ${MAX_IMAGE_COUNT} can be. ` + + `images, but at most ${MAX_IMAGE_COUNT} can be embedded per document. ` + "Remove some images and export again.", }; } diff --git a/tests/button.test.ts b/tests/button.test.ts index 0937e31..89e24b2 100644 --- a/tests/button.test.ts +++ b/tests/button.test.ts @@ -70,6 +70,20 @@ describe("injectDownloadButton", () => { expect(document.getElementById(FLOATING_HOST_ID)).not.toBeNull(); }); + it("keeps the home button floating even when the README links to a raw path", () => { + // A README may link to `/owner/repo/raw/...` itself; that is page content, + // not the header's Raw button, and the button must not land inside it. + document.body.innerHTML = + '
'; + expect(injectDownloadButton(document, HOME_TARGET, () => {})).toBe(true); + + expect(document.getElementById(FLOATING_HOST_ID)).not.toBeNull(); + const readme = document.getElementById("readme"); + expect(readme?.querySelector(`#${BUTTON_ID}`)).toBeNull(); + expect(readme?.querySelector("a")?.getAttribute("href")).toBe("/acme/docs/raw/main/logo.png"); + }); + it("removeInjected clears the button, status and floating host", () => { injectDownloadButton(document, BLOB_TARGET, () => {}); removeInjected(document); diff --git a/tests/github-adapter.test.ts b/tests/github-adapter.test.ts index 81cfcfe..e42f456 100644 --- a/tests/github-adapter.test.ts +++ b/tests/github-adapter.test.ts @@ -140,7 +140,7 @@ describe("GitHubMarkdownAdapter.getMarkdown", () => { expect(calls[0]?.url).toBe("https://github.com/acme/docs/raw/main/readme.md"); }); - it("tries README.markdown when README.md is missing on the repo home", async () => { + it("falls back to a lowercase readme.md on the repo home (the raw route is case-sensitive)", async () => { const { fetchImpl, calls } = fakeFetch([ new Response("not found", { status: 404 }), new Response("# Hi\n", { status: 200 }), @@ -149,19 +149,26 @@ describe("GitHubMarkdownAdapter.getMarkdown", () => { await expect(adapter.getMarkdown()).resolves.toBe("# Hi\n"); expect(calls.map((call) => call.url)).toEqual([ "https://github.com/acme/docs/raw/HEAD/README.md", - "https://github.com/acme/docs/raw/HEAD/README.markdown", + "https://github.com/acme/docs/raw/HEAD/readme.md", ]); }); - it("reports a missing README clearly", async () => { - const { fetchImpl } = fakeFetch([ - new Response("not found", { status: 404 }), - new Response("not found", { status: 404 }), - ]); + it("tries every common README spelling, then reports a missing README clearly", async () => { + const { fetchImpl, calls } = fakeFetch( + Array.from({ length: 6 }, () => new Response("not found", { status: 404 })), + ); const adapter = adapterFor("https://github.com/acme/docs", fetchImpl); const pending = adapter.getMarkdown(); await expect(pending).rejects.toThrow(MarkdownFetchError); await expect(pending).rejects.toThrow("No README.md"); + expect(calls.map((call) => call.url)).toEqual([ + "https://github.com/acme/docs/raw/HEAD/README.md", + "https://github.com/acme/docs/raw/HEAD/readme.md", + "https://github.com/acme/docs/raw/HEAD/Readme.md", + "https://github.com/acme/docs/raw/HEAD/README.markdown", + "https://github.com/acme/docs/raw/HEAD/readme.markdown", + "https://github.com/acme/docs/raw/HEAD/Readme.markdown", + ]); }); it("reports a non-404 failure with its status", async () => { diff --git a/tests/markdown-images.test.ts b/tests/markdown-images.test.ts index a06f92e..96933c6 100644 --- a/tests/markdown-images.test.ts +++ b/tests/markdown-images.test.ts @@ -122,10 +122,25 @@ describe("prepareExportMarkdown", () => { } }); - it("passes exactly at the cap", async () => { - const markdown = Array.from({ length: MAX_IMAGE_COUNT }, (_, i) => `![img](img/${i}.png)`).join("\n"); + it("counts absolute images toward the cap too, matching the server's all-src count", async () => { + const markdown = Array.from({ length: MAX_IMAGE_COUNT - 1 }, (_, i) => `![img](img/${i}.png)`) + .concat([ + "![one](https://example.com/one.png)", + "![two](https://example.com/two.png)", + ]) + .join("\n"); + const result = await prepareExportMarkdown(markdown, okResolve); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.message).toContain(`references ${MAX_IMAGE_COUNT + 1} images`); + }); + + it("passes at the cap with a mix of relative and absolute refs, leaving the absolute ones alone", async () => { + const markdown = Array.from({ length: MAX_IMAGE_COUNT - 1 }, (_, i) => `![img](img/${i}.png)`) + .concat(["![remote](https://example.com/one.png)"]) + .join("\n"); const result = await prepareExportMarkdown(markdown, okResolve); expect(result.ok).toBe(true); + if (result.ok) expect(result.markdown).toContain("![remote](https://example.com/one.png)"); }); it("stops with the image message when any reference fails", async () => {