feat(scaffold): initialize WXT + Svelte 5 project (Phase 0)

Scaffolds the project per CLAUDE.md Phase 0 and docs/01, 02, 06, 07, 08, 10.
Both entrypoints render, and `npm run verify` is green.

- WXT 0.20.27 + Svelte 5 runes + TypeScript 6 strict, srcDir: 'src'.
- Manifest carries exactly ["bookmarks", "storage"], no host permissions, no
  background worker, and never loosens the MV3 default CSP. Verified against
  the built artifact, not just the config.
- scripts/guard.mjs implements the canonical grep gate from docs/08 §3 as a
  single Node-stdlib script, so the same gate runs locally and in CI and
  cannot drift between them.
- scripts/gen-icons.mjs writes placeholder PNGs by hand (zlib + CRC32), so no
  image dependency enters the tree and the manifest loads before the designed
  icon exists.
- i18n: en/vi/ja dictionaries with `satisfies Dict` (never `as const` — see
  docs/07 §2), plus a pure resolve-locale module so locale mapping is testable
  without the runes runtime.
- Tests run under jsdom, including an environment canary asserting the
  implied-end-tag DL nesting and `:scope >` behaviour the Netscape parser will
  depend on, and that a parsed hostile document stays inert.
- legal/ drafts, SECURITY.md, FUNDING.yml and .nvmrc land now because the
  About tab and first-run gate link to them from the very first screens.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5 committed 2026-07-26 06:13:53 +07:00
1 parent 9a3570f65e
commit 57b2cb43fa
41 files changed
+9170

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
github: poli0981
ko_fi: skullmute
buy_me_a_coffee: skullmute
patreon: skullmute
custom:
- paypal.me/DungDang212
+38
View File
@@ -0,0 +1,38 @@
# Dependencies
node_modules/
# WXT build output + generated types
.output/
.wxt/
stats.html
stats-*.json
# Test / coverage
coverage/
*.tsbuildinfo
# Editors
.idea/
.vs/
.vscode/*
!.vscode/extensions.json
*.swp
# OS
.DS_Store
._*
Thumbs.db
Desktop.ini
# Logs
*.log
npm-debug.log*
# Local env
.env
.env.local
.env.*.local
# Generated fixtures that are too big to commit (tests/fixtures/generate-huge.ts
# writes here on demand — docs/11 §2)
tests/fixtures/generated/
+1
View File
@@ -0,0 +1 @@
24
+40
View File
@@ -0,0 +1,40 @@
# Security Policy
## Reporting a vulnerability
Report privately via **GitHub Security Advisories**:
<https://github.com/poli0981/bookmarkmagic/security/advisories/new>
Please do not open a public issue for a security problem.
Include, where possible: the affected version, a description of the impact, and
a minimal reproduction. If a bookmark file triggers the issue, attach a
**sanitized** sample — replace real URLs and titles with placeholders.
## Response targets
| Stage | Target |
|---|---|
| Acknowledgement | 72 hours |
| Fix or mitigation for High/Critical | 14 days |
This is a hobby project with no bounty programme. Credit is given in the
release notes unless you ask otherwise.
## Scope
In scope: the extension's parsing, serialization, storage and UI code in this
repository, and the release/build pipeline.
Out of scope: vulnerabilities in Chrome itself, and issues that require the
user to install a modified build.
## Design notes relevant to reporters
The extension holds exactly two permissions (`bookmarks`, `storage`), makes no
network requests at runtime, ships no remote code, and never loosens the MV3
default Content Security Policy. Imported files are parsed with
`DOMParser('text/html')` into an inert document; nodes from that document are
never adopted into the live DOM, and all file-derived strings reach the UI via
text interpolation only. See `docs/09_SECURITY_PRIVACY.md` for the full threat
model (T1–T8).
+56
View File
@@ -0,0 +1,56 @@
{
"$schema": "https://biomejs.dev/schemas/2.5.5/schema.json",
"vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true },
"files": {
"ignoreUnknown": true,
"includes": ["**", "!**/*.svelte", "!**/*.css", "!.output", "!.wxt"]
},
"formatter": {
"enabled": true,
"indentStyle": "space",
"indentWidth": 2,
"lineWidth": 100
},
"javascript": {
"formatter": {
"quoteStyle": "single",
"semicolons": "always",
"trailingCommas": "all",
"arrowParentheses": "always"
}
},
"linter": {
"enabled": true,
"rules": {
"preset": "recommended",
"correctness": {
"noUnusedImports": "error",
"noUnusedVariables": "error"
},
"suspicious": {
"noExplicitAny": "error",
"noConsole": { "level": "error", "options": { "allow": ["warn", "error"] } }
},
"style": { "noDefaultExport": "error" }
}
},
"assist": {
"enabled": true,
"actions": { "source": { "organizeImports": "on" } }
},
"overrides": [
{
"includes": ["src/entrypoints/**", "wxt.config.ts", "vitest.config.ts", "scripts/**"],
"linter": {
"rules": {
"style": { "noDefaultExport": "off" },
"suspicious": { "noConsole": "off" }
}
}
},
{
"includes": ["src/lib/i18n/locales/**"],
"linter": { "rules": { "style": { "noDefaultExport": "off" } } }
}
]
}
+11
View File
@@ -0,0 +1,11 @@
{
"$schema": "https://unpkg.com/knip@6/schema.json",
"entry": [
"src/entrypoints/**/main.ts",
"src/entrypoints/**/index.html",
"tests/**/*.test.ts",
"scripts/*.mjs"
],
"project": ["src/**/*.{ts,svelte}", "tests/**/*.ts"],
"ignoreDependencies": []
}
+15
View File
@@ -0,0 +1,15 @@
# Disclaimer — BookmarkMagic
- Provided "AS IS", without warranty of any kind (see LICENSE §15–16).
- Bookmark operations modify your browser's bookmark data. The "Replace
everything" mode DELETES all existing bookmarks after saving an automatic
safety backup. You are responsible for keeping backups of data you care
about.
- Imported bookmarks are created with the current date and time. Chrome's
extension API does not allow an extension to set a bookmark's original
creation date, so original dates are preserved in your exported *files* but
not when writing back into the browser.
- Import files come from outside this Extension; verify you trust their source.
Bookmarked URLs are stored as-is and are not vetted by the Extension.
- This project is not affiliated with or endorsed by Google, Chrome, or any
browser vendor. Browser names are trademarks of their respective owners.
+15
View File
@@ -0,0 +1,15 @@
# End User License Agreement — BookmarkMagic
1. **License.** The software is free software licensed under the GNU General
Public License v3.0 or later (see LICENSE). You may use, study, share, and
modify it under those terms. This EULA adds no restrictions beyond the GPL;
if anything here conflicts with the GPL, the GPL prevails.
2. **No warranty; limitation of liability.** As stated in GPL-3.0 §15 and §16,
the software is provided without warranty, and authors are not liable for
damages, including loss of bookmark data.
3. **Acceptable use.** You agree not to use the software to violate applicable
law or third-party rights.
4. **Your data.** The software processes bookmark data locally on your device
only (see PRIVACY.md).
5. **Updates.** Updates are delivered via the Chrome Web Store and may change
functionality. Material legal changes trigger re-acceptance in-app.
+45
View File
@@ -0,0 +1,45 @@
# Privacy Policy — BookmarkMagic
Last updated: 2026-07-25
BookmarkMagic ("the Extension") is designed to work entirely on your device.
## What we collect
Nothing. The Extension has no servers, performs no network requests, and
contains no analytics, telemetry, or crash reporting.
## What the Extension accesses, and why
- **Bookmarks** (permission: `bookmarks`): read to display and export your
bookmark tree; written when you import or edit. This data never leaves your
device.
- **Local settings** (permission: `storage`): your language, theme,
preferences, and the date you accepted these terms are stored locally via
`chrome.storage.local`. They are not transmitted anywhere and are removed by
Chrome when you uninstall the Extension. The Extension does not use
`chrome.storage.sync`, so even your settings stay off any vendor cloud.
The Extension requests no other permissions. It has no host permissions, no
content scripts, and no background service worker.
## Files you import or export
Files are read and generated locally in your browser. They are never uploaded.
Exported files are saved through your browser's normal download mechanism to a
location you control.
## Third parties
No data is shared with anyone, because no data is collected. The Extension
ships with zero runtime dependencies.
## Changes
Material changes will be published here and re-acceptance will be requested
inside the Extension.
## Contact
⚠️ contact email — or open an issue at
<https://github.com/poli0981/bookmarkmagic/issues>
+15
View File
@@ -0,0 +1,15 @@
# Third-Party Notices — BookmarkMagic
**Runtime dependencies: None.**
The shipped extension bundles no third-party code. Parsing, serializing and
downloading use platform APIs only (`DOMParser`, `Blob`, `URL`,
`crypto.randomUUID`).
Build-time tooling (WXT, Vite, Svelte, TypeScript, Biome, Knip, Vitest) is not
distributed with the extension and is not listed here. All of it is
MIT/Apache-2.0/ISC licensed and compatible with GPL-3.0-or-later.
If a runtime dependency is ever added — see `docs/01_TECH_STACK.md §4` for the
gated list — its name and full license text must be added to this file in the
same pull request, and the About tab must render it (`docs/14 §5`).
+8161
View File
File diff suppressed because it is too large. Load diff
+49
View File
@@ -0,0 +1,49 @@
{
"name": "bookmarkmagic",
"private": true,
"version": "0.1.0",
"type": "module",
"description": "Import, export & edit bookmarks between browsers — offline, no account, no cloud.",
"license": "GPL-3.0-or-later",
"author": "skullmute (poli0981)",
"homepage": "https://github.com/poli0981/bookmarkmagic",
"repository": {
"type": "git",
"url": "git+https://github.com/poli0981/bookmarkmagic.git"
},
"bugs": {
"url": "https://github.com/poli0981/bookmarkmagic/issues"
},
"engines": {
"node": ">=24"
},
"scripts": {
"postinstall": "wxt prepare",
"dev": "wxt",
"dev:firefox": "wxt -b firefox",
"build": "wxt build",
"zip": "wxt zip",
"check": "svelte-check --tsconfig ./tsconfig.json && tsc --noEmit",
"lint": "biome check .",
"lint:fix": "biome check --write .",
"knip": "knip",
"guard": "node scripts/guard.mjs",
"icons": "node scripts/gen-icons.mjs",
"test": "vitest run",
"test:watch": "vitest",
"coverage": "vitest run --coverage",
"verify": "npm run lint && npm run check && npm run knip && npm run guard && npm run test"
},
"devDependencies": {
"@biomejs/biome": "2.5.5",
"@vitest/coverage-v8": "^4.1.10",
"@wxt-dev/module-svelte": "^2.0.5",
"jsdom": "^29.1.1",
"knip": "^6.29.0",
"svelte": "^5.56.8",
"svelte-check": "^4.7.3",
"typescript": "~6.0.3",
"vitest": "^4.1.10",
"wxt": "^0.20.27"
}
}
+105
View File
@@ -0,0 +1,105 @@
/**
* Generate placeholder extension icons — a rounded violet square with a white
* bookmark ribbon — at the four sizes Chrome needs. Zero dependencies: PNG is
* written by hand (zlib deflate + a CRC32 table), so no image library enters
* the tree.
*
* These are functional placeholders so the manifest loads from Phase 0.
* Replace with the designed icon before a store release (docs/00 §10 item 3,
* docs/13 §2). Run: `npm run icons`.
*/
import { mkdirSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { deflateSync } from 'node:zlib';
const ACCENT = [0x6d, 0x4a, 0xff, 255]; // --accent, docs/06 §1
const WHITE = [255, 255, 255, 255];
const TRANSPARENT = [0, 0, 0, 0];
const CRC_TABLE = (() => {
const table = new Uint32Array(256);
for (let n = 0; n < 256; n++) {
let c = n;
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
table[n] = c >>> 0;
}
return table;
})();
function crc32(buf) {
let c = 0xffffffff;
for (const byte of buf) c = CRC_TABLE[(c ^ byte) & 0xff] ^ (c >>> 8);
return (c ^ 0xffffffff) >>> 0;
}
function chunk(type, data) {
const body = Buffer.concat([Buffer.from(type, 'ascii'), data]);
const len = Buffer.alloc(4);
len.writeUInt32BE(data.length);
const crc = Buffer.alloc(4);
crc.writeUInt32BE(crc32(body));
return Buffer.concat([len, body, crc]);
}
function insideRounded(x, y, size, radius) {
const px = x + 0.5;
const py = y + 0.5;
const dx = Math.max(radius - px, px - (size - radius), 0);
const dy = Math.max(radius - py, py - (size - radius), 0);
return dx * dx + dy * dy <= radius * radius;
}
/** Bookmark ribbon: a tall rectangle with a triangular notch cut from the bottom. */
function insideBookmark(x, y, size) {
const u = (x + 0.5) / size;
const v = (y + 0.5) / size;
if (u < 0.32 || u > 0.68 || v < 0.22 || v > 0.78) return false;
// Notch: from the bottom edge, cut a V rising to the ribbon's middle.
const notchDepth = 0.22;
if (v > 0.78 - notchDepth) {
const fromBottom = (0.78 - v) / notchDepth; // 0 at bottom edge, 1 at notch apex
if (Math.abs(u - 0.5) < (1 - fromBottom) * 0.18) return false;
}
return true;
}
function colorAt(x, y, size) {
if (!insideRounded(x, y, size, size * 0.2)) return TRANSPARENT;
if (insideBookmark(x, y, size)) return WHITE;
return ACCENT;
}
function makePng(size) {
const stride = size * 4;
const raw = Buffer.alloc((stride + 1) * size);
for (let y = 0; y < size; y++) {
let off = y * (stride + 1) + 1; // skip filter byte (0 = None)
for (let x = 0; x < size; x++) {
const [r, g, b, a] = colorAt(x, y, size);
raw[off++] = r;
raw[off++] = g;
raw[off++] = b;
raw[off++] = a;
}
}
const ihdr = Buffer.alloc(13);
ihdr.writeUInt32BE(size, 0);
ihdr.writeUInt32BE(size, 4);
ihdr[8] = 8; // bit depth
ihdr[9] = 6; // colour type RGBA
const sig = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
return Buffer.concat([
sig,
chunk('IHDR', ihdr),
chunk('IDAT', deflateSync(raw, { level: 9 })),
chunk('IEND', Buffer.alloc(0)),
]);
}
const outDir = join(dirname(fileURLToPath(import.meta.url)), '..', 'src', 'public', 'icon');
mkdirSync(outDir, { recursive: true });
for (const size of [16, 32, 48, 128]) {
writeFileSync(join(outDir, `${size}.png`), makePng(size));
console.warn(`wrote src/public/icon/${size}.png`);
}
+84
View File
@@ -0,0 +1,84 @@
/**
* The canonical grep gate — docs/08_MV3_COMPLIANCE.md §3.
*
* This file is the single implementation of that pattern. It runs both locally
* (`npm run verify`) and in CI (`npm run guard`), so the gate cannot drift
* between the two. Zero dependencies, Node stdlib only.
*
* Why a grep and not a lint rule: MV3's default CSP blocks remote code, but it
* has no connect-src at all and does not restrict network egress. And no Biome
* rule sees Svelte's {@html} — noDangerouslySetInnerHtml is a React rule. This
* script plus review is the entire enforcement of the zero-network and
* no-raw-HTML promises.
*/
import { readFileSync } from 'node:fs';
import { readdir } from 'node:fs/promises';
import { extname, join, relative } from 'node:path';
const ROOT = new URL('..', import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1');
const SCAN_DIRS = ['src'];
const SCAN_EXTS = new Set(['.ts', '.js', '.mjs', '.svelte']);
const SKIP_DIRS = new Set(['node_modules', '.output', '.wxt', '.git']);
/** Each entry: [human-readable name, pattern]. Keep in sync with docs/08 §3. */
const BANNED = [
['network: fetch', /\bfetch\s*\(/],
['network: XMLHttpRequest', /\bXMLHttpRequest\b/],
['network: WebSocket', /\bWebSocket\b/],
['network: EventSource', /\bEventSource\b/],
['network: sendBeacon', /\bsendBeacon\b/],
['remote code: eval', /\beval\s*\(/],
['remote code: new Function', /\bnew\s+Function\s*\(/],
['remote code: dynamic import', /(^|[^.\w])import\s*\(/],
['raw HTML: {@html}', /\{@html\b/],
['raw HTML: innerHTML assignment', /\b(?:inner|outer)HTML\s*=/],
['raw HTML: insertAdjacentHTML', /\binsertAdjacentHTML\b/],
];
/** Test files may reference banned identifiers when asserting they are absent. */
const isExempt = (path) => /\.(test|spec)\.ts$/.test(path);
async function* walk(dir) {
let entries;
try {
entries = await readdir(dir, { withFileTypes: true });
} catch {
return; // directory not created yet — nothing to scan
}
for (const entry of entries) {
const full = join(dir, entry.name);
if (entry.isDirectory()) {
if (!SKIP_DIRS.has(entry.name)) yield* walk(full);
} else if (SCAN_EXTS.has(extname(entry.name))) {
yield full;
}
}
}
const violations = [];
for (const dir of SCAN_DIRS) {
for await (const file of walk(join(ROOT, dir))) {
const rel = relative(ROOT, file).replace(/\\/g, '/');
if (isExempt(rel)) continue;
const lines = readFileSync(file, 'utf8').split(/\r?\n/);
lines.forEach((line, i) => {
for (const [name, pattern] of BANNED) {
if (pattern.test(line)) violations.push({ rel, line: i + 1, name, text: line.trim() });
}
});
}
}
if (violations.length > 0) {
for (const v of violations) {
console.error(`::error file=${v.rel},line=${v.line}::[${v.name}] ${v.text}`);
console.error(` ${v.rel}:${v.line} ${v.name}\n ${v.text}`);
}
console.error(
`\nguard: ${violations.length} banned pattern(s) found. See docs/08_MV3_COMPLIANCE.md §3.`,
);
process.exit(1);
}
console.warn(`guard: clean — no banned patterns in ${SCAN_DIRS.join(', ')}`);
+27
View File
@@ -0,0 +1,27 @@
<script lang="ts">
import { t } from '@/lib/i18n/index.svelte';
</script>
<main>
<h1>{t('common.appName')}</h1>
<p>hello — manager</p>
</main>
<style>
main {
max-width: 960px;
margin: 0 auto;
padding: var(--sp-6) var(--sp-4);
}
h1 {
margin: 0 0 var(--sp-2);
font-size: var(--fs-4);
color: var(--accent);
}
p {
margin: 0;
color: var(--fg-muted);
}
</style>
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>BookmarkMagic</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="./main.ts"></script>
</body>
</html>
+16
View File
@@ -0,0 +1,16 @@
import { mount } from 'svelte';
import { browser } from 'wxt/browser';
import { setLocale } from '@/lib/i18n/index.svelte';
import { resolveLocale } from '@/lib/i18n/resolve-locale';
import '@/styles/base.css';
import App from './App.svelte';
// Phase 0: browser UI language only. Phase 4 hydrates from the persisted
// Settings value first, falling back to this (docs/07 §2).
setLocale(resolveLocale(browser.i18n.getUILanguage()));
// SAFETY: the element is declared in this entrypoint's own index.html, so it
// always exists by the time this module runs.
const target = document.getElementById('app') as HTMLElement;
export default mount(App, { target });
+27
View File
@@ -0,0 +1,27 @@
<script lang="ts">
import { t } from '@/lib/i18n/index.svelte';
</script>
<main>
<h1>{t('common.appName')}</h1>
<p>hello — popup</p>
</main>
<style>
main {
width: 320px;
padding: var(--sp-4);
}
h1 {
margin: 0 0 var(--sp-2);
font-size: var(--fs-3);
color: var(--accent);
}
p {
margin: 0;
color: var(--fg-muted);
font-size: var(--fs-1);
}
</style>
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>BookmarkMagic</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="./main.ts"></script>
</body>
</html>
+16
View File
@@ -0,0 +1,16 @@
import { mount } from 'svelte';
import { browser } from 'wxt/browser';
import { setLocale } from '@/lib/i18n/index.svelte';
import { resolveLocale } from '@/lib/i18n/resolve-locale';
import '@/styles/base.css';
import App from './App.svelte';
// Phase 0: browser UI language only. Phase 4 hydrates from the persisted
// Settings value first, falling back to this (docs/07 §2).
setLocale(resolveLocale(browser.i18n.getUILanguage()));
// SAFETY: the element is declared in this entrypoint's own index.html, so it
// always exists by the time this module runs.
const target = document.getElementById('app') as HTMLElement;
export default mount(App, { target });
+24
View File
@@ -0,0 +1,24 @@
/**
* Hard caps and versioned constants.
*
* Purpose: one place for every number that bounds untrusted input, so the
* threat model (docs/09 §2 T2) and the parser cannot drift apart.
* Inputs: none — pure constants.
* Guarantees: values here are the ones docs/09 promises to reviewers.
*/
/** Pre-parse file size cap. Larger files fail with `FILE_TOO_LARGE`. */
export const MAX_FILE_BYTES = 25 * 1024 * 1024;
/** Node count cap across a parsed tree. Exceeding it throws `TOO_MANY_NODES`. */
export const MAX_NODES = 100_000;
/** Nesting depth cap. Exceeding it throws `TOO_DEEP` (docs/05 §1). */
export const MAX_DEPTH = 200;
/**
* Legal document version. Bump ONLY for material changes to the documents in
* `legal/`; the first-run gate reappears for every user when this increases
* (docs/14 §2).
*/
export const LEGAL_VERSION = 1;
+42
View File
@@ -0,0 +1,42 @@
import en from './locales/en';
import ja from './locales/ja';
import vi from './locales/vi';
import type { Locale } from './resolve-locale';
/**
* Runtime UI i18n (docs/07 §2).
*
* chrome.i18n always follows the browser UI language and cannot be switched at
* runtime, so every in-app string resolves through this store instead. The
* dictionaries are static imports, not fetched — `fetch` is banned repo-wide
* (docs/08 §3), and bundling three small dicts costs nothing at our size.
*/
const dicts = { en, vi, ja };
let locale = $state<Locale>('en');
export function setLocale(next: Locale): void {
locale = next;
}
/**
* Resolve a dotted key path, falling back to English, then to the key itself.
* Interpolation is `{token}` replacement only — never concatenate sentence
* fragments, or VI/JA word order breaks (docs/07 §2).
*/
export function t(path: string, params?: Record<string, string | number>): string {
const raw = lookup(dicts[locale], path) ?? lookup(dicts.en, path) ?? path;
if (params === undefined) return raw;
return raw.replace(/\{(\w+)\}/g, (match, token: string) =>
Object.hasOwn(params, token) ? String(params[token]) : match,
);
}
function lookup(dict: unknown, path: string): string | undefined {
let node: unknown = dict;
for (const key of path.split('.')) {
if (typeof node !== 'object' || node === null) return undefined;
node = (node as Record<string, unknown>)[key];
}
return typeof node === 'string' ? node : undefined;
}
+26
View File
@@ -0,0 +1,26 @@
/**
* English dictionary — the schema source of truth (docs/07 §2).
*
* vi.ts and ja.ts mirror this exact shape via `satisfies Dict`, so a missing
* key fails `tsc`. That is the whole completeness check; no i18n framework.
*
* NEVER write `as const` here. It would make `Dict` a tree of string *literal*
* types, so `satisfies Dict` would demand vi.common.import === 'Import' and
* every correct translation would become a compile error.
*/
const dict = {
common: {
appName: 'BookmarkMagic',
import: 'Import',
export: 'Export',
edit: 'Edit',
settings: 'Settings',
about: 'About',
cancel: 'Cancel',
},
};
export default dict;
/** Widened shape (string, not the literal). vi/ja are typed against this. */
export type Dict = typeof dict;
+14
View File
@@ -0,0 +1,14 @@
import type { Dict } from './en';
/** Japanese — です/ます form, katakana loanwords (docs/07 §4). */
export default {
common: {
appName: 'BookmarkMagic',
import: 'インポート',
export: 'エクスポート',
edit: '編集',
settings: '設定',
about: '概要',
cancel: 'キャンセル',
},
} satisfies Dict;
+14
View File
@@ -0,0 +1,14 @@
import type { Dict } from './en';
/** Vietnamese — neutral-friendly register, "bạn"; folder = "thư mục" (docs/07 §4). */
export default {
common: {
appName: 'BookmarkMagic',
import: 'Nhập',
export: 'Xuất',
edit: 'Chỉnh sửa',
settings: 'Cài đặt',
about: 'Giới thiệu',
cancel: 'Hủy',
},
} satisfies Dict;
+19
View File
@@ -0,0 +1,19 @@
/**
* Locale resolution — pure, so it is unit-testable without the runes runtime.
*
* Inputs: a browser UI language tag (`chrome.i18n.getUILanguage()`).
* Guarantees: always returns a supported locale; never throws.
*/
export type Locale = 'en' | 'vi' | 'ja';
/**
* Map a browser UI language tag onto a supported locale (docs/07 §2).
* Only the primary subtag matters: `vi`, `vi-VN` → vi; `ja`, `ja-JP` → ja;
* everything else falls back to English, the default locale.
*/
export function resolveLocale(uiLanguage: string): Locale {
const tag = uiLanguage.toLowerCase();
if (tag === 'vi' || tag.startsWith('vi-')) return 'vi';
if (tag === 'ja' || tag.startsWith('ja-')) return 'ja';
return 'en';
}
+6
View File
@@ -0,0 +1,6 @@
{
"appName": { "message": "BookmarkMagic" },
"appDesc": {
"message": "Import, export & edit bookmarks between browsers — offline, no account, no cloud."
}
}
+6
View File
@@ -0,0 +1,6 @@
{
"appName": { "message": "BookmarkMagic" },
"appDesc": {
"message": "ブラウザ間でブックマークをインポート・エクスポート・編集。オフライン、アカウント不要、クラウド不要。"
}
}
+6
View File
@@ -0,0 +1,6 @@
{
"appName": { "message": "BookmarkMagic" },
"appDesc": {
"message": "Nhập, xuất & chỉnh sửa bookmark giữa các trình duyệt — offline, không tài khoản, không cloud."
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 497 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 106 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 158 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 201 B

+31
View File
@@ -0,0 +1,31 @@
@import './tokens.css';
*,
*::before,
*::after {
box-sizing: border-box;
}
html,
body {
margin: 0;
padding: 0;
}
body {
background: var(--bg);
color: var(--fg);
font-family: var(--font);
font-size: var(--fs-2);
line-height: 1.5;
}
/* Focus rings are always visible — docs/06 §1. */
:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
a {
color: var(--accent);
}
+58
View File
@@ -0,0 +1,58 @@
/* Design tokens — docs/06 §1. Theme via data-theme on <html>; default follows
prefers-color-scheme, manual override persisted in Settings. */
:root {
--bg: #ffffff;
--bg-raised: #f6f7f9;
--border: #e2e5ea;
--fg: #1b1e24;
--fg-muted: #5b6472;
--accent: #6d4aff; /* violet — "magic" identity */
--accent-fg: #ffffff;
--danger: #d8384a;
--success: #1f9d55;
--warn: #b7791f;
--radius: 10px;
--radius-sm: 6px;
--font: system-ui, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
--fs-0: 12px;
--fs-1: 13.5px;
--fs-2: 15px;
--fs-3: 18px;
--fs-4: 24px;
--sp-1: 4px;
--sp-2: 8px;
--sp-3: 12px;
--sp-4: 16px;
--sp-5: 24px;
--sp-6: 32px;
}
[data-theme='dark'] {
--bg: #16181d;
--bg-raised: #1e2128;
--border: #2b3039;
--fg: #e8eaee;
--fg-muted: #9aa3b0;
--accent: #8b6dff;
--danger: #ff6b7d;
--success: #3ecf8e;
--warn: #e2b93b;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme='light']) {
--bg: #16181d;
--bg-raised: #1e2128;
--border: #2b3039;
--fg: #e8eaee;
--fg-muted: #9aa3b0;
--accent: #8b6dff;
--danger: #ff6b7d;
--success: #3ecf8e;
--warn: #e2b93b;
}
}
+25
View File
@@ -0,0 +1,25 @@
import { describe, expect, it } from 'vitest';
import { LEGAL_VERSION, MAX_DEPTH, MAX_FILE_BYTES, MAX_NODES } from '@/lib/core/limits';
/**
* These constants are public promises, not implementation details: docs/09 §2
* T2 cites the exact caps to reviewers, and docs/14 §2 ties LEGAL_VERSION to
* re-consent. Changing one without updating the docs should break the build.
*/
describe('limits', () => {
it('caps files at the 25 MB documented in docs/09 T2', () => {
expect(MAX_FILE_BYTES).toBe(25 * 1024 * 1024);
});
it('caps node count at the 100 000 documented in docs/09 T2', () => {
expect(MAX_NODES).toBe(100_000);
});
it('caps nesting depth at the 200 documented in docs/09 T2', () => {
expect(MAX_DEPTH).toBe(200);
});
it('starts LEGAL_VERSION at 1 (docs/14 §2)', () => {
expect(LEGAL_VERSION).toBe(1);
});
});
+45
View File
@@ -0,0 +1,45 @@
import { describe, expect, it } from 'vitest';
/**
* Environment canary — docs/02 §3, docs/11 §1.
*
* The whole Netscape parser walk rests on two DOM behaviours: HTML5 "generate
* implied end tags", which nests a folder's child <DL> INSIDE the unclosed
* <DT> before it, and `:scope >` selectors evaluated from an element root.
* jsdom (parse5) implements both; happy-dom does not.
*
* If someone swaps the test environment, this fails loudly here instead of
* every folder silently parsing as childless in the real suite.
*/
const CHROME_SHAPE = `<!DOCTYPE NETSCAPE-Bookmark-file-1>
<DL><p>
<DT><H3 PERSONAL_TOOLBAR_FOLDER="true">Bookmarks bar</H3>
<DL><p>
<DT><A HREF="https://example.com/">Example</A>
</DL><p>
</DL><p>`;
describe('DOM environment', () => {
const doc = new DOMParser().parseFromString(CHROME_SHAPE, 'text/html');
it('nests a folder child <DL> inside the preceding unclosed <DT>', () => {
const dt = doc.querySelector('dl > dt');
expect(dt).not.toBeNull();
expect(dt?.querySelector(':scope > dl')).not.toBeNull();
});
it('supports :scope > selectors from an element root', () => {
const dt = doc.querySelector('dl > dt');
expect(dt?.querySelector(':scope > h3')?.textContent).toBe('Bookmarks bar');
});
it('produces an inert document — scripts never execute (docs/09 T1)', () => {
const hostile = new DOMParser().parseFromString(
'<!DOCTYPE NETSCAPE-Bookmark-file-1><DL><p><DT><A HREF="https://x.test/" ' +
'onerror="globalThis.__pwned = true">t</A><script>globalThis.__pwned = true;</script></DL>',
'text/html',
);
expect(hostile.querySelector('a')?.textContent).toBe('t');
expect((globalThis as Record<string, unknown>).__pwned).toBeUndefined();
});
});
+27
View File
@@ -0,0 +1,27 @@
import { describe, expect, it } from 'vitest';
import { resolveLocale } from '@/lib/i18n/resolve-locale';
describe('resolveLocale', () => {
it('maps Vietnamese tags to vi', () => {
expect(resolveLocale('vi')).toBe('vi');
expect(resolveLocale('vi-VN')).toBe('vi');
expect(resolveLocale('VI-vn')).toBe('vi');
});
it('maps Japanese tags to ja', () => {
expect(resolveLocale('ja')).toBe('ja');
expect(resolveLocale('ja-JP')).toBe('ja');
});
it('falls back to en for anything else', () => {
expect(resolveLocale('en-US')).toBe('en');
expect(resolveLocale('de')).toBe('en');
expect(resolveLocale('')).toBe('en');
});
it('does not match on a shared prefix that is a different language', () => {
// 'vic' / 'jav' (Javanese) start with vi/ja but are not our locales.
expect(resolveLocale('jav')).toBe('en');
expect(resolveLocale('vic')).toBe('en');
});
});
+14
View File
@@ -0,0 +1,14 @@
{
"extends": "./.wxt/tsconfig.json",
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"exactOptionalPropertyTypes": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"verbatimModuleSyntax": true,
"erasableSyntaxOnly": true
}
}
+22
View File
@@ -0,0 +1,22 @@
import { defineConfig } from 'vitest/config';
import { WxtVitest } from 'wxt/testing';
/**
* jsdom, not happy-dom (docs/02 §3). The Netscape parser walk depends on
* HTML5 "generate implied end tags" — the child <DL> nesting inside an
* unclosed <DT> — and on `:scope > h3` from an element root. jsdom uses
* parse5 and is spec-compliant on both; happy-dom is not, so a suite run
* there would validate a DOM the browser never produces.
*/
export default defineConfig({
plugins: [WxtVitest()],
test: {
environment: 'jsdom',
include: ['tests/unit/**/*.test.ts'],
coverage: {
provider: 'v8',
include: ['src/lib/core/**'],
thresholds: { lines: 90, functions: 90, branches: 85 },
},
},
});
+40
View File
@@ -0,0 +1,40 @@
import { defineConfig } from 'wxt';
/**
* WXT configuration.
*
* Hard constraints encoded here (docs/08 §1, CLAUDE.md hard rules):
* - Permissions are exactly ["bookmarks", "storage"] — forever, for v1.
* No host_permissions, no content_scripts, no background service worker.
* - No remote code: everything ships in the package, and the MV3 default CSP
* is never loosened.
* - srcDir: 'src' so entrypoints/, public/ and lib/ all live under src/ and
* the `@` alias resolves there (docs/02 §2).
*/
export default defineConfig({
srcDir: 'src',
// publicDir is resolved against the project ROOT, not srcDir — WXT's default
// is `<root>/public`, so this line is required to keep _locales/ and icon/
// under src/. Without it they are silently omitted from the build and Chrome
// refuses to load the extension (missing __MSG_appName__ and icons).
publicDir: 'src/public',
modules: ['@wxt-dev/module-svelte'],
manifest: {
name: '__MSG_appName__',
description: '__MSG_appDesc__',
default_locale: 'en',
minimum_chrome_version: '120',
permissions: ['bookmarks', 'storage'],
// Deep-link lands on #settings only when no Manager tab is open — with
// open_in_tab Chrome matches the singleton tab ignoring the fragment,
// so route.svelte.ts must react to hashchange (docs/02 §5).
options_ui: { page: 'manager.html#settings', open_in_tab: true },
icons: {
16: '/icon/16.png',
32: '/icon/32.png',
48: '/icon/48.png',
128: '/icon/128.png',
},
homepage_url: 'https://github.com/poli0981/bookmarkmagic',
},
});