Compare commits

...
23 Commits
Author SHA1 Message Date
poli0981andClaude Opus 5 9c6ecaaa75 fix(deps): take npm audit to zero with overrides for six transitive dev CVEs
Six Dependabot alerts (1 critical, 3 high, 1 medium, 1 low) plus six further
`npm audit` highs, all in transitive DEV dependencies whose parents pin them to
vulnerable ranges. That pinning is why Dependabot's own per-package PRs could
not fix any of them — every one of those runs failed. `overrides` is the npm
mechanism for precisely this case.

  shell-quote     1.7.3   -> ^1.9.0    wxt > web-ext-run > fx-runner
  adm-zip         0.5.18  -> ^0.6.0    wxt > web-ext-run > firefox-profile
  tmp             0.2.5   -> ^0.2.6    wxt > web-ext-run
  uuid            8.3.2   -> ^11.1.1   wxt > web-ext-run > node-notifier
  esbuild         0.27.7  -> ^0.28.1   vite, wxt, unplugin
  brace-expansion 1.1.16  -> ^5.0.8    web-ext-run > multimatch > minimatch

The last one is the whole second cluster: `npm audit` reported six highs that
were one brace-expansion DoS propagating through minimatch -> multimatch ->
web-ext-run -> wxt, with fixAvailable:false because multimatch pins minimatch.

`npm audit` now reports 0. It already reported 0 for `--omit=dev`, and still
does: the shipped extension has no runtime dependencies, so none of this was
ever in the artifact.

Correcting something I wrote in the dependabot.yml comment and repeated in a
PR: I said these advisories had "no reachable patched version". That was wrong
— every one of them had a patched version. What they lacked was a path
Dependabot could take on its own.

Re-verified after the overrides: lint, check, knip, coverage, guard, build,
check:manifest and zip all pass, and the built manifest is still exactly
["bookmarks","storage"] at version 1.0.0.

⚠️ Four of the six live only under web-ext-run, the Firefox dev runner behind
`npm run dev:firefox` — a v1.0 non-goal per docs/00 §7, and the one script no
gate exercises. docs/09 §3.1 records that, plus when each override can be
dropped.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 17:36:30 +07:00
dependabot[bot] 8d8c3f3d9f ci(deps): Bump actions/setup-node from 6 to 7 in the actions group
Bumps the actions group with 1 update: [actions/setup-node](https://github.com/actions/setup-node).


Updates `actions/setup-node` from 6 to 7
- [Release notes](https://github.com/actions/setup-node/releases)
- [Commits](https://github.com/actions/setup-node/compare/v6...v7)

---
updated-dependencies:
- dependency-name: actions/setup-node
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-26 17:27:47 +07:00
poli0981andClaude Opus 5 626e4fab3d feat: release prep for 1.0.0 — Dependabot, version bump, and two screenshot fixes
Two defects visible in the owner's screenshots of the running extension, both
invisible to every gate the repo has:

- The footer rendered "v0.1.0 ·GPL-3.0". Svelte trims trailing whitespace at an
  {#if} boundary, so the space after the separator inside the block was
  dropped. Separators are `{' · '}` expressions now, which are never trimmed;
  verified in the built bundle.
- The compact theme toggle's dark option used U+263E (☾), a thin crescent that
  reads as a capital "C" at ~13px — clearly visible in all four screenshots.
  Now ☀️/🌙, which also matches the popup's existing ⬆/⬇/🗂 vocabulary. The
  accessible name came from aria-label either way, so this is purely visual.

Adds .github/dependabot.yml (docs/12 §5): weekly npm and github-actions, dev
minor+patch grouped into one PR so CI runs once, Conventional Commit prefixes,
and TypeScript majors held because svelte-check needs the TS 6 programmatic API
until 7.1. The comment records what the file cannot do — security updates run
from the repo's alerts regardless, and the ones failing today are transitive
DEV dependencies with no reachable patch, which is why `npm audit --omit=dev`
is still 0.

Version bumped to 1.0.0 with the CHANGELOG section dated, and the icon set
closed in docs/00 §10: the owner adopted the gen-icons.mjs output as final, so
the generator is the source of truth rather than a placeholder. README's
screenshot placeholder is replaced with the four real captures.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 17:20:17 +07:00
poli0981andClaude Opus 5 2c8fba9a74 fix(ci): grant contents: write so the reusable build job can start at all
The first real run of ci.yml was a startup_failure — no jobs, no log, just
"this run likely failed because of a workflow file issue".

reusable-chrome-extension.yml declares two mutually exclusive jobs: `build`
(contents: read, `if: !inputs.release`) and `release` (contents: write,
`if: inputs.release`). GitHub validates the caller's grant against EVERY job
the reusable declares, before evaluating any `if:` — so passing `release: false`
does not exempt the caller from the release job's requirement, and the
least-privilege `contents: read` in docs/12 §2.1's sample rejects the whole run.

CodeQL succeeded on the same push because its caller happened to grant a
superset of what its single job needs, which is what isolated the cause.

docs/12 §2.1 updated with the same grant and a warning, since its sample is
what this stub was written from.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 14:57:15 +07:00
poli0981andClaude Opus 5 674ac341e5 fix: close the eight findings the Phase 5 review confirmed
Five lenses filed 20; 8 survived verification.

**release.yml would have failed on the first tag.** The `announce` job called
the ops reusable with no `with:` block, but that reusable resolves
TAG="${INPUT_TAG:-$EVENT_TAG}" where EVENT_TAG is github.event.release.tag_name
-- empty, because this workflow is triggered by `on: push: tags`, not
`on: release`. The job would have exited 1 on "No release tag available" for
every release. Filed independently by three lenses and confirmed against the
reusable's actual source; docs/12 §2.3 had the same omission and is fixed too.
Ironically the comment right above it explains why the workflow deliberately is
not event-driven -- which is exactly what makes tag_override mandatory.

**Nothing checked the BUILT manifest.** The unit test reads wxt.config.ts,
which proves what we ask for, not what WXT emits. Those differ: a dev build of
this same config carries ["bookmarks","storage","tabs","scripting"] and
host_permissions ["http://localhost/*"]. Production is clean, but that is
WXT's behaviour, not ours. scripts/check-manifest.mjs now gates the artifact
and runs in both CI and release; verified by editing a built manifest. The
README sentence claiming a test asserted the built manifest was false and is
corrected -- the same overclaim I had already made once verbally.

**The contrast test I added last commit could not see its own bypass.**
TabBar's `.locked { opacity: 0.65 }` composites --fg-muted against the page and
drops the label to 2.83:1. The test reads token values, so alpha applied on top
is invisible to it. Opacity removed; the padlock and title already carried the
signal. TEXT_PAIRS also widened to check the status colours on --bg, not only
--bg-raised.

**docs/09 T3 was signed off with half its mitigation unbuilt.** The row has
always specified a ⚠ badge for dangerous schemes; only the blocking existed. A
`javascript:` bookmark titled "Your bank" rendered identically to a safe one
and its Open button silently did nothing. isBlockedUrl now drives a badge, and
a refused open raises a toast.

Also: the five row action buttons had glyphs as their accessible names (content
beats title in accname), so voice control could not address them; the manifest
test's literal-harvesting regex would have passed a spread or identifier;
resolveNewFolderParent returned a focused unmodifiable folder's id, which every
create rejects; and clipboard.ts was the only new module with no test.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 14:57:15 +07:00
poli0981andClaude Opus 5 6a8ede7373 feat(security): close the two gaps the T1-T8 pass found
Walking docs/09's threat model against the shipped code turned up two things
that had gone unnoticed because nothing mechanical was watching either.

**The permission list had no test.** "Exactly bookmarks + storage" is
CLAUDE.md's first hard rule, the README's headline privacy claim, the store's
privacy-tab answer and a line in the privacy policy -- and a single added
string in wxt.config.ts would have shipped silently. tests/unit/manifest.test.ts
now asserts the list exactly, plus the absence of host_permissions,
content_scripts, a background worker and eight other reach-widening keys.
Verified to fail by sneaking in 'tabs'. It reads the config as text, with
comments stripped, so the assertion cannot be satisfied by something computed
at build time -- and because the file's own header says "No host_permissions,
no content_scripts", a naive substring check failed on the prose promising the
very thing it checks.

**"Copy URL" was never built.** docs/06 §3.3 lists it in the row menu and
docs/09 T8 describes its mitigation, so the threat model documented a control
for a feature that did not exist. Now implemented in browser/clipboard.ts:
write-only, on an explicit click, never reads the clipboard, and needs no
permission because a transient user activation grants clipboard-write.

Also records the measured pass in docs/09 §2 and the reproducibility finding in
§5: content-identical rebuilds (every zip entry matches by CRC32) but not
byte-identical, because wxt zip records mtimes. The old wording implied more
than is true.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 14:57:15 +07:00
poli0981andClaude Opus 5 ba11fbf229 ci: add the four caller workflows
Per docs/12 §2, with every input checked against the ops repo's actual
workflow_call blocks rather than the doc — docs/12 originally described a
template family that had never existed.

Verified before writing: reusable-chrome-extension.yml takes
package-manager/node-version/build-command/source-dir/release and declares NO
secrets block, so passing a named secret to it would be a compile error;
reusable-codeql.yml takes `languages` as a JSON-array string (the older
codeql.yml's singular `language` is the wrong one); notify-ci-failure.yml
declares DISCORD_CI_WEBHOOK required:true; announce-release.yml's secrets are
optional. actions/checkout@v7 and setup-node@v6 are what the ops repo itself
runs.

Three traps the comments now carry, because each costs a run to rediscover:
- leaving package-manager at its 'none' default skips install and build, then
  fails on `test -f ./manifest.json`, a file WXT never writes to the repo root;
- reusable workflows do not inherit the caller's permissions, so every caller
  repeats its permissions block on the job;
- the release announcement is a job INSIDE release.yml, not an
  `on: release: [published]` caller — a Release created by gh under the default
  GITHUB_TOKEN emits no event that starts new workflow runs, so the
  event-driven version silently never fires.

The quality job is local because the reusable runs no quality gates at all.
All four parse, and `npm run zip` emits .output/bookmarkmagic-0.1.0-chrome.zip,
matching the glob release.yml uses.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 14:57:15 +07:00
poli0981andClaude Opus 5 f929336007 docs: add CHANGELOG and README, and point About's link at the real file
CHANGELOG.md follows Keep a Changelog with the semver policy docs/12 §4
defines, and carries a marker for the human step at first release (rename
[Unreleased] to [1.0.0]).

README leads with what the project is actually for and then spends its longest
section on privacy, because that is the product's reason to exist and every
claim in it is mechanically enforced: the grep gate for network calls, the
manifest assertion for permissions, zero runtime dependencies. It also keeps
docs/13's honesty corner -- favicons, import dates, CSV flattening -- rather
than only listing what works.

src/lib/links.ts now points "Changelog" at blob/main/CHANGELOG.md instead of
the /releases placeholder it used through Phase 4, and the links test asserts
the file exists, the same way it already does for the four legal documents. A
link shipped inside the product must not 404 because someone renamed the
target.

Screenshots and the store URL are marked ⚠️ in the README -- both need a human
and neither blocks the code.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 14:57:15 +07:00
poli0981andClaude Opus 5 a447d550bf refactor(edit): split EditTab under the size limit and test what came out
EditTab.svelte was 589 lines against the 500-line hard limit in docs/10 §1 --
the one place in the codebase that broke it. Now 459.

Extracted, in each case because the thing was genuinely cohesive rather than to
hit a number:

- src/lib/edit/edit-node.ts -- toEditNode, flattenTree, isEditable,
  resolveNewFolderParent, countDescendants, extraCopyIds. All pure, all
  previously inline and therefore untestable. resolveNewFolderParent in
  particular encodes a fixed bug (a focused root resolving to the synthetic
  root "0", which every create rejects) that nothing was pinning.
- src/lib/browser/open-url.ts -- the docs/09 T3 scheme allowlist, which is the
  only thing between a crafted `javascript:` bookmark in someone's import file
  and the browser acting on it. It had NO test. It does now, including the
  case-shouting dodge and data:/file:/chrome:.
- EditToolbar.svelte and MoveToDialog.svelte -- presentational, with their
  styles copied verbatim. This is a move, not a redesign.

The script block is still 279 lines against docs/10 §1's 150-line guidance. The
remainder is the mutation layer (guardEdit and the six operations), which is
coupled to reactive state and would need accessor indirection to move. Adding
that indirection to the app's delete paths immediately before a release is a
worse trade than the line count, so it stays and is recorded in CLAUDE.md
rather than quietly ignored.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 14:57:15 +07:00
poli0981andClaude Opus 5 9e937bff30 fix(ui): make every colour token meet the contrast the spec has always required
docs/06 §5 has said "≥ 4.5:1 in both themes (tokens chosen accordingly)" since
the spec was written. Nothing enforced it, and the tokens were not chosen
accordingly. Measured:

  white on dark --accent      3.67:1   (fixed in Phase 4)
  white on dark --danger      2.74:1   Button/ConfirmDialog .danger
  light --warn on --bg-raised 3.40:1   WarningList summary
  light --success  "     "    3.26:1   TreePreviewNode badge, DuplicatePanel
  light --danger   "     "    4.27:1   DuplicatePanel count
  dark --accent    "     "    4.40:1   links inside raised panels

Adds --danger-fg, which like --accent-fg must be redefined in the dark block in
the OPPOSITE direction: dark mode lightens the colour for contrast against the
page, and that is exactly what breaks white ink sitting on it.

The light status colours are now darker than an eyeball would pick, because all
three are rendered as text on --bg-raised. Adjustments preserve hue and were
solved for numerically rather than guessed; each clears 4.5 with margin.

The real deliverable is tests/unit/styles/contrast.test.ts, which parses
tokens.css and fails on any text pair below 4.5:1 — verified to actually fail
by restoring the old --warn and watching it report 3.40:1. It also pins the two
dark blocks (explicit override and prefers-color-scheme) against each other,
because they already drifted once when --accent-fg was added to only one.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 14:57:15 +07:00
poli0981andClaude Opus 5 72e7c29428 docs: record the Phase 4 browser verification and the resolved contact email
Phase 4 is now verified on a real browser, which every earlier phase had been
and this one had not: the gate's block/reach/persist behaviour, EN→VI→JA live
switching with localized numbers and dates, the theme control, settings
surviving an immediate tab close (the path the $state-proxy DataCloneError
would have broken), and the Phase 2–3 flows still working after Phase 4 touched
their tabs and the settings store.

docs/00 §10 item 4 closes: the contact email in legal/PRIVACY.md is filled in
and confirmed live. That was the last thing standing between the repo and the
docs/13 §1 store runbook that is not Phase 5 work.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:54:25 +07:00
poli0981andClaude Opus 5 01c46beecb docs: record the Phase 4 review outcome
The plural helper docs/07 §5 asked for now exists, so §5 names it and the two
shape tests that enforce it. The decision log gains the five design choices
the review forced, and the progress note records that 19 of 33 findings
survived verification -- including the first-run dead-end where the gate was
reachable only from the routes it blocked.

Adds one measured defect to the Phase 5 list rather than fixing it silently:
Button's .danger/.success hardcode white, which is 2.75:1 on dark-theme
--danger. Same class of bug as the --accent-fg one Phase 4 fixed, but it needs
new tokens and a visual decision rather than a mechanical change.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:54:25 +07:00
poli0981andClaude Opus 5 0e0f041eb8 fix(i18n): plural forms, the count the retrofit missed, and error text that re-translates
Last batch from the Phase 4 adversarial review, including one the completeness
critic caught that none of the six lenses looked for.

The num() retrofit was incomplete: FolderPickNode rendered its per-folder count
raw, so a Vietnamese user saw "12345" in the export pick tree while StatsCard
showed "12.345" on the adjacent tab. docs/07 §3, written in this same phase,
enumerates exactly three exemptions and this was on none of them.

ImportTab resolved t('errors.…') inside a catch block and stored the resulting
STRING in the session store. t() is only reactive where it is called, so the
error message froze in whatever language was active when it happened and never
followed a language switch. Phase 4 is what makes that observable -- until now
there was no way to switch language at runtime. The store holds the key now.

docs/07 §5 specifies plural keys as { one, other } objects in every locale with
a helper that selects by locale. No such helper existed and the dictionaries
used "(s)" instead, which produced "1 unreadable date(s) were left blank." --
wrong in more ways than the parenthesis. selectPluralForm uses Intl.PluralRules
(en gives one/other, vi/ja only ever other, so two forms cover every locale we
ship) and tPlural supplies a locale-grouped {n} so callers pass a raw count.
All seven warning codes are plural keys, including the two that interpolate no
count, so WarningList can call tPlural unconditionally instead of maintaining a
list of which codes count things.

Also splits getGeneratorVersion from getAppVersion: the UI hides an unknown
version, but a file field cannot be hidden, and "BookmarkMagic " with a
trailing space is a worse artifact in an export -- and in the forced Replace
safety backup -- than the bare product name.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:54:25 +07:00
poli0981andClaude Opus 5 bb7962d98a fix(a11y): contrast, focus ring, radiogroup keys, live region and document language
Five findings from the Phase 4 adversarial review, all of them things a green
build cannot see.

tokens.css redefined --accent in both dark blocks but never --accent-fg, so
dark mode painted white on #8b6dff -- 3.67:1, under the 4.5:1 docs/06 §5
requires. That hit the ThemeToggle's selected chip and every primary button.
Dark ink on the same violet measures 4.84:1.

ThemeToggle's `overflow: hidden` clipped the global :focus-visible ring, which
base.css draws at outline-offset: 2px, i.e. entirely outside the clip region.
The theme control had no keyboard focus indicator at all. Corner rounding is
per-child now and the ring is inset.

ThemeToggle also claimed role="radiogroup"/"radio" while implementing neither
roving tabindex nor arrow keys, so a screen reader announced "radio button,
1 of 3", switched to forms mode, and then the arrows did nothing while all
three stayed separate tab stops -- the inverse of the pattern (WCAG 4.1.2).
Arrow/Home/End now work and only the selected radio is a tab stop. The handler
sits on the radios, not the group: a keydown handler on a non-focusable
container never fires.

Toast built its role="status" region and its text in one DOM insertion. Screen
readers derive announcements from mutations to a region that was ALREADY
present, so success toasts were never announced. Two permanently-mounted
regions now, polite and assertive, with only their text changing -- two rather
than one with a swapped aria-live, because changing politeness at runtime is
not reliably picked up.

applyLocale never touched <html lang>, and both entrypoints ship lang="en", so
a screen reader read Vietnamese and Japanese with an English voice. It also
fixes the toast's dismiss button, which was labelled "Cancel" -- there is
nothing to call off, the operation already finished.

Also routes the last three hardcoded English aria-labels ("Sections",
"Preview" x2) through the dictionary. They date from Phase 2, but full EN/VI/JA
coverage is this phase's exit criterion.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:54:25 +07:00
poli0981andClaude Opus 5 72b169f5a0 fix(i18n): show the localized failure message, not the raw browser error
Found by the Phase 4 adversarial review; three lenses filed it.

Every failure path was written `outcome.detail ?? t('...saveFailed')`. But
`detail` is set for any rejection that is an Error, which is the normal case
for chrome.storage.local.set -- so the `??` almost never fell through and the
localized sentence was dead code in all three locales. A Vietnamese user over
quota saw "QUOTA_BYTES quota exceeded".

The worst instance was legal.saveFailed: "Your acceptance could not be saved,
so nothing was recorded. Check that this browser allows extension storage,
then try again." Translated into VI and JA, and unreachable -- at the one
moment a first-run user most needs an actionable instruction.

docs/02 §7 already specified the right shape: "human-readable, localized
messages + a copyable technical detail block", which ImportTab has done since
Phase 2. The message is now the translated sentence and the raw error moves
into a <pre class="detail"> beside it, in both #settings and the gate. The
header controls show the sentence alone -- there is no room for a detail block
there, and #settings has one.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:54:25 +07:00
poli0981andClaude Opus 5 02817bdfe0 fix(legal): make the gate reachable from every route, and stop About lying after a bump
Found by the Phase 4 adversarial review; four of six lenses filed it
independently.

The gate rendered only on #import/#export/#edit, and TabBar rendered exactly
those three tabs `disabled` while it was up. But they are the only in-app
navigation to a gated route, and the footer only offers #settings and #about.
So a first-run user who reached #settings -- the flow docs/14 §2 explicitly
prescribes, "so a VI/JA user can switch language and theme first" -- had no
enabled control that led back to the accept UI.

Worst path, introduced by the popup gear this same phase: fresh profile, no
Manager tab, click ⚙. openManager creates a NEW tab at #settings, so there is
no history entry to go Back to. Reopening from the popup does not rescue it
either -- open-manager deliberately focuses the existing tab without touching
its hash (docs/02 §6). The only escapes were editing the URL fragment or
closing the tab.

The fix is that disabling was never what blocked anything: App.svelte already
substitutes <LegalGate> for the tab body on any gated route, which is what
keeps Import/Export/Edit from mounting pre-acceptance. So the tabs are now
clickable and clicking one shows the gate. They carry legal.blocked as their
title -- a key that was translated into all three locales and rendered
nowhere, which is its own half of the same defect: the dead tabs gave no
reason at all.

Separately: decideLegalStatus dropped the stored record on the `updated` path,
so the first time LEGAL_VERSION is bumped, About would tell a user who
accepted v1 that they have never accepted anything. It now carries the
superseded acceptance. Dead code today (LEGAL_VERSION is 1), a wrong statement
about consent the day it is not.

Also clears LegalGate's close timer before setting a new one; repeated clicks
stacked timers and only the last was ever cleaned up.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:54:25 +07:00
poli0981andClaude Opus 5 432645ca43 docs: reconcile the spec with Phase 4
The docs are binding, so where Phase 4 diverged from them the divergence has
to be written down rather than left as an undocumented difference between
spec and code.

Three owner decisions recorded: six settings rows (markdownStyle was persisted
but only editable as a transient #export control), all five donate handles in
About, and a three-way segmented theme control rather than a cycling glyph.

One genuine conflict resolved: docs/06 §3 called the Legal Gate "a full
overlay" while docs/14 §2 -- echoed in docs/03 §4 and the decision log --
requires #settings and #about to stay reachable while it is up. Those cannot
both be satisfied literally, so docs/06 now says the gate fills the content
region and explains why.

Also: docs/02's directory tree had been stale since Phase 2 (it predated
lib/edit, lib/export and lib/import entirely); docs/03 §4 documented a
five-field Settings shape that had six fields in code; docs/07 §3 now names
where the Intl helpers live and, more usefully, the three sites that
deliberately do NOT use them; docs/11 §5 gains the QA items Phase 4 created.

The decision log gains fifteen rows, including the cross-tab sync limitation,
recorded as a known limitation rather than left to be rediscovered in review.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:54:25 +07:00
poli0981andClaude Opus 5 636182f1ef feat(legal): the first-run Legal Gate
docs/14 §1: the Chrome Web Store has no pre-install acceptance mechanism, so a
first-run gate is what makes the terms reachable at all. Without it the
extension cannot be submitted.

acceptLegal writes, awaits, and flips to `accepted` ONLY once the write
resolves. Getting this backwards is the exact defect shape the last three
phase reviews kept finding: dismiss optimistically, await a chrome.* call that
can reject, never handle the rejection. Here that would leave the user
accepted in the UI and unaccepted on disk, so the gate would silently return
next launch with no explanation. There is a test that rejects the write and
asserts the gate stays up and storage stays empty.

It fails CLOSED: an unreadable store gates. Showing the gate to someone who
already accepted costs one click; skipping it for someone who has not is not
recoverable. A stored version NEWER than LEGAL_VERSION still counts as
accepted -- re-gating on a downgrade is noise, not consent.

The gate fills the content region rather than covering the viewport. docs/06
§3 calls it "a full overlay", but docs/14 §2 -- echoed in docs/03 §4 and the
docs/15 log -- requires #settings and #about to stay reachable while it is up,
and a literal inset:0 scrim buries the footer links that get you there. The
docs edit reconciling this follows in the docs commit. A side effect worth
keeping: Import/Export/Edit never mount before acceptance, so nothing touches
chrome.bookmarks until the user has agreed.

"Close tab" does not bet the decline path on window.close(): the Manager is
opened by tabs.create, so window.opener is null and close() may no-op. It
waits 150 ms and says so plainly if the document is still there. tabs.remove
is not an option -- that needs the `tabs` permission docs/08 §2 forbids.

Also finally consumes TabBar's `blocked` prop, which has sat unused since
Phase 2, and adds About's acceptance line -- showing the version the user
ACCEPTED, not the current constant.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:54:25 +07:00
poli0981andClaude Opus 5 e5b0d667a2 feat(about): the #about tab, manifest version, and outbound links
Completes docs/06 §3.5: identity, tagline, GitHub/issues/changelog links, the
"Third-party dependencies: None" statement, all five donate handles from
.github/FUNDING.yml (docs/14 §5), and the four legal documents. The
acceptance-date line follows in the Legal Gate commit, which owns that store.

The displayed version now comes from the manifest, as docs/06 §3.5 requires.
It was hardcoded as "0.1.0" in THREE places -- the Manager footer, run-export
and run-import -- so a release bump had three chances to leave a stale number
in a footer users quote in bug reports, and two chances to write a lying
`generator` field into an exported backup. getAppVersion() returns '' rather
than a plausible fallback, and every render site hides the line instead.

Static links are <a target="_blank" rel="noopener noreferrer">. docs/09 T3
bans <a href> for *imported* bookmark URLs, which is untrusted data and keeps
using tabs.create in #edit; these are compile-time literals in one module.
Using tabs.create here would add an awaited call that can reject, for nothing.

Changelog points at /releases: CHANGELOG.md is Phase 5 work, and a 404 opened
from a legal-adjacent surface is worse than an empty releases page. A test
pins it, and another asserts every legal URL resolves to a file that actually
exists in legal/ -- a rename would otherwise ship four dead links inside the
legal gate with nothing else noticing.

Also drops common.comingSoon now that no route falls through to a placeholder.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:54:25 +07:00
poli0981andClaude Opus 5 2ea92da4ef feat(settings): the #settings tab, header controls, and a save path that tells the truth
Six rows per docs/06 §3.4 as amended -- the doc drew five, but Settings has
carried markdownStyle since Phase 3 and #export was the only place to change
it, so it never actually persisted. Plus the header language/theme controls
from the docs/06 §3 layout, which have been missing since Phase 0.

Three defects in the store had to be fixed for any of this to work, and none
of them could fail before, because updateSettings and resetSettings had zero
callers in src/:

- writeSettings handed the Svelte $state proxy to chrome.storage.local.set,
  which structured-clones its argument. Proxies are not cloneable, so every
  save would have thrown DataCloneError in a real browser. fakeBrowser stores
  the reference without cloning, which is why 338 green tests never saw it;
  the new test clones explicitly to reproduce Chrome.
- updateSettings replaced the settings object rather than mutating it, so any
  component capturing getSettings() into a local would silently stop updating.
  Four new components read this store. Now in-place, with an identity test.
- resetSettings left the pending debounce running, so a reset within 200 ms of
  a change wrote twice -- the first write persisting values just discarded.

updateSettings now returns a SaveOutcome that resolves when the write settles
and never rejects, so the "Saved" toast reports what happened instead of
assuming. flushSettings on visibilitychange shrinks the loss window from
200 ms to roughly nothing; the comment is explicit that it does not reach zero.

Both entrypoints now await settings before mount() and drop the unguarded
browser.i18n.getUILanguage() call at module scope, which could blank the page
on a throw. Awaiting means the pre-load frame is an empty #app rather than
content painted in the wrong locale and theme. Verified top-level await
survives wxt build.

Also gates the footer nav on isWriting(): navigating away during `attesting`
unmounts ImportTab and strands its attestation resolver, deadlocking the
import until reload. TabBar already guarded this; the footer was the way
around it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:54:25 +07:00
poli0981andClaude Opus 5 4f77bd17fd feat(ui): store-backed Toast with a real queue
docs/06 §4 specifies a Toast (queue, auto-dismiss 4s, ARIA status) and §3.4
needs one for the Settings auto-save. All that existed was an inline
<p role="status"> in #export that never dismissed -- and that assigned error
strings to the same variable its CSS painted var(--success), so a failed
export reported itself in success-green. That is fixed here.

The store owns the timers rather than the component, because <Toast> mounts
once at the App root while the route chain below it unmounts on every
navigation. Component-owned timers would leak by construction.

Two queue rules exist for specific races, and both are pinned by tests:
timeouts are keyed by item id and re-check the head before shifting, so a user
dismiss racing a timer cannot double-shift and flash the next toast for a
frame; and a repeat of the visible message restarts its timer instead of
queueing a twin, because one debounced save resolves one promise that may have
several subscribers.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:54:25 +07:00
poli0981andClaude Opus 5 c104754e8b refactor(i18n): route every rendered count through Intl.NumberFormat
docs/07 §3 says counts follow the UI locale, and the docs/11 §5 QA item is
"Language switch EN→VI→JA live-updates all tabs; dates/numbers localized".
Every count was being interpolated raw, so a Vietnamese user saw "1,284" where
their locale writes "1.284".

Three sites are deliberately left alone, each with a comment saying why, since
they all look like the retrofit missed them:

- ProgressBar's percentage is 0–100, no locale groups two digits, and it is
  the hottest render path in the app.
- ImportTab.formatFolderDate stays ISO — docs/07 §3 pins the created folder to
  the localized *word* plus an ISO date ("Đã nhập 2026-07-03"). Localizing it
  would change the names of folders written into the user's browser.
- run-export.isoDate and every filename stay locale-neutral so an exported
  file means the same thing whoever opens it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:54:25 +07:00
poli0981andClaude Opus 5 c955e071a9 feat(i18n): locale-aware formatting and the Phase 4 dictionaries
docs/07 §3 requires Intl for every rendered count and timestamp, but nothing
in src/ constructed an Intl formatter and there was no Locale -> BCP 47 tag
map at all. Adds a pure format.ts (cached formatters, since StatsCard alone
formats four counts per paint) plus num()/dateTime() wrappers that follow the
reactive locale.

formatDateTime returns undefined rather than a string on an unparseable date.
That is load-bearing: readLegal deliberately coerces a missing acceptedAt to
"", and Intl.format(new Date("")) throws a RangeError *inside a render* --
which would blank the About tab that Phase 4 is about to add.

Also lands the whole settings.*/about.*/legal.* tree in en, vi and ja ahead of
every consumer, and two runtime companions to the `satisfies Dict` compile
check. The token-equality test is the one that earns its keep: a translation
that drops {total} from "Importing... {done} / {total}" type-checks perfectly
and renders a broken sentence.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:54:25 +07:00
83 changed files with 4856 additions and 495 deletions

No files matched your search

+50
View File
@@ -0,0 +1,50 @@
# docs/12 §5. Two ecosystems: the npm dev toolchain, and the pinned actions in
# .github/workflows/.
#
# Note what this file cannot do: Dependabot *security* updates run from the
# repo's alerts regardless of any config here. Several currently fail because
# the advisories are against transitive dev dependencies with no reachable
# patched version. That is noisy but not shipped — BookmarkMagic has zero
# runtime dependencies, so `npm audit --omit=dev` reports 0 and nothing in the
# published extension is affected (docs/09 T5).
version: 2
updates:
- package-ecosystem: npm
directory: /
schedule:
interval: weekly
day: monday
open-pull-requests-limit: 5
commit-message:
# Conventional Commits — docs/10 §7 applies to bot commits too.
prefix: chore
prefix-development: chore
include: scope
groups:
# One PR per week for the routine churn, so CI runs once rather than
# eight times and the review is a single diff.
dev-minor-and-patch:
dependency-type: development
update-types:
- minor
- patch
ignore:
# Held deliberately: svelte-check and Volar need the TypeScript 6
# programmatic API until TS 7.1 (docs/01). A major bump here breaks
# `npm run check` rather than improving anything.
- dependency-name: typescript
update-types: [version-update:semver-major]
- package-ecosystem: github-actions
directory: /
schedule:
interval: weekly
day: monday
open-pull-requests-limit: 3
commit-message:
prefix: ci
include: scope
groups:
actions:
patterns: ['*']
+72
View File
@@ -0,0 +1,72 @@
# Caller stub — docs/12 §2.1.
#
# The `quality` job is local because the ops reusable runs NO quality gates at
# all: its entire surface is install → build → assert manifest_version == 3 →
# zip → upload. Lint, type-check, knip, coverage and the grep gate are ours.
name: CI
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
quality:
name: Quality gates
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: read
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: '24'
cache: npm
- run: npm ci
- run: npm run lint # biome check .
- run: npm run check # svelte-check + tsc --noEmit
- run: npm run knip
- run: npm run coverage # vitest --coverage, thresholds per docs/11 §1
- run: npm run guard # the canonical grep gate, docs/08 §3
# The unit test proves what wxt.config.ts ASKS for. Only this proves what
# WXT actually emitted — a dev build of the same config carries
# tabs/scripting/host_permissions that never appear in the config file.
- run: npm run build
- run: npm run check:manifest
build:
name: Build + package
needs: quality
# No `secrets:` here — the reusable declares no secrets block at all, and
# passing a named secret to it is a workflow-compile error.
uses: poli0981/.github/.github/workflows/reusable-chrome-extension.yml@main
permissions:
# `contents: write`, not `read`, even though nothing here writes.
#
# The reusable has two mutually exclusive jobs: `build` (contents: read,
# `if: !inputs.release`) and `release` (contents: write, `if:
# inputs.release`). GitHub validates the caller's grant against EVERY job
# the reusable declares, BEFORE evaluating any `if:` — so passing
# `release: false` does not exempt us from the release job's requirement.
# Granting only `contents: read` makes the whole run fail at startup with
# no jobs and no log, which is how this was found (docs/12 §2.1's sample
# had the same too-narrow grant).
contents: write
with:
# All four are required in practice. Leaving package-manager at its
# 'none' default skips install and build, then fails on
# `test -f ./manifest.json` — a file WXT never writes to the repo root.
package-manager: 'npm'
node-version: '24'
build-command: 'npm run build'
source-dir: '.output/chrome-mv3'
release: false
+36
View File
@@ -0,0 +1,36 @@
# Caller stub — docs/12 §2.2.
#
# Uses `reusable-codeql.yml` (CodeQL Action v4), NOT the older `codeql.yml`,
# whose input is the singular `language`. This one takes `languages`: a JSON
# array encoded as a string.
#
# ⚠️ Prerequisite: repo Settings → Advanced Security → CodeQL "Default setup"
# must be DISABLED, or this advanced-setup workflow is rejected at SARIF upload.
name: CodeQL
on:
push:
branches: [main]
pull_request:
branches: [main]
schedule:
- cron: '0 14 * * 1' # weekly, Monday
permissions:
security-events: write
actions: read
contents: read
packages: read
jobs:
analyze:
# Reusable workflows do not inherit the caller's permissions — the block
# below is repeated on the job on purpose.
uses: poli0981/.github/.github/workflows/reusable-codeql.yml@main
permissions:
security-events: write
actions: read
contents: read
packages: read
with:
languages: '["javascript-typescript"]'
+25
View File
@@ -0,0 +1,25 @@
# Caller stub — docs/12 §2.4.
#
# The reusable already filters to `conclusion == 'failure'` on the default
# branch, so this caller needs no `if:`.
#
# ⚠️ It declares `DISCORD_CI_WEBHOOK` as `required: true`, so this workflow
# fails until that repo secret exists (docs/12 §5).
name: Notify CI failure
on:
workflow_run:
workflows: ['CI']
types: [completed]
permissions:
contents: read
actions: read
jobs:
notify:
uses: poli0981/.github/.github/workflows/notify-ci-failure.yml@main
permissions:
contents: read
actions: read
secrets: inherit
+91
View File
@@ -0,0 +1,91 @@
# Release — docs/12 §2.3.
#
# Standalone rather than the ops reusable: the reusable's `release` job only
# runs `gh release create --generate-notes`. It produces no SHA256SUMS.txt
# (required by docs/09 §5), performs no store submission, and exposes no
# `outputs:`, so a caller cannot reference the zip it built.
name: Release
on:
push:
tags: ['v*']
permissions:
contents: read
jobs:
release:
runs-on: ubuntu-latest
timeout-minutes: 20
permissions:
contents: write # create the GitHub Release
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: '24'
cache: npm
- run: npm ci
# The same gates as CI. A tag must never ship what a PR would have
# blocked — pushing a tag skips the CI workflow's branch triggers.
- run: npm run lint
- run: npm run check
- run: npm run knip
- run: npm run coverage
- run: npm run guard
- run: npm run zip # wxt zip → .output/<name>-<version>-chrome.zip
# Gate the artifact, not just the config it was built from. A tag is the
# last point at which an unintended permission can still be stopped.
- run: npm run check:manifest
- name: Verify tag matches manifest version
run: |
set -euo pipefail
MANIFEST_VERSION=$(jq -r '.version' .output/chrome-mv3/manifest.json)
TAG_VERSION="${GITHUB_REF_NAME#v}"
test "$MANIFEST_VERSION" = "$TAG_VERSION" \
|| { echo "::error::tag $TAG_VERSION != manifest $MANIFEST_VERSION"; exit 1; }
- name: SHA256SUMS
working-directory: .output
run: sha256sum *-chrome.zip > SHA256SUMS.txt
- name: GitHub Release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
gh release create "$GITHUB_REF_NAME" \
.output/*-chrome.zip .output/SHA256SUMS.txt --generate-notes
# v1.0.x is published by hand (docs/12 §3) — first store reviews often
# ask questions and want a human in the loop. Flipping the repo variable
# CWS_AUTOPUBLISH to 'true' turns this on for v1.1+.
- name: Publish to Chrome Web Store
if: vars.CWS_AUTOPUBLISH == 'true'
env:
CHROME_EXTENSION_ID: ${{ secrets.CHROME_EXTENSION_ID }}
CHROME_CLIENT_ID: ${{ secrets.CHROME_CLIENT_ID }}
CHROME_CLIENT_SECRET: ${{ secrets.CHROME_CLIENT_SECRET }}
CHROME_REFRESH_TOKEN: ${{ secrets.CHROME_REFRESH_TOKEN }}
run: npx wxt submit --chrome-zip .output/*-chrome.zip
# A job INSIDE this workflow, not an `on: release: [published]` caller.
# A Release created by `gh release create` under the default GITHUB_TOKEN
# emits no event that starts new workflow runs, so an event-driven caller
# would silently never fire.
announce:
needs: release
uses: poli0981/.github/.github/workflows/announce-release.yml@main
permissions:
contents: read
with:
# REQUIRED here, and only because of the comment above. The reusable
# resolves `TAG="${INPUT_TAG:-$EVENT_TAG}"` with EVENT_TAG =
# github.event.release.tag_name — which is empty under `on: push: tags`,
# so without this the job exits 1 on "No release tag available" and the
# announcement never fires for any release.
tag_override: ${{ github.ref_name }}
secrets: inherit
+48
View File
@@ -0,0 +1,48 @@
# Changelog
All notable changes to BookmarkMagic are documented here.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
Per `docs/12 §4`: **patch** = fixes and translations · **minor** = features, and
any change to the permission list or the store privacy tab · **major** =
breaking format or schema changes (a BM JSON version bump).
## [Unreleased]
Nothing yet.
## [1.0.0] — 2026-07-26
First public release.
### Added
- Import bookmark files (Netscape HTML, BookmarkMagic JSON, CSV) with a full
preview — counts, folder depth, duplicates and warnings — before anything is
written.
- Three import modes: into a new dated folder (the default), merge into
existing folders, or replace everything. Replace downloads a JSON safety
backup first and deletes nothing until that backup is proven.
- Skip bookmarks whose URL already exists in this browser.
- Export everything, or just the folders you pick, to HTML, JSON, CSV or
Markdown.
- Edit the bookmark tree: search, rename, create folders, delete, drag & drop,
a keyboard "Move to…" with full parity, and a duplicate-finder panel.
- English, Vietnamese and Japanese, switchable in Settings independently of the
browser's own language.
- Light, dark and system themes.
- A first-run legal gate covering the EULA, licence, disclaimer and privacy
policy.
### Security
- Imported URLs are never rendered as links. Opening one goes through an
`http(s)`-only allowlist, so a `javascript:` or `data:` bookmark in a crafted
file cannot be activated from the extension.
- Parsing is bounded: 25 MB per file, 100 000 nodes, 200 levels of nesting.
- No network access of any kind at runtime, enforced by a grep gate in CI.
[Unreleased]: https://github.com/poli0981/bookmarkmagic/compare/v1.0.0...HEAD
[1.0.0]: https://github.com/poli0981/bookmarkmagic/releases/tag/v1.0.0
+9 -1
View File
@@ -87,7 +87,15 @@ performance budgets docs/11 §6, CI workflows per docs/12 §2 (explicit
`permissions:` blocks on every caller — and note the ops repo has **no**
`browser-extension-*` family), CHANGELOG, README (badges, screenshots ⚠,
install, privacy summary, donate), full manual QA (docs/11 §5), `wxt zip`
clean-install test.
clean-install test. Also carried in from the Phase 4 review:
- point About's "Changelog" link at `CHANGELOG.md` once it exists
(`src/lib/links.ts` currently targets `/releases`);
- ✔ `EditTab.svelte` split (589 → 459, under the hard limit). Its script block
is still 279 lines against the 150-line guidance; the remainder is the
mutation layer, which is genuinely coupled to reactive state and was left
whole rather than split behind accessors on the app's delete paths;
- ✔ contrast tokens fixed, and `tests/unit/styles/contrast.test.ts` now fails
the build on any text pair under 4.5:1.
**Exit:** ready for the docs/13 §1 runbook (human performs store submission).
## Working style
+115
View File
@@ -0,0 +1,115 @@
# BookmarkMagic
[![License: GPL-3.0-or-later](https://img.shields.io/badge/license-GPL--3.0--or--later-blue.svg)](LICENSE)
[![CI](https://github.com/poli0981/bookmarkmagic/actions/workflows/ci.yml/badge.svg)](https://github.com/poli0981/bookmarkmagic/actions/workflows/ci.yml)
[![CodeQL](https://github.com/poli0981/bookmarkmagic/actions/workflows/codeql.yml/badge.svg)](https://github.com/poli0981/bookmarkmagic/actions/workflows/codeql.yml)
[![Runtime dependencies: 0](https://img.shields.io/badge/runtime%20dependencies-0-brightgreen.svg)](#privacy)
Move your bookmarks between browsers the simple way: with a file. No account,
no cloud sync, 100% offline.
A Chrome (MV3) extension for importing, exporting and editing bookmarks and
folder trees. English · Tiếng Việt · 日本語.
## Screenshots
| Edit | Export |
|---|---|
| ![The edit tree, showing bookmarks with their domains](capture/Edit2.png) | ![The export tab: folder picker on the left, format cards on the right](capture/export.png) |
| Settings | About |
|---|---|
| ![Settings: language, theme, and four defaults](capture/Setting.png) | ![About: version, links, third-party statement, donate links and the legal block](capture/About.png) |
## What it does
- **Import** HTML, JSON or CSV bookmark files, with a full preview first —
counts, folders, depth, duplicates and warnings before anything is written.
- **Choose how**: into a new dated folder (the safe default), merged into your
existing folders, or replacing everything. Replace saves a JSON safety backup
first and **deletes nothing until that backup is proven**.
- **Export** everything, or just the folders you pick, to HTML (Chrome, Edge,
Brave, Firefox, Safari, Vivaldi, Opera), JSON, CSV or Markdown.
- **Edit** the tree: search, rename, drag & drop, create folders, delete, and
find duplicate links — every action reachable from the keyboard.
## Privacy
This is the whole point of the project, so it is worth being precise.
- **No network access at all.** Not analytics, not telemetry, not update pings.
There is no server. A grep gate (`npm run guard`) fails the build if anyone
adds `fetch`, `XMLHttpRequest`, `WebSocket`, `EventSource` or `sendBeacon`.
- **Exactly two permissions**: `bookmarks` and `storage`. No host permissions,
no content scripts, no background worker. Two gates enforce it: a unit test
over `wxt.config.ts`, and `npm run check:manifest`, which CI runs against the
**built** `manifest.json` — because a build can add what the config never
asked for.
- **Zero runtime dependencies.** Nothing third-party ships in the extension.
- Settings use `chrome.storage.local`, never `storage.sync`, so even your
preferences stay off any vendor cloud.
Full policy: [`legal/PRIVACY.md`](legal/PRIVACY.md).
## Honest limitations
- Favicons cannot be imported — the bookmarks API has no favicon field.
- Imported bookmarks get today's date. Chrome does not let an extension set a
bookmark's original creation date. Your **exported** files keep the real ones.
- CSV is a flattened view: empty folders and "which folder is the toolbar" are
not preserved. Use HTML or JSON for a faithful backup.
- Markdown is share-only — BookmarkMagic cannot read it back.
## Install
From the Chrome Web Store: ⚠️ *link once the listing is live.*
From source:
```bash
npm ci && npm run build
```
Then load `.output/chrome-mv3/` at `chrome://extensions` with Developer mode on.
## Development
```bash
npm run dev
```
`npm run verify` is the gate everything else answers to — lint, type-check,
knip, the grep gate and the test suite, in that order. It must be green before
every commit.
The [`docs/`](docs/) directory is the binding specification, not notes: where
code and docs disagree, the docs win. Start with [`CLAUDE.md`](CLAUDE.md), then
`docs/00`–`docs/02`.
## Contributing
Bug reports and translation fixes are welcome via
[issues](https://github.com/poli0981/bookmarkmagic/issues). A bug report about
parsing is far more useful with a sanitized sample of the file that broke.
Security issues: please follow [`SECURITY.md`](SECURITY.md) rather than opening
a public issue.
## Support development
Entirely optional — BookmarkMagic is free software either way.
[GitHub Sponsors](https://github.com/sponsors/poli0981) ·
[Ko-fi](https://ko-fi.com/skullmute) ·
[Buy Me a Coffee](https://www.buymeacoffee.com/skullmute) ·
[Patreon](https://www.patreon.com/skullmute) ·
[PayPal](https://paypal.me/DungDang212)
## Licence
[GPL-3.0-or-later](LICENSE). Also see [`legal/EULA.md`](legal/EULA.md),
[`legal/DISCLAIMER.md`](legal/DISCLAIMER.md) and
[`legal/THIRD_PARTY_NOTICES.md`](legal/THIRD_PARTY_NOTICES.md).
Not affiliated with or endorsed by Google, Chrome, or any browser vendor.
Browser names are trademarks of their respective owners.
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 163 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

+12 -9
View File
@@ -5,11 +5,11 @@
> **Owner:** poli0981 (GitHub) / SkullMute
> **Repo:** `poli0981/bookmarkmagic` ✔
> **License:** GPL-3.0-or-later
> **Status:** In development — **Phases 0–3 complete** (scaffold, core library,
> browser layer + import, export + edit). Verified working on real Chrome and
> Brave, 2026-07-25. Next: Phase 4 (i18n wiring, theming, Settings, About,
> Legal Gate). Sequencing lives in `/CLAUDE.md`.
> **Doc suite version:** 1.2 (2026-07-25 — reality pass)
> **Status:** In development — **Phases 0–4 complete** (scaffold, core library,
> browser layer + import, export + edit, and i18n/theming/Settings/About/Legal
> Gate). Verified working on real Chrome and Brave, 2026-07-25. Next: Phase 5
> (hardening + release prep). Sequencing lives in `/CLAUDE.md`.
> **Doc suite version:** 1.3 (2026-07-26 — Phase 4 reconciliation)
---
@@ -119,11 +119,14 @@ Derived identifiers (canonical across docs and code):
`github.com/poli0981/bookmarkmagic`.
2. ✔ Repo created, `LICENSE` committed. Variant resolved: **GPL-3.0-or-later**,
matching `poli0981/switch-every-tab-hotkey`.
3. **Designed** icon set (16/32/48/128 px) + CWS promo images. Not blocking:
`scripts/gen-icons.mjs` (ported from the portfolio precedent, zero-dep) emits
placeholder PNGs in the accent violet so the manifest loads from Phase 0.
3. ✔ Icon set (16/32/48/128 px) — the owner adopted the `scripts/gen-icons.mjs`
output as final on 2026-07-26, so the generator is the source of truth rather
than a placeholder. Regenerate with `npm run icons` after any change.
**Still open:** CWS promo images, which the store listing needs but the
extension does not.
4. ✔ Donate URLs resolved from `.github/FUNDING.yml` (`14 §5`).
Still open: contact email in `legal/PRIVACY.md`.
✔ Contact email filled in and confirmed live: `contact@poli0981.dev`
(`legal/PRIVACY.md`), alongside the GitHub Issues link.
5. Chrome Web Store: developer account already paid ✔ — create the item,
fill the Privacy tab per `08_MV3_COMPLIANCE.md`.
6. Repo secrets + settings per `12 §5` (incl. disabling CodeQL "Default setup").
+15
View File
@@ -77,20 +77,35 @@ bookmarkmagic/
│ │ │ ├── dedupe.ts
│ │ │ ├── diff.ts
│ │ │ ├── detect-format.ts
│ │ │ ├── plan.ts # buildImportPlan → segments (§4)
│ │ │ ├── search.ts # #edit filter + ancestor expansion
│ │ │ ├── select.ts # tri-state export selection → subtree
│ │ │ ├── csv-path.ts # folder-path encoding shared by CSV both ways
│ │ │ └── limits.ts # MAX_FILE_BYTES, MAX_NODES, MAX_DEPTH, LEGAL_VERSION
│ │ ├── browser/
│ │ │ ├── bookmarks.ts # getTree/create/move/update/remove wrappers
│ │ │ ├── write-queue.ts # sequential tree writer + progress + abort
│ │ │ ├── storage.ts # typed settings/legal accessors
│ │ │ ├── download.ts # Blob → <a download>
│ │ │ ├── app-info.ts # manifest version — the ONE source (06 §3.5)
│ │ │ ├── errors.ts # BmBrowserError / BmBackupError / BmAborted (§7)
│ │ │ ├── open-url.ts # http(s) allowlist before tabs.create (09 T3)
│ │ │ └── open-manager.ts # getContexts() focus-or-create
│ │ ├── import/run-import.ts # the import pipeline (03 §1)
│ │ ├── export/run-export.ts # the export pipeline (03 §2)
│ │ ├── edit/ # edit-node, patch-tree, move-target, tree-keyboard (03 §3)
│ │ ├── settings/options.ts # the six Settings choice tables (06 §3.4)
│ │ ├── links.ts # repo / legal / donate URLs (14 §4, §5)
│ │ ├── stores/ # Svelte 5 runes state (.svelte.ts)
│ │ │ ├── settings.svelte.ts # locale, theme, defaults (persisted)
│ │ │ ├── legal.svelte.ts # acceptedVersion
│ │ │ ├── toast.svelte.ts # transient status queue + its timers (06 §4)
│ │ │ ├── route.svelte.ts # location.hash + hashchange wrapper (§5)
│ │ │ └── import-session.svelte.ts
│ │ ├── i18n/ # runtime UI i18n (see 07_I18N.md)
│ │ │ ├── index.svelte.ts
│ │ │ ├── format.ts # pure Intl number/date helpers (07 §3)
│ │ │ ├── resolve-locale.ts
│ │ │ └── locales/{en,vi,ja}.ts
│ │ └── components/ # shared Svelte components (see 06_UI.md)
│ └── styles/
+16 -1
View File
@@ -129,7 +129,18 @@ import) appear without reload. Listeners attach on tab enter, detach on leave.
- Settings writes go through `stores/settings.svelte.ts` →
`chrome.storage.local` (debounced 200 ms). Shape:
`{ locale, theme, defaultExportFormat, defaultMergeMode, csvDelimiter }`.
`{ locale, theme, defaultExportFormat, defaultMergeMode, csvDelimiter,
markdownStyle }` — **six** fields, one `<SettingRow>` each (`06 §3.4`).
- `updateSettings(patch)` returns a `SaveOutcome` that resolves when the
debounced write has **settled**, and never rejects. UI feedback follows the
write; it never precedes it, or a failed save still says "Saved".
- The store object is **mutated in place**, never replaced, so a component that
reads `getSettings()` into a local cannot silently go stale. Writes pass a
plain snapshot — `chrome.storage.local.set` structured-clones its argument and
a Svelte `$state` proxy is not cloneable.
- `flushSettings()` runs on `visibilitychange` → hidden (not `beforeunload`,
which is cancellable). It shrinks the window in which an unwritten change is
lost from 200 ms to roughly nothing — not to zero.
- Legal gate: on Manager mount read `legal.acceptedVersion`; if
`< LEGAL_VERSION` render `<LegalGate>` overlay blocking **#import / #export /
#edit** — **#settings and #about stay reachable**, so a VI/JA user can switch
@@ -137,6 +148,10 @@ import) appear without reload. Listeners attach on tab enter, detach on leave.
switcher of its own. Accept → write version + timestamp → unlock.
This three-route set is normative; `14 §2` states the same list.
Details: `14_LEGAL_GATE.md`.
- The gate's accept path writes **first**, awaits, and only then reflects
acceptance in state. Dismissing optimistically would leave the user accepted
in the UI and unaccepted on disk, so the gate would silently reappear next
launch. A storage read failure fails **closed** (gate shown).
## 5. State machines (informal)
+84 -8
View File
@@ -11,7 +11,8 @@ framework.
--bg: #ffffff; --bg-raised: #f6f7f9; --border: #e2e5ea;
--fg: #1b1e24; --fg-muted: #5b6472;
--accent: #6d4aff; --accent-fg: #ffffff; /* violet — "magic" identity */
--danger: #d8384a; --success: #1f9d55; --warn: #b7791f;
--danger: #ce3547; --danger-fg: #ffffff;
--success: #198045; --warn: #99651a;
--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;
@@ -20,10 +21,27 @@ framework.
[data-theme="dark"] {
--bg: #16181d; --bg-raised: #1e2128; --border: #2b3039;
--fg: #e8eaee; --fg-muted: #9aa3b0;
--accent: #8b6dff; --danger: #ff6b7d; --success: #3ecf8e; --warn: #e2b93b;
--accent: #8f72ff; --accent-fg: #16181d;
--danger: #ff6b7d; --danger-fg: #16181d;
--success: #3ecf8e; --warn: #e2b93b;
}
```
⚠️ **`--accent-fg` and `--danger-fg` must be redefined in the dark block, in the
opposite direction to the colour they sit on.** Dark mode lightens `--accent`
and `--danger` for contrast against `--bg`, which is exactly what breaks white
ink on them — the original palette measured 3.67:1 and 2.74:1 there, against
the 4.5:1 §5 requires.
The light `--danger`/`--success`/`--warn` are darker than an eyeball would pick
because all three are rendered as **text** on `--bg-raised` (DuplicatePanel
counts, TreePreviewNode badges, WarningList's summary), where the original
values measured 4.27, 3.26 and 3.40.
None of these numbers is a matter of taste: `tests/unit/styles/contrast.test.ts`
parses `tokens.css` and fails the build if any text pair drops below 4.5:1, or
if the two dark blocks drift apart. Re-run it after changing a colour.
Theme: `data-theme` on `<html>`; default follows `prefers-color-scheme`,
manual override persisted in Settings. Focus rings always visible
(`:focus-visible` outline in accent).
@@ -58,7 +76,24 @@ there). No heavy work in the popup, ever.
```
Max content width 960px, centered. Settings/About open as tabs too (footer
links = same routes). `<LegalGate>` renders as a full overlay when required.
links = same routes, and both are disabled while an import is writing — see
`03 §5`). The version in the footer is read from the manifest at runtime
(`browser/app-info.ts`), never hardcoded.
The header's theme control is a **three-way segmented control**
(System · Light · Dark), not the single `◐` glyph the sketch above draws.
Rationale: one code path shared with the `#settings` row, and the current
choice is visible rather than inferred — a cycling button conflates "what am I"
with "what will I become", which fights §5.
`<LegalGate>` fills the **content region**, not the viewport. `docs/14 §2`
(echoed in `03 §4` and the `15` decision log) requires `#settings` and `#about`
to stay reachable while the gate is up, and a literal `inset: 0` scrim would
bury the footer links that get you there. So: a full-bleed panel inside
`<main>`, with the header and footer still live and the three blocked tabs
disabled via `TabBar`'s `blocked` prop. A side effect worth keeping — the
Import/Export/Edit tabs never mount before acceptance, so nothing touches
`chrome.bookmarks` until the user has agreed to the terms.
### 3.1 #import
@@ -106,19 +141,44 @@ Empty state: friendly illustration + "Import some bookmarks →".
### 3.4 #settings
Single column of `<SettingRow>`s: Language (EN/VI/JA select) · Theme
Single column of **six** `<SettingRow>`s: Language · Theme
(System/Light/Dark segmented) · Default export format · Default import mode ·
CSV delimiter. Auto-save + saved toast. Footer: "Reset to defaults".
CSV delimiter · Markdown layout.
- The Language select offers **four** options, not three: `Settings.locale` is
`'auto' | 'en' | 'vi' | 'ja'` and `DEFAULT_SETTINGS.locale === 'auto'`, so
"Automatic (follow the browser)" has to be selectable or the default is
unreachable. The three language labels are **endonyms**, identical in all
three dictionaries — a Japanese user hunting for Vietnamese looks for
"Tiếng Việt".
- Markdown layout is the sixth row because `markdownStyle` is a persisted
field; without it the only place to change it was a transient `#export`
control that never wrote back.
- Four of the six rows reuse the Export/Import tabs' own i18n keys rather than
inventing parallel wording, so the two surfaces cannot describe the same
choice differently.
Auto-save + saved toast — the toast reports the resolved `SaveOutcome`, so a
failed write says so rather than claiming success. Footer: "Reset to defaults",
behind a `<ConfirmDialog>` (six preferences is enough to be worth a confirm).
### 3.5 #about
`<AboutCard>`: logo, name, version (from manifest at runtime), tagline;
links: **GitHub repo ↗** · Report an issue ↗ · Changelog ↗;
**Third-party dependencies: None 🎉** (statement, satisfies the requirement);
Donate: GitHub Sponsors (`poli0981`) ↗ · Ko-fi (`skullmute`) ↗ — full handle
list in `14 §5`, sourced from `.github/FUNDING.yml`;
Donate: **all five** handles from `14 §5` / `.github/FUNDING.yml` — GitHub
Sponsors · Ko-fi · Buy Me a Coffee · Patreon · PayPal (platform names are brand
names and stay untranslated, `07 §4`);
Legal block: EULA · License (GPL-3.0) · Disclaimer · Privacy Policy — each →
GitHub `legal/` file; "Legal terms accepted on <date> · version n".
GitHub `legal/` file; "Legal terms accepted on <date> · version n" — where `n`
is the version the user **accepted**, from the stored record, not the current
`LEGAL_VERSION` constant. Reachable before acceptance (`14 §2`), so it also has
a not-yet-accepted state, and a dateless variant for a stored record whose
timestamp is missing or unparseable.
"Changelog" points at the repo's **releases** page until `CHANGELOG.md` exists
(Phase 5) — an empty releases page beats a 404 opened from a legal surface.
## 4. Component inventory (`src/lib/components/`)
@@ -132,6 +192,22 @@ auto-dismiss 4s, ARIA `status`) · `SettingRow` · `AboutCard` · `LegalGate` ·
Rule: components ≤ 300 lines; recursive tree logic isolated in `TreeNode`.
As built, some inventory names map differently — recorded so the list is not
read as a list of missing files:
| Inventory name | Realized as |
|---|---|
| `AboutCard` | `AboutTab.svelte`, for symmetry with the other four tab shells |
| `TreeView` | inline in `EditTab.svelte`; the row is `TreeRow.svelte` and the flattening lives in `edit/tree-keyboard.ts` |
| `TreeNode` | `TreePreviewNode.svelte` (import preview) + `FolderPickNode.svelte` (export picker) |
| `ResultCard` | inline in `ImportTab` |
| `SearchInput` | inside `EditToolbar.svelte` |
| — | plus `SettingsTab.svelte` (the fifth tab shell), `EditToolbar.svelte` and `MoveToDialog.svelte` |
`Toast`'s queue and timers live in `stores/toast.svelte.ts`, not the component:
one `<Toast>` mounts at the App root while the route chain below it unmounts on
every navigation, so component-owned timers would leak by construction.
## 5. Accessibility & keyboard
- Tree uses `role="tree"/"treeitem"`, `aria-expanded`, `aria-level`; arrow
+34
View File
@@ -88,6 +88,26 @@ export function setLocale(l: Locale) { locale = l; } // settings store persists
- Dates in UI: `new Intl.DateTimeFormat(localeTag, { dateStyle:'medium', timeStyle:'short' })`
with tags `en-US` / `vi-VN` / `ja-JP`.
- Numbers (counts): `Intl.NumberFormat(localeTag)` — VI uses `.` thousands.
Where these live: pure `localeTag` / `formatCount` / `formatDateTime` in
`src/lib/i18n/format.ts` (formatters cached per tag — `StatsCard` alone formats
four counts per paint), plus reactive `num()` / `dateTime()` wrappers in
`index.svelte.ts` that read the current locale. `formatDateTime` returns
`undefined` rather than a string on an unparseable input: `readLegal` coerces a
missing `acceptedAt` to `''`, and `Intl.format(new Date(''))` throws a
`RangeError` *inside a render*, which would blank the About tab.
Three rendered numbers deliberately do **not** go through `num()`, each with a
comment at the site so the next reader does not "finish the job":
| Site | Why |
|---|---|
| `ProgressBar`'s `{n}%` | 0–100; no locale groups two digits, and it is the hottest render path in the app |
| `import.folderName`'s date | this bullet list already pins it to the localized *word* + an **ISO** date; localizing it would rename folders written into the user's browser |
| Export filenames and file contents | locale-independent so a file means the same thing whoever opens it |
ARIA numeric attributes (`aria-level`, `aria-valuenow`) are not display text and
stay raw.
- File names & file contents stay locale-independent (ISO dates, English
"Imported" folder prefix? **No** — the auto-folder title uses the localized
word + ISO date, e.g. `Đã nhập 2026-07-03`, key `import.folderName`).
@@ -109,6 +129,20 @@ export function setLocale(l: Locale) { locale = l; } // settings store persists
a tiny helper selects by locale. VI/JA have one grammatical form, so they set
`one` and `other` to the same string. They must still carry both keys, or the
`satisfies Dict` shape check that §2 relies on for completeness fails.
Implemented as `selectPluralForm(count, tag)` in `i18n/format.ts` (backed by
`Intl.PluralRules`, narrowed to the two forms — en yields `one`/`other`, vi
and ja only ever `other`, so two forms cover every locale we ship) and
`tPlural(path, count, params?)` in `index.svelte.ts`, which supplies `{n}`
already grouped for the locale so callers pass a raw count. Two tests in
`tests/unit/i18n/dictionaries.test.ts` enforce the shape: every plural key
carries both forms in all three locales, and carries nothing else.
The current plural keys are `import.warnings.title` and **all seven**
`warnings.*` codes — including the two that interpolate no count, because
`ParseWarning` always carries one and a uniform shape lets `WarningList` call
`tPlural` unconditionally instead of maintaining a list of which codes count
things. Anything else stays a plain string.
- Legal Gate: the four legal documents are **English-only** (canonical), with
a localized one-line note: "The legally binding documents are in English."
- Store listing: EN required; VI + JA listings via CWS dashboard localized
+70 -3
View File
@@ -21,11 +21,44 @@
| T2 | Malicious file — resource exhaustion (huge/deep/zip-bomb-style) | 500 MB file, 1M nodes, 10k-deep nesting | Pre-parse size cap 25 MB; node cap 100 000; depth cap 200 — typed errors, parse aborts early. Lazy tree rendering (§05 §9) bounds DOM size. |
| T3 | Dangerous URLs in imported bookmarks (`javascript:`, `data:`) | Clicking them in #edit | Never rendered as `<a href>`; "Open" uses `tabs.create`, which refuses `javascript:`. UI marks non-http(s)/ftp/file/about/chrome schemes with a ⚠ badge; they are display-only. Imported URLs are stored verbatim (user's data, not ours to censor) — the browser's own bookmark UI applies its own rules. |
| T4 | Data loss from destructive import | User picks "Replace all" casually | Non-skippable auto safety-backup (BM JSON download) *before* deletion; danger-styled confirm with exact counts; default mode is non-destructive new-folder. |
| T5 | Supply-chain compromise | Malicious transitive dep | **Zero runtime deps**; dev deps pinned via lockfile; Dependabot + `npm audit` in CI; Biome installed exact-pinned. |
| T5 | Supply-chain compromise | Malicious transitive dep | **Zero runtime deps**; dev deps pinned via lockfile; Dependabot + `npm audit` in CI; Biome installed exact-pinned. See §5.1 for the `overrides` block. |
| T6 | Store-listing impersonation / trademark issues | — | Unique name + linked GitHub; report via CWS if cloned. |
| T7 | XSS via filenames/titles echoed into UI (result cards, toasts) | Weird characters in file name | Same as T1 — text interpolation only; filenames additionally sanitized for the *download* name (`[\\/:*?"<>|]` → `_`). |
| T8 | Clipboard abuse | "Copy URL" action | Uses `navigator.clipboard.writeText` on explicit user click only; never reads the clipboard. |
### Pass performed 2026-07-26 (Phase 5)
| # | Now enforced by |
|---|---|
| T1 | `tests/unit/core/fixtures.test.ts` parses `malformed/script-injection.html` and asserts the payloads survive as inert text. `DOMParser('text/html')` never executes scripts, and `{@html}` is barred by `npm run guard`. |
| T2 | `tests/unit/core/limits.test.ts` plus the caps in `core/limits.ts`. Measured: a 100k-node file parses without exhausting anything (`11 §6`). |
| T3 | `malformed/js-url.html` at parse level, `tests/unit/browser/open-url.test.ts` at the point of use — `javascript:`, `data:`, `file:`, `chrome:`, `vbscript:` and case-shouted variants are refused before `tabs.create` — and the ⚠ badge this row has always specified, which `isBlockedUrl` now drives in `TreeRow`. A refused open also raises a toast; it used to do nothing at all, which read as a broken button rather than a deliberate refusal. |
| T4 | `tests/unit/import/safety-backup.test.ts`. |
| T5 | `npm audit --omit=dev` reports **0** — every open Dependabot alert is `development` scope. |
| T6 | Human; nothing in code. |
| T7 | `sanitizeFilename` (`tests/unit/browser/download.test.ts`); everything else reaches the DOM through Svelte text interpolation. |
| T8 | `browser/clipboard.ts` — write-only, click-only, never reads. Implemented in Phase 5; it had been specified in `06 §3.3` and here since the start but never built. |
Three gaps this pass closed, all of which had gone unnoticed because nothing
mechanical was watching:
- **The permission list had no gate at all.** Two now exist, and both are
needed. `tests/unit/manifest.test.ts` asserts `['bookmarks', 'storage']`
against `wxt.config.ts` — what we *ask* for. `scripts/check-manifest.mjs`
asserts the **built** artifact, which is not the same thing: a dev build of
this identical config emits
`"permissions": ["bookmarks","storage","tabs","scripting"]` and
`"host_permissions": ["http://localhost/*"]`, because WXT injects them.
Production is clean today, but that is WXT's behaviour, not our enforcement.
Both were verified to fail — one by adding `'tabs'` to the config, the other
by editing the built manifest.
- **"Copy URL" did not exist**, so T8 described the mitigation for a feature
that was never shipped.
- **T3's ⚠ badge did not exist either.** The blocking half was real and tested;
the "mark dangerous schemes in the UI" half was not, so a `javascript:`
bookmark titled "Your bank" rendered exactly like a safe one and its Open
button silently did nothing.
## 3. Secure coding rules (enforced)
- `{@html}` — **forbidden**. Enforced by the canonical grep gate (`08 §3`) and
@@ -44,6 +77,33 @@
≤120-char excerpt of the offending line (avoids log-injection weirdness in
screenshots/issues).
### 3.1 The `package.json` `overrides` block
Six Dependabot alerts and six `npm audit` highs were all transitive **dev**
dependencies that their parents pinned to vulnerable ranges, so Dependabot's own
per-package PRs could not fix them — every one failed. `overrides` is the npm
mechanism for exactly this, and it takes `npm audit` to **0**.
| Override | Was | Reached through | Remove when |
|---|---|---|---|
| `shell-quote ^1.9.0` | 1.7.3 | `wxt > web-ext-run > fx-runner` | `web-ext-run` updates `fx-runner` |
| `adm-zip ^0.6.0` | 0.5.18 | `wxt > web-ext-run > firefox-profile` | `web-ext-run` updates `firefox-profile` |
| `tmp ^0.2.6` | 0.2.5 | `wxt > web-ext-run` | `web-ext-run` bumps `tmp` |
| `uuid ^11.1.1` | 8.3.2 | `wxt > web-ext-run > node-notifier` | `web-ext-run` updates `node-notifier` |
| `esbuild ^0.28.1` | 0.27.7 | `vite`, `wxt`, `unplugin` | vite/wxt allow 0.28.x |
| `brace-expansion ^5.0.8` | 1.1.16 | `web-ext-run > multimatch > minimatch` | `multimatch` unpins `minimatch` |
Four of the six exist only under **`web-ext-run`**, the Firefox dev runner
behind `npm run dev:firefox` — which `00 §7` lists as a v1.0 non-goal, and which
neither CI nor the Chrome build touches. ⚠️ **`npm run dev:firefox` is therefore
the one script these overrides could plausibly break**, and it is the one script
no gate exercises. Verify it by hand before relying on it.
Everything CI runs was re-verified after the overrides landed: lint, check,
knip, coverage, guard, build, `check:manifest` and `zip`, plus a clean-room
`npm ci`. Drop an override as soon as its parent ships the fix — a stale
override silently holds a package back.
## 4. Permissions posture
`bookmarks` + `storage`, nothing else (justifications in `08 §2`). Any PR
@@ -52,9 +112,16 @@ a **minor-version** event at minimum.
## 5. Release integrity
- Builds are reproducible from a clean checkout: `npm ci && npm run zip`.
- Builds are **content**-reproducible from a clean checkout: `npm ci && npm run
zip`. Verified 2026-07-26 by building the same commit in a fresh clone and in
the working tree — every entry in the two zips has an identical name and
CRC32. The archives' SHA-256 hashes still differ, because `wxt zip` records
file mtimes and nothing normalizes them (there is no `SOURCE_DATE_EPOCH`
support). Do not claim byte-identical rebuilds.
- GitHub Releases attach the exact zip uploaded to CWS + `SHA256SUMS.txt`
so users can verify store build ↔ source correspondence.
so users can verify store build ↔ source correspondence. That works on the
released artifact itself, which is the same file in both places — it is not a
claim that a third party can rebuild the same hash.
- Tags are signed (GPG) — consistent with the tracker-repo signing practice.
## 6. Vulnerability reporting
+34 -1
View File
@@ -130,8 +130,17 @@ generate-huge.ts # script: emits 100k+1 node file on demand
panel bulk-keep-first.
- [ ] Keyboard-only pass of the tree (WAI-ARIA pattern) + dialogs.
- [ ] Language switch EN→VI→JA live-updates all tabs; dates/numbers
localized; restart persists.
localized; restart persists. Header switcher and the `#settings` row
agree at all times (one state, two views).
- [ ] Theme: system/light/dark; contrast spot-check.
- [ ] Settings auto-save: change a value, close the tab immediately, reopen —
the value stuck. The "Saved" toast appears only *after* the write
confirms, and a failure says so instead.
- [ ] Legal Gate "Close tab" either closes the tab or shows the
manual-close message — never appears to do nothing.
- [ ] Two Manager tabs open: accepting or changing a setting in one is
reflected in the other (or record it as the known limitation it is —
`15` decision log).
- [ ] chrome://extensions → no errors logged during the whole pass.
- [ ] Edge (or Brave): smoke test install + import/export.
@@ -141,3 +150,27 @@ generate-huge.ts # script: emits 100k+1 node file on demand
- Preview render after parse: < 500 ms (lazy tree).
- Manager cold open: interactive < 1 s.
- Import 10k nodes: progress visible ≤ 500 ms after start; cancel ≤ 1 s.
### Measured 2026-07-26 — Phase 5
A generated 100 000-node Netscape file (11.2 MB, 99 000 bookmarks in 1 000
folders), timed **under jsdom**:
| Stage | Time |
|---|---|
| `detectFormat` | 0 ms |
| `parseNetscapeHtml` | **2 869 ms** |
| `buildUrlIndex` | 42 ms |
| `diffAgainstBrowser` | 53 ms |
| `serializeNetscapeHtml` | 72 ms |
⚠️ **This does not settle the 2 s budget either way.** Everything except the
parse is pure JS and comfortably fast; the parse is dominated by `DOMParser`,
and jsdom's parse5 implementation is roughly an order of magnitude slower than
Chrome's native parser. The budget is about the real browser, so the honest
reading is "≤ 2.9 s in the slowest environment we can measure from a test".
The number that decides it has to come from Chrome. Added to the §5 checklist:
- [ ] Generate a 100k-node HTML file, import it in a real browser, and time
from drop to preview. Record the number here rather than re-deriving it.
+21 -1
View File
@@ -63,13 +63,15 @@ jobs:
- run: npm run knip
- run: npm run coverage # vitest --coverage, thresholds per 11 §1
- run: npm run guard # canonical grep gate, 08_MV3 §3
- run: npm run build
- run: npm run check:manifest # the BUILT artifact, not just the config
build:
name: Build + package
needs: quality
uses: poli0981/.github/.github/workflows/reusable-chrome-extension.yml@main
permissions:
contents: read
contents: write # see the warning below — `read` fails at startup
with:
package-manager: 'npm' # 01 §6 commits package-lock.json
node-version: '24'
@@ -82,6 +84,16 @@ All four `with:` values are required. Omitting `package-manager` defaults it to
`'none'`, which skips install/build entirely and then fails on
`test -f ./manifest.json` — a file WXT never writes to the repo root.
⚠️ **`contents: write` on the `build` job is not a mistake.** The reusable
declares two mutually exclusive jobs — `build` (`contents: read`,
`if: !inputs.release`) and `release` (`contents: write`, `if: inputs.release`).
GitHub validates the caller's grant against **every job the reusable declares,
before evaluating any `if:`**, so `release: false` does not exempt the caller
from the release job's requirement. Granting `contents: read` makes the entire
run fail with `startup_failure`: no jobs, no log, and only the generic "this run
likely failed because of a workflow file issue" in the UI. Verified 2026-07-26
on the first real run of this workflow.
`npm run guard` runs the same script locally and in CI, so the gate cannot
drift between the two (`10 §3`). It is the single canonical pattern defined in
`08_MV3_COMPLIANCE.md §3`; do not restate the pattern here or anywhere else.
@@ -194,9 +206,17 @@ jobs:
uses: poli0981/.github/.github/workflows/announce-release.yml@main
permissions:
contents: read
with:
tag_override: ${{ github.ref_name }}
secrets: inherit
```
`tag_override` is **required here**, and for the same reason the announcement
is a job rather than a caller. The reusable resolves
`TAG="${INPUT_TAG:-$EVENT_TAG}"` with `EVENT_TAG = github.event.release.tag_name`
— empty under `on: push: tags` — so omitting it makes the job exit 1 on
"No release tag available" and the announcement never fires for any release.
The announcement is a **job inside this workflow**, not a separate
`on: release: [published]` caller. A Release created by `gh release create`
under the default `GITHUB_TOKEN` does not emit an event that starts new
+49 -4
View File
@@ -16,19 +16,45 @@ Build-phase breakdown lives in `CLAUDE.md` (single source for sequencing).
| 1 — Core library | ✔ 2026-07-25 | 3 parsers, 4 serializers, dedupe/diff/plan; 600 seeded round-trips |
| 2 — Browser layer + #import | ✔ 2026-07-25 | adapter, write queue, stores, full import flow incl. forced backup |
| 3 — #export + #edit | ✔ 2026-07-25 | tri-state picker, tree CRUD, search, duplicates, DnD + keyboard parity |
| 4 — i18n, theming, Settings, About, Legal Gate | next | dictionaries already exist in EN/VI/JA; the switcher UI does not |
| 5 — Hardening + release prep | pending | CI stubs per `12 §2`, CHANGELOG, README, full QA, `wxt zip` clean install |
| 4 — i18n, theming, Settings, About, Legal Gate | ✔ 2026-07-26 | switcher + theme controls, six-row `#settings`, `#about`, first-run gate; Intl retrofit; store-backed Toast |
| 5 — Hardening + release prep | next | CI stubs per `12 §2`, CHANGELOG, README, full QA, `wxt zip` clean install |
**Verified on real browsers 2026-07-25:** Chrome and Brave, unpacked build.
Until that point every phase had been tested only against a hand-rolled
`chrome.bookmarks` mock, because WXT's `fakeBrowser` stubs that API with
"not implemented" throws (`11 §4`).
Each of phases 1–3 was adversarially reviewed after implementation and each
review found real defects (7, 13 and 14 respectively) — several in the paths
**Phase 4 verified on a real browser 2026-07-26**, after the review fixes
landed. Covered: the Legal Gate (appears once, blocks the three routes, leaves
`#settings`/`#about` reachable pre-accept, re-renders in the language chosen
before accepting, and persists across a restart); EN→VI→JA live switching with
localized numbers and dates, and the header and `#settings` controls staying in
agreement; theme system/light/dark; settings surviving an immediate tab close —
the path the `$state`-proxy `DataCloneError` would have broken; and the Phase
2–3 import/export/edit flows still working after Phase 4 touched their tabs and
the settings store.
Each of phases 1–4 was adversarially reviewed after implementation and each
review found real defects (7, 13 and 14 in phases 1–3) — several in the paths
that delete bookmarks. Budget that review into the remaining phases; a green
test run has not once meant "done" on this project.
Phase 4's own review filed 33 findings across six lenses; 19 survived
adversarial verification. The most serious was a first-run dead-end: the gate
rendered only on the three routes it blocked, and those three tabs were the
only in-app navigation to them — so a user who reached `#settings` (via the
popup's new gear, which opens a fresh tab with no history) could never get
back to the accept UI.
Phase 4 also found three latent defects in code that 338 green tests had
already signed off, all unreachable until Phase 4 gave them a caller:
`writeSettings` handed a `$state` proxy to `chrome.storage.local.set` (would
throw `DataCloneError` in a real browser — `fakeBrowser` stores the reference
without cloning, so the suite could not see it); `updateSettings` replaced the
settings object rather than mutating it, which would strand any component that
captured it; and footer navigation during `attesting` stranded the import's
attestation resolver, deadlocking it until reload.
## v1.0.x — stabilization
- Parser-tolerance fixes from real user files (fixture + test per report).
@@ -93,3 +119,22 @@ test run has not once meant "done" on this project.
| 2026-07-25 | CI: ops repo has no `browser-extension-*` family; callers use `reusable-chrome-extension.yml` + a local quality job, release is standalone | 12 §2 |
| 2026-07-25 | Replace deletes nothing until the backup is **proven** — picker `close()` resolving, or an explicit user attestation on the anchor fallback | 03 §1 6b |
| 2026-07-25 | Every `#edit` mutation resyncs from the browser on rejection; roots and `unmodifiable` nodes offer no destructive affordance at all | 03 §3 |
| 2026-07-26 | Legal Gate renders **inside the content region**, not as a viewport overlay — `06 §3`'s "full overlay" reconciled in favour of `14 §2`'s reachable `#settings`/`#about` | 06 §3 |
| 2026-07-26 | Settings state mutates **in place**; every storage write passes a plain snapshot (a `$state` proxy is not structured-cloneable, so the old code would have thrown `DataCloneError` in a real browser) | 03 §4 |
| 2026-07-26 | `updateSettings` / `acceptLegal` return non-rejecting outcomes; UI feedback follows the write, never precedes it | 03 §4 |
| 2026-07-26 | Toast queue + timers live in a store, so they survive the route chain unmounting | 06 §4 |
| 2026-07-26 | Static outbound links use `<a target="_blank" rel="noopener noreferrer">`; imported bookmark URLs keep `tabs.create` (`09` T3 unchanged). Two mechanisms for two trust classes — do not harmonize | 09 T3 |
| 2026-07-26 | `#settings` has **six** rows: `markdownStyle` was persisted but only editable as a transient `#export` control | 06 §3.4 |
| 2026-07-26 | `locale: 'auto'` is a first-class fourth option in the switcher — it is the default, so it must be selectable | 06 §3.4 |
| 2026-07-26 | Language labels are endonyms, duplicated identically across the three dicts (the `common.appName` precedent) | 07 §4 |
| 2026-07-26 | Theme control is a three-way segmented control in both header and `#settings`, not a cycling `◐` | 06 §3 |
| 2026-07-26 | Version comes from the manifest at runtime; three hardcoded `0.1.0` literals removed (footer, `run-export`, `run-import`) | 06 §3.5 |
| 2026-07-26 | About's "Changelog" points at GitHub Releases until `CHANGELOG.md` exists in Phase 5 | 06 §3.5 |
| 2026-07-26 | The gate's acceptance checkbox deliberately resets if the user navigates away and back — an un-submitted legal affirmation is not worth persisting | 14 §2 |
| 2026-07-26 | Both entrypoints await settings (Manager also legal) **before** `mount()`, trading a blank frame for no locale/theme/gate flicker | 02 §2 |
| 2026-07-26 | **Known limitation:** two open Manager tabs do not sync settings or acceptance to each other; last write wins. No `storage.onChanged` listener in v1 | 03 §4 |
| 2026-07-26 | Gate-blocked tabs stay **clickable**; what blocks a route is the gate replacing the tab body, not an inert button. Disabling them removed the only in-app path back to the accept UI | 06 §3 |
| 2026-07-26 | Failure UI shows the localized sentence and puts the raw browser error in a separate detail block — `detail ?? t(key)` made every translation dead code | 02 §7 |
| 2026-07-26 | `--accent-fg` is redefined in the dark blocks alongside `--accent`; white on the lightened violet measured 3.67:1 | 06 §5 |
| 2026-07-26 | Plural keys implemented per `07 §5` (`selectPluralForm` + `tPlural`); `import.warnings.title` and all seven `warnings.*` codes converted | 07 §5 |
| 2026-07-26 | The import session stores an i18n **key**, not a resolved string — `t()` is only reactive where it is called, so a stored sentence never follows a language switch | 03 §5 |
+1 -1
View File
@@ -41,5 +41,5 @@ inside the Extension.
## Contact
⚠️ contact email — or open an issue at
Email: contact@poli0981.dev — or open an issue at
<https://github.com/poli0981/bookmarkmagic/issues>
+149 -141
View File
@@ -1,16 +1,17 @@
{
"name": "bookmarkmagic",
"version": "0.1.0",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "bookmarkmagic",
"version": "0.1.0",
"version": "1.0.0",
"hasInstallScript": true,
"license": "GPL-3.0-or-later",
"devDependencies": {
"@biomejs/biome": "2.5.5",
"@sveltejs/vite-plugin-svelte": "^7.2.0",
"@vitest/coverage-v8": "^4.1.10",
"@wxt-dev/module-svelte": "^2.0.5",
"jsdom": "^29.1.1",
@@ -681,9 +682,9 @@
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.27.7",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.7.tgz",
"integrity": "sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg==",
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",
"integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==",
"cpu": [
"ppc64"
],
@@ -698,9 +699,9 @@
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.27.7",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.7.tgz",
"integrity": "sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ==",
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz",
"integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==",
"cpu": [
"arm"
],
@@ -715,9 +716,9 @@
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.27.7",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.7.tgz",
"integrity": "sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ==",
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz",
"integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==",
"cpu": [
"arm64"
],
@@ -732,9 +733,9 @@
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.27.7",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.7.tgz",
"integrity": "sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg==",
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz",
"integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==",
"cpu": [
"x64"
],
@@ -749,9 +750,9 @@
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.27.7",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.7.tgz",
"integrity": "sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw==",
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz",
"integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==",
"cpu": [
"arm64"
],
@@ -766,9 +767,9 @@
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.27.7",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.7.tgz",
"integrity": "sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ==",
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz",
"integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==",
"cpu": [
"x64"
],
@@ -783,9 +784,9 @@
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.27.7",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.7.tgz",
"integrity": "sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w==",
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz",
"integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==",
"cpu": [
"arm64"
],
@@ -800,9 +801,9 @@
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.27.7",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.7.tgz",
"integrity": "sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ==",
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz",
"integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==",
"cpu": [
"x64"
],
@@ -817,9 +818,9 @@
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.27.7",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.7.tgz",
"integrity": "sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA==",
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz",
"integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==",
"cpu": [
"arm"
],
@@ -834,9 +835,9 @@
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.27.7",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.7.tgz",
"integrity": "sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A==",
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz",
"integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==",
"cpu": [
"arm64"
],
@@ -851,9 +852,9 @@
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.27.7",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.7.tgz",
"integrity": "sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg==",
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz",
"integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==",
"cpu": [
"ia32"
],
@@ -868,9 +869,9 @@
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.27.7",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.7.tgz",
"integrity": "sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q==",
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz",
"integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==",
"cpu": [
"loong64"
],
@@ -885,9 +886,9 @@
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.27.7",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.7.tgz",
"integrity": "sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw==",
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz",
"integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==",
"cpu": [
"mips64el"
],
@@ -902,9 +903,9 @@
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.27.7",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.7.tgz",
"integrity": "sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ==",
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz",
"integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==",
"cpu": [
"ppc64"
],
@@ -919,9 +920,9 @@
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.27.7",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.7.tgz",
"integrity": "sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ==",
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz",
"integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==",
"cpu": [
"riscv64"
],
@@ -936,9 +937,9 @@
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.27.7",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.7.tgz",
"integrity": "sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw==",
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz",
"integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==",
"cpu": [
"s390x"
],
@@ -953,9 +954,9 @@
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.27.7",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.7.tgz",
"integrity": "sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA==",
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz",
"integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==",
"cpu": [
"x64"
],
@@ -970,9 +971,9 @@
}
},
"node_modules/@esbuild/netbsd-arm64": {
"version": "0.27.7",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.7.tgz",
"integrity": "sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w==",
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz",
"integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==",
"cpu": [
"arm64"
],
@@ -987,9 +988,9 @@
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.27.7",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.7.tgz",
"integrity": "sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw==",
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz",
"integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==",
"cpu": [
"x64"
],
@@ -1004,9 +1005,9 @@
}
},
"node_modules/@esbuild/openbsd-arm64": {
"version": "0.27.7",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.7.tgz",
"integrity": "sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A==",
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz",
"integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==",
"cpu": [
"arm64"
],
@@ -1021,9 +1022,9 @@
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.27.7",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.7.tgz",
"integrity": "sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg==",
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz",
"integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==",
"cpu": [
"x64"
],
@@ -1038,9 +1039,9 @@
}
},
"node_modules/@esbuild/openharmony-arm64": {
"version": "0.27.7",
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.7.tgz",
"integrity": "sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw==",
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz",
"integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==",
"cpu": [
"arm64"
],
@@ -1055,9 +1056,9 @@
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.27.7",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.7.tgz",
"integrity": "sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA==",
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz",
"integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==",
"cpu": [
"x64"
],
@@ -1072,9 +1073,9 @@
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.27.7",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.7.tgz",
"integrity": "sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA==",
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz",
"integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==",
"cpu": [
"arm64"
],
@@ -1089,9 +1090,9 @@
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.27.7",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.7.tgz",
"integrity": "sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw==",
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz",
"integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==",
"cpu": [
"ia32"
],
@@ -1106,9 +1107,9 @@
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.27.7",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.7.tgz",
"integrity": "sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg==",
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz",
"integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==",
"cpu": [
"x64"
],
@@ -2614,13 +2615,13 @@
}
},
"node_modules/adm-zip": {
"version": "0.5.18",
"resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.5.18.tgz",
"integrity": "sha512-ufJnssQGbxzLNS1Ho9bCtX4rQKCCvoVuDLHoJyc3F9dOGDB4BkWs2Ci0kv53lqocAEQ/Cbi+I2XCsNYGqVYqng==",
"version": "0.6.0",
"resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.6.0.tgz",
"integrity": "sha512-XleryMhbuksdKtofnWZ9Sk+4CUTbms4Mb/EU32SZwToAyZ5RgVos/ki8n+yr0LWHOGKuakbXTuuYNHLQjhddgg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12.0"
"node": ">=14.0"
}
},
"node_modules/ansi-align": {
@@ -2830,11 +2831,14 @@
}
},
"node_modules/balanced-match": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
"integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",
"dev": true,
"license": "MIT"
"license": "MIT",
"engines": {
"node": "18 || 20 || >=22"
}
},
"node_modules/bidi-js": {
"version": "1.0.3",
@@ -2947,14 +2951,16 @@
}
},
"node_modules/brace-expansion": {
"version": "1.1.16",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.16.tgz",
"integrity": "sha512-IDw48K2/2kRkg9LdJxurvq3lV3aBgq0REY89duEqFRthjlPdXHKMj7EnQOXVckxzgisinf3nHfrcE2FufFLXMw==",
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.8.tgz",
"integrity": "sha512-JZyDyq3D4AUifKTPOB7DELf6XsB3WdPuNxCtob1vFXPsSXhdAiHBWJ/tJ8HAc9aH84BK+5JFZLNkJKx3G9kzQg==",
"dev": true,
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0",
"concat-map": "0.0.1"
"balanced-match": "^4.0.2"
},
"engines": {
"node": "20 || >=22"
}
},
"node_modules/buffer-equal-constant-time": {
@@ -3375,13 +3381,6 @@
"node": "^12.20.0 || >=14"
}
},
"node_modules/concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
"integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",
"dev": true,
"license": "MIT"
},
"node_modules/concat-stream": {
"version": "1.6.2",
"resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz",
@@ -3882,9 +3881,9 @@
"license": "MIT"
},
"node_modules/esbuild": {
"version": "0.27.7",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.7.tgz",
"integrity": "sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==",
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",
"integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
@@ -3895,32 +3894,32 @@
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.27.7",
"@esbuild/android-arm": "0.27.7",
"@esbuild/android-arm64": "0.27.7",
"@esbuild/android-x64": "0.27.7",
"@esbuild/darwin-arm64": "0.27.7",
"@esbuild/darwin-x64": "0.27.7",
"@esbuild/freebsd-arm64": "0.27.7",
"@esbuild/freebsd-x64": "0.27.7",
"@esbuild/linux-arm": "0.27.7",
"@esbuild/linux-arm64": "0.27.7",
"@esbuild/linux-ia32": "0.27.7",
"@esbuild/linux-loong64": "0.27.7",
"@esbuild/linux-mips64el": "0.27.7",
"@esbuild/linux-ppc64": "0.27.7",
"@esbuild/linux-riscv64": "0.27.7",
"@esbuild/linux-s390x": "0.27.7",
"@esbuild/linux-x64": "0.27.7",
"@esbuild/netbsd-arm64": "0.27.7",
"@esbuild/netbsd-x64": "0.27.7",
"@esbuild/openbsd-arm64": "0.27.7",
"@esbuild/openbsd-x64": "0.27.7",
"@esbuild/openharmony-arm64": "0.27.7",
"@esbuild/sunos-x64": "0.27.7",
"@esbuild/win32-arm64": "0.27.7",
"@esbuild/win32-ia32": "0.27.7",
"@esbuild/win32-x64": "0.27.7"
"@esbuild/aix-ppc64": "0.28.1",
"@esbuild/android-arm": "0.28.1",
"@esbuild/android-arm64": "0.28.1",
"@esbuild/android-x64": "0.28.1",
"@esbuild/darwin-arm64": "0.28.1",
"@esbuild/darwin-x64": "0.28.1",
"@esbuild/freebsd-arm64": "0.28.1",
"@esbuild/freebsd-x64": "0.28.1",
"@esbuild/linux-arm": "0.28.1",
"@esbuild/linux-arm64": "0.28.1",
"@esbuild/linux-ia32": "0.28.1",
"@esbuild/linux-loong64": "0.28.1",
"@esbuild/linux-mips64el": "0.28.1",
"@esbuild/linux-ppc64": "0.28.1",
"@esbuild/linux-riscv64": "0.28.1",
"@esbuild/linux-s390x": "0.28.1",
"@esbuild/linux-x64": "0.28.1",
"@esbuild/netbsd-arm64": "0.28.1",
"@esbuild/netbsd-x64": "0.28.1",
"@esbuild/openbsd-arm64": "0.28.1",
"@esbuild/openbsd-x64": "0.28.1",
"@esbuild/openharmony-arm64": "0.28.1",
"@esbuild/sunos-x64": "0.28.1",
"@esbuild/win32-arm64": "0.28.1",
"@esbuild/win32-ia32": "0.28.1",
"@esbuild/win32-x64": "0.28.1"
}
},
"node_modules/escalade": {
@@ -6690,11 +6689,17 @@
"license": "MIT"
},
"node_modules/shell-quote": {
"version": "1.7.3",
"resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.7.3.tgz",
"integrity": "sha512-Vpfqwm4EnqGdlsBFNmHhxhElJYrdfcxPThu+ryKS5J8L/fhAwLazFZtq+S+TWZ9ANj2piSQLGj6NQg+lKPmxrw==",
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.10.0.tgz",
"integrity": "sha512-w1aiOKwKuRgtwAReIIj89puqg+I7GvX4IbLrvmhXbzQsj1+Zwi4VO3+fa6ZF91TWSjIxoEkKnMeHcLEODK5ZXA==",
"dev": true,
"license": "MIT"
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/shellwords": {
"version": "0.1.1",
@@ -7128,9 +7133,9 @@
"license": "MIT"
},
"node_modules/tmp": {
"version": "0.2.5",
"resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.5.tgz",
"integrity": "sha512-voyz6MApa1rQGUxT3E+BK7/ROe8itEx7vD8/HEvt4xwXucvQ5G5oeEiHkmHZJuBO21RpOf+YYm9MOivj709jow==",
"version": "0.2.7",
"resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.7.tgz",
"integrity": "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw==",
"dev": true,
"license": "MIT",
"engines": {
@@ -7398,14 +7403,17 @@
"license": "MIT"
},
"node_modules/uuid": {
"version": "8.3.2",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
"integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",
"deprecated": "uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).",
"version": "11.1.1",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.1.tgz",
"integrity": "sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==",
"dev": true,
"funding": [
"https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
],
"license": "MIT",
"bin": {
"uuid": "dist/bin/uuid"
"uuid": "dist/esm/bin/uuid"
}
},
"node_modules/vite": {
+10 -1
View File
@@ -1,7 +1,7 @@
{
"name": "bookmarkmagic",
"private": true,
"version": "0.1.0",
"version": "1.0.0",
"type": "module",
"description": "Import, export & edit bookmarks between browsers — offline, no account, no cloud.",
"license": "GPL-3.0-or-later",
@@ -28,6 +28,7 @@
"lint:fix": "biome check --write .",
"knip": "knip",
"guard": "node scripts/guard.mjs",
"check:manifest": "node scripts/check-manifest.mjs",
"icons": "node scripts/gen-icons.mjs",
"test": "vitest run",
"test:watch": "vitest",
@@ -46,5 +47,13 @@
"typescript": "~6.0.3",
"vitest": "^4.1.10",
"wxt": "^0.20.27"
},
"overrides": {
"shell-quote": "^1.9.0",
"adm-zip": "^0.6.0",
"tmp": "^0.2.6",
"uuid": "^11.1.1",
"esbuild": "^0.28.1",
"brace-expansion": "^5.0.8"
}
}
+74
View File
@@ -0,0 +1,74 @@
/**
* Assert the BUILT manifest — CLAUDE.md hard rule 1, docs/08 §2.
*
* The unit test in `tests/unit/manifest.test.ts` reads `wxt.config.ts`, which
* proves what we ASKED for. It cannot prove what WXT emitted. Those differ:
* a dev build of this exact config produces
* "permissions": ["bookmarks","storage","tabs","scripting"]
* "host_permissions": ["http://localhost/*"]
* because WXT injects them for its dev server. Production is clean today, but
* that is a property of WXT's dev/prod branch, not of anything this repo
* enforces — so the shipped artifact needs its own gate.
*
* Run after `npm run build` (or `npm run zip`). Zero dependencies, Node stdlib.
*/
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
const MANIFEST = join(process.cwd(), '.output', 'chrome-mv3', 'manifest.json');
/** Exactly this, in any order. Adding one is a minor-version event (docs/09 §4). */
const ALLOWED_PERMISSIONS = ['bookmarks', 'storage'];
/** Keys that would widen the extension's reach. None may be present. */
const FORBIDDEN_KEYS = [
'host_permissions',
'optional_permissions',
'optional_host_permissions',
'content_scripts',
'background',
'web_accessible_resources',
'externally_connectable',
'declarative_net_request',
'devtools_page',
'chrome_url_overrides',
];
let manifest;
try {
manifest = JSON.parse(readFileSync(MANIFEST, 'utf8'));
} catch (cause) {
console.error(`check-manifest: cannot read ${MANIFEST} — run \`npm run build\` first.`);
console.error(` ${cause.message}`);
process.exit(1);
}
const problems = [];
if (manifest.manifest_version !== 3) {
problems.push(`manifest_version is ${manifest.manifest_version}, expected 3`);
}
const permissions = [...(manifest.permissions ?? [])].sort();
if (permissions.join(',') !== [...ALLOWED_PERMISSIONS].sort().join(',')) {
problems.push(
`permissions are ${JSON.stringify(manifest.permissions)}, expected ${JSON.stringify(ALLOWED_PERMISSIONS)}`,
);
}
for (const key of FORBIDDEN_KEYS) {
if (key in manifest) problems.push(`declares "${key}": ${JSON.stringify(manifest[key])}`);
}
if (problems.length > 0) {
for (const problem of problems) {
console.error(`::error::check-manifest: ${problem}`);
console.error(` ${problem}`);
}
console.error('\nSee CLAUDE.md hard rule 1 and docs/09 §4 before changing this.');
process.exit(1);
}
console.warn(
`check-manifest: clean — MV3, permissions ${JSON.stringify(manifest.permissions)}, no reach-widening keys.`,
);
+109 -15
View File
@@ -1,16 +1,38 @@
<script lang="ts">
import { onMount } from 'svelte';
import { getAppVersion } from '@/lib/browser/app-info';
import AboutTab from '@/lib/components/AboutTab.svelte';
import EditTab from '@/lib/components/EditTab.svelte';
import ExportTab from '@/lib/components/ExportTab.svelte';
import ImportTab from '@/lib/components/ImportTab.svelte';
import LanguageSwitcher from '@/lib/components/LanguageSwitcher.svelte';
import LegalGate from '@/lib/components/LegalGate.svelte';
import SettingsTab from '@/lib/components/SettingsTab.svelte';
import TabBar from '@/lib/components/TabBar.svelte';
import ThemeToggle from '@/lib/components/ThemeToggle.svelte';
import Toast from '@/lib/components/Toast.svelte';
import { t } from '@/lib/i18n/index.svelte';
import { isWriting } from '@/lib/stores/import-session.svelte';
import { REPO_URL } from '@/lib/links';
import {
getBlockedRoutes,
getLegalStatus,
isGatedRoute,
isGateRequired,
} from '@/lib/stores/legal.svelte';
import { getRoute, navigate, startRouting } from '@/lib/stores/route.svelte';
import { loadSettings } from '@/lib/stores/settings.svelte';
import { flushSettings, getSettings, updateSettings } from '@/lib/stores/settings.svelte';
import { pushToast } from '@/lib/stores/toast.svelte';
// Settings are loaded and awaited in main.ts, before this ever mounts.
const settings = $derived(getSettings());
const version = getAppVersion();
const legal = $derived(getLegalStatus());
const gated = $derived(isGateRequired() && isGatedRoute(getRoute()));
let mainEl: HTMLElement | undefined = $state();
onMount(() => {
void loadSettings();
const stopRouting = startRouting();
// Leaving mid-write would kill the queue with the tab (docs/03 §5).
@@ -18,13 +40,37 @@
if (!isWriting()) return;
event.preventDefault();
};
// Fires on tab close, navigation and backgrounding — unlike beforeunload it
// cannot be cancelled, so it is the right place to shorten the 200 ms
// window in which a just-changed setting is still unwritten.
const onVisibilityChange = (): void => {
if (globalThis.document?.visibilityState === 'hidden') void flushSettings();
};
globalThis.addEventListener('beforeunload', onBeforeUnload);
globalThis.document?.addEventListener('visibilitychange', onVisibilityChange);
return () => {
stopRouting();
globalThis.removeEventListener('beforeunload', onBeforeUnload);
globalThis.document?.removeEventListener('visibilitychange', onVisibilityChange);
};
});
/**
* Shared by the header controls so a silent failure there is impossible.
*
* The toast carries the LOCALIZED sentence, never the raw browser error —
* `detail` is essentially always present for a storage rejection, so putting
* it first made every translation of settings.saveFailed unreachable. The
* header has no room for a detail block; #settings shows one.
*/
function save(patch: Parameters<typeof updateSettings>[0]): void {
void updateSettings(patch).then((outcome) => {
pushToast(t(outcome.ok ? 'settings.saved' : 'settings.saveFailed'), outcome.ok ? 'success' : 'danger');
});
}
</script>
<header>
@@ -32,30 +78,71 @@
<span class="mark" aria-hidden="true">◆</span>
<strong>{t('common.appName')}</strong>
</div>
<TabBar />
<TabBar blocked={getBlockedRoutes()} />
<div class="controls">
<LanguageSwitcher compact value={settings.locale} onchange={(locale) => save({ locale })} />
<ThemeToggle compact value={settings.theme} onchange={(theme) => save({ theme })} />
</div>
</header>
<main>
{#if getRoute() === 'import'}
<main bind:this={mainEl} tabindex="-1">
{#if gated && legal.kind === 'required'}
<!-- Fills the content region rather than covering the viewport. docs/06 §3
calls it "a full overlay", but docs/14 §2 (echoed in docs/03 §4 and the
docs/15 log) requires #settings and #about to stay reachable while it
is up — a literal inset:0 scrim would bury the footer links that get
you there. Header and footer stay live; the three blocked tabs are
disabled via TabBar's `blocked`.
Side effect worth keeping: the Import/Export/Edit tabs never mount
before acceptance, so nothing touches chrome.bookmarks until the user
has agreed to the terms. -->
<LegalGate status={legal} onaccepted={() => mainEl?.focus()} />
{:else if getRoute() === 'import'}
<ImportTab />
{:else if getRoute() === 'export'}
<ExportTab />
{:else if getRoute() === 'edit'}
<EditTab />
{:else if getRoute() === 'settings'}
<SettingsTab />
{:else}
<!-- Phases 3-4 fill these in; the routes exist now so the shell is real. -->
<p class="placeholder">{t('common.comingSoon', { tab: t(`common.${getRoute()}`) })}</p>
<AboutTab />
{/if}
</main>
<footer>
<span>v0.1.0 · GPL-3.0</span>
<span>
<!-- Separators are `{' · '}` expressions, not literal text. Svelte trims
trailing whitespace at an {#if} boundary, which rendered the footer as
"v0.1.0 ·GPL-3.0". An expression is never trimmed. -->
{#if version !== ''}v{version}{' · '}{/if}GPL-3.0{' · '}<a
href={REPO_URL}
target="_blank"
rel="noopener noreferrer">GitHub ↗</a
>
</span>
<nav>
<button onclick={() => navigate('settings')}>{t('common.settings')}</button>
<button onclick={() => navigate('about')}>{t('common.about')}</button>
<!-- Gated like TabBar's tabs: navigating away mid-write unmounts ImportTab
and strands the attestation resolver, deadlocking the import
(docs/03 §5). The footer used to be the one way around that. -->
<button
disabled={isWriting()}
title={isWriting() ? t('common.busy') : undefined}
onclick={() => navigate('settings')}>{t('common.settings')}</button
>
<button
disabled={isWriting()}
title={isWriting() ? t('common.busy') : undefined}
onclick={() => navigate('about')}>{t('common.about')}</button
>
</nav>
</footer>
<!-- Mounted once, outside <main>, so the route chain below cannot unmount it
mid-dismiss and strand a timer (docs/06 §4). -->
<Toast />
<style>
header,
footer {
@@ -84,6 +171,12 @@
gap: var(--sp-2);
}
.controls {
display: flex;
align-items: center;
gap: var(--sp-2);
}
.mark {
color: var(--accent);
}
@@ -95,10 +188,6 @@
min-height: 60vh;
}
.placeholder {
color: var(--fg-muted);
}
footer nav {
display: flex;
gap: var(--sp-3);
@@ -113,7 +202,12 @@
padding: 0;
}
footer button:hover {
footer button:hover:not(:disabled) {
color: var(--accent);
}
footer button:disabled {
opacity: 0.4;
cursor: not-allowed;
}
</style>
+15 -7
View File
@@ -1,16 +1,24 @@
import { mount } from 'svelte';
import { browser } from 'wxt/browser';
import { setLocale } from '@/lib/i18n/index.svelte';
import { resolveLocale } from '@/lib/i18n/resolve-locale';
import { loadLegal } from '@/lib/stores/legal.svelte';
import { loadSettings } from '@/lib/stores/settings.svelte';
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;
// Both reads happen BEFORE the first render, on purpose. The alternative --
// mount, then hydrate -- paints one frame in the browser's UI language and the
// system theme, then flips to the persisted ones, and flashes the legal gate at
// users who accepted it long ago. Awaiting means that frame holds an empty #app
// instead: a blank moment rather than visible EN->VI, light->dark or gate
// flicker.
//
// Neither loader can throw: readSettings and readLegal both swallow storage
// failures (browser/storage.ts) and applyLocale guards the i18n lookup. No
// timeout race either — storage.local.get always settles, and racing it would
// just re-introduce the wrong-locale render this exists to prevent.
await Promise.all([loadSettings(), loadLegal()]);
export default mount(App, { target });
+44 -6
View File
@@ -1,14 +1,15 @@
<script lang="ts">
import { onMount } from 'svelte';
import { getAppVersion } from '@/lib/browser/app-info';
import { getRootChildren } from '@/lib/browser/bookmarks';
import { openManager } from '@/lib/browser/open-manager';
import { t } from '@/lib/i18n/index.svelte';
import { loadSettings } from '@/lib/stores/settings.svelte';
import { num, t } from '@/lib/i18n/index.svelte';
let counts = $state<{ bookmarks: number; folders: number } | undefined>();
const version = getAppVersion();
// Settings are loaded and awaited in main.ts, before this ever mounts.
onMount(() => {
void loadSettings();
void countTree();
});
@@ -39,6 +40,7 @@
<header>
<span class="mark" aria-hidden="true">◆</span>
<strong>{t('common.appName')}</strong>
{#if version !== ''}<span class="version">v{version}</span>{/if}
</header>
<div class="actions">
@@ -48,9 +50,19 @@
</div>
<footer>
{#if counts !== undefined}
{t('popup.counts', { bookmarks: counts.bookmarks, folders: counts.folders })}
{/if}
<span>
{#if counts !== undefined}
{t('popup.counts', { bookmarks: num(counts.bookmarks), folders: num(counts.folders) })}
{/if}
</span>
<button
class="settings"
aria-label={t('common.settings')}
title={t('common.settings')}
onclick={() => void openManager('#settings')}
>
⚙
</button>
</footer>
</main>
@@ -95,10 +107,36 @@
}
footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--sp-2);
padding-top: var(--sp-2);
border-top: 1px solid var(--border);
color: var(--fg-muted);
font-size: var(--fs-0);
min-height: 1.5em;
}
.version {
margin-left: auto;
color: var(--fg-muted);
font-size: var(--fs-0);
font-variant-numeric: tabular-nums;
}
.settings {
font: inherit;
flex-shrink: 0;
padding: 0 var(--sp-1);
border: none;
background: none;
color: var(--fg-muted);
cursor: pointer;
font-size: var(--fs-2);
}
.settings:hover {
color: var(--accent);
}
</style>
+6 -7
View File
@@ -1,16 +1,15 @@
import { mount } from 'svelte';
import { browser } from 'wxt/browser';
import { setLocale } from '@/lib/i18n/index.svelte';
import { resolveLocale } from '@/lib/i18n/resolve-locale';
import { loadSettings } from '@/lib/stores/settings.svelte';
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;
// Awaited before mount for the same reason as the Manager: the popup is small
// and fast, so a locale or theme flip here is proportionally more visible.
// The popup is never gated (docs/14 §2), so there is no legal read to make.
await loadSettings();
export default mount(App, { target });
+39
View File
@@ -0,0 +1,39 @@
/**
* Runtime metadata about the built extension.
*
* Purpose: the ONE place the displayed version comes from (docs/06 §3.5). It
* used to be hardcoded in three files, which is three chances to ship a
* number that disagrees with the manifest.
* Inputs: none — reads the packaged manifest.
* Guarantees: synchronous, so there is no version race and no loading state;
* never throws.
*/
import { browser } from 'wxt/browser';
/**
* The manifest version, or `''` when it cannot be read.
*
* Empty rather than a plausible fallback like `'0.0.0'`: callers hide the line
* entirely, and no version at all is better than a wrong one in a footer users
* quote in bug reports.
*/
export function getAppVersion(): string {
try {
return browser.runtime.getManifest().version;
} catch {
return '';
}
}
/**
* The `generator` string written into exported and backup BM JSON.
*
* Separate from `getAppVersion` because the UI and a file want different
* fallbacks: the UI hides an unknown version, but a file field cannot be
* hidden, and `"BookmarkMagic "` with a trailing space is a worse artifact
* than the bare product name.
*/
export function getGeneratorVersion(): string {
const version = getAppVersion();
return version === '' ? 'unknown' : version;
}
+23
View File
@@ -0,0 +1,23 @@
/**
* Copying a bookmark's URL — the docs/09 T8 surface.
*
* Purpose: the only place this extension touches the clipboard.
* Inputs: a URL string, from an explicit user click.
* Guarantees: **write only**. Nothing here ever reads the clipboard, and the
* write is never triggered by anything but a click, so no permission is
* needed — `clipboard-write` is granted to a transient user activation.
* Never throws; returns whether the copy landed.
*/
export async function copyToClipboard(text: string): Promise<boolean> {
const clipboard = globalThis.navigator?.clipboard;
// Absent in a non-secure context and in jsdom. A missing clipboard is a
// "could not copy", not a crash.
if (clipboard === undefined) return false;
try {
await clipboard.writeText(text);
return true;
} catch {
return false;
}
}
+54
View File
@@ -0,0 +1,54 @@
/**
* Opening a bookmarked URL — the docs/09 T3 control.
*
* Purpose: the single gate between a URL that came out of someone's import file
* and the browser actually navigating to it.
* Inputs: a URL string from untrusted file data.
* Guarantees: only `http:` and `https:` ever reach `tabs.create`. Nothing is
* opened for an unparseable URL, and nothing throws.
*/
import { browser } from 'wxt/browser';
/** Schemes allowed to reach the browser. Everything else is display-only. */
const ALLOWED_SCHEMES = new Set(['http:', 'https:']);
/**
* Whether this URL would be refused — so the row can warn BEFORE the click.
*
* docs/09 T3 asks for both halves: block the navigation, and mark the bookmark
* so a `javascript:` entry titled "Your bank" does not look like an ordinary
* link that simply does nothing.
*/
export function isBlockedUrl(url: string | undefined): boolean {
if (url === undefined) return false;
try {
return !ALLOWED_SCHEMES.has(new URL(url).protocol);
} catch {
return true;
}
}
/**
* Open `url` in a new tab if its scheme is allowed.
*
* Returns whether it was opened, so callers and tests can tell "blocked" from
* "opened" rather than inferring it.
*
* Chromium also refuses `javascript:` from `tabs.create`, but this allowlist is
* the authoritative control: it is ours, it is testable, and it does not move
* when a browser changes its mind. `data:`, `file:` and `chrome:` are blocked
* here even though some are navigable, because a bookmark file is untrusted
* input and none of them are worth the surface.
*/
export async function openBookmarkUrl(url: string): Promise<boolean> {
let scheme: string;
try {
scheme = new URL(url).protocol;
} catch {
return false;
}
if (!ALLOWED_SCHEMES.has(scheme)) return false;
await browser.tabs.create({ url });
return true;
}
+128
View File
@@ -0,0 +1,128 @@
<script lang="ts">
import { getAppVersion } from '../browser/app-info';
import { dateTime, t } from '../i18n/index.svelte';
import { CHANGELOG_URL, DONATE_LINKS, ISSUES_URL, LEGAL_URLS, REPO_URL } from '../links';
import { getAcceptance } from '../stores/legal.svelte';
const version = getAppVersion();
const acceptance = $derived(getAcceptance());
// undefined when acceptedAt is missing or unparseable — storage coerces a
// missing timestamp to '', and formatting that would throw inside the render.
const acceptedOn = $derived(
acceptance === undefined ? undefined : dateTime(acceptance.acceptedAt),
);
</script>
<section aria-label={t('common.about')}>
<header>
<img src="/icon/48.png" alt="" width="48" height="48" />
<div>
<strong>{t('common.appName')}</strong>
{#if version !== ''}<span class="version">{t('about.version', { version })}</span>{/if}
</div>
</header>
<p class="tagline">{t('about.tagline')}</p>
<h2>{t('about.links')}</h2>
<ul class="links">
<li><a href={REPO_URL} target="_blank" rel="noopener noreferrer">{t('about.repo')} ↗</a></li>
<li><a href={ISSUES_URL} target="_blank" rel="noopener noreferrer">{t('about.issues')} ↗</a></li>
<li>
<a href={CHANGELOG_URL} target="_blank" rel="noopener noreferrer">
{t('about.changelog')} ↗
</a>
</li>
</ul>
<h2>{t('about.thirdParty')}</h2>
<p class="muted">{t('about.thirdPartyNote')}</p>
<h2>{t('about.donate')}</h2>
<p class="muted">{t('about.donateNote')}</p>
<ul class="links">
{#each DONATE_LINKS as link (link.url)}
<li><a href={link.url} target="_blank" rel="noopener noreferrer">{link.label} ↗</a></li>
{/each}
</ul>
<h2>{t('about.legal')}</h2>
<ul class="links">
{#each LEGAL_URLS as link (link.url)}
<li>
<a href={link.url} target="_blank" rel="noopener noreferrer">{t(link.labelKey)} ↗</a>
</li>
{/each}
</ul>
<p class="muted">{t('legal.englishNote')}</p>
<p class="muted">
<!-- The version the user ACCEPTED, not LEGAL_VERSION: if they differ the
gate is up anyway, and showing the current constant here would claim
consent that was never given (docs/06 §3.5). -->
{#if acceptance === undefined}
{t('about.notAccepted')}
{:else if acceptedOn === undefined}
{t('about.acceptedUndated', { version: acceptance.acceptedVersion })}
{:else}
{t('about.accepted', {
date: acceptedOn,
version: acceptance.acceptedVersion,
})}
{/if}
</p>
</section>
<style>
section {
max-width: 640px;
}
header {
display: flex;
align-items: center;
gap: var(--sp-3);
padding-bottom: var(--sp-3);
border-bottom: 1px solid var(--border);
}
header div {
display: flex;
flex-direction: column;
}
header strong {
font-size: var(--fs-3);
}
.version {
font-size: var(--fs-0);
color: var(--fg-muted);
font-variant-numeric: tabular-nums;
}
.tagline {
color: var(--fg-muted);
font-size: var(--fs-1);
}
h2 {
margin: var(--sp-5) 0 var(--sp-2);
font-size: var(--fs-2);
}
.muted {
margin: 0;
color: var(--fg-muted);
font-size: var(--fs-1);
}
.links {
display: flex;
flex-wrap: wrap;
gap: var(--sp-2) var(--sp-4);
margin: var(--sp-2) 0 0;
padding: 0;
list-style: none;
font-size: var(--fs-1);
}
</style>
+3 -1
View File
@@ -44,6 +44,8 @@
.danger {
background: var(--danger);
border-color: var(--danger);
color: #fff;
/* Not #fff: dark mode lightens --danger, where white ink measures 2.74:1
against the 4.5:1 docs/06 §5 requires. */
color: var(--danger-fg);
}
</style>
+1 -1
View File
@@ -77,6 +77,6 @@
.danger {
background: var(--danger);
border-color: var(--danger);
color: #fff;
color: var(--danger-fg);
}
</style>
+3 -3
View File
@@ -1,7 +1,7 @@
<script lang="ts">
import type { DuplicateGroup } from '../core/dedupe';
import type { EditNode } from '../edit/patch-tree';
import { t } from '../i18n/index.svelte';
import { num, t } from '../i18n/index.svelte';
import Button from './Button.svelte';
interface Props {
@@ -18,14 +18,14 @@
<aside aria-label={t('edit.duplicates')}>
<header>
<strong>{t('edit.duplicatesFound', { groups: groups.length, extra })}</strong>
<strong>{t('edit.duplicatesFound', { groups: num(groups.length), extra: num(extra) })}</strong>
<button class="close" aria-label={t('common.cancel')} onclick={onclose}>✕</button>
</header>
{#if groups.length === 0}
<p class="muted">{t('edit.noDuplicates')}</p>
{:else}
<Button variant="danger" onclick={onkeepFirst}>{t('edit.keepFirst', { n: extra })}</Button>
<Button variant="danger" onclick={onkeepFirst}>{t('edit.keepFirst', { n: num(extra) })}</Button>
<ul>
{#each groups as group (group.key)}
+56 -164
View File
@@ -1,19 +1,27 @@
<script lang="ts">
import { onMount } from 'svelte';
import { browser } from 'wxt/browser';
import {
create,
getRootChildren,
type LiveNode,
move,
remove,
removeTree,
subscribe,
update,
} from '../browser/bookmarks';
import { copyToClipboard } from '../browser/clipboard';
import { BmBrowserError } from '../browser/errors';
import { openBookmarkUrl } from '../browser/open-url';
import { findDuplicateGroups } from '../core/dedupe';
import { searchTree } from '../core/search';
import {
countDescendants,
extraCopyIds,
flattenTree,
isEditable as canEdit,
resolveNewFolderParent,
toEditNode,
} from '../edit/edit-node';
import {
changeNode,
type EditNode,
@@ -24,11 +32,13 @@
} from '../edit/patch-tree';
import { canMoveInto, moveTargets } from '../edit/move-target';
import { resolveKey, visibleRows } from '../edit/tree-keyboard';
import { t } from '../i18n/index.svelte';
import Button from './Button.svelte';
import { num, t } from '../i18n/index.svelte';
import { pushToast } from '../stores/toast.svelte';
import Callout from './Callout.svelte';
import ConfirmDialog from './ConfirmDialog.svelte';
import DuplicatePanel from './DuplicatePanel.svelte';
import EditToolbar from './EditToolbar.svelte';
import MoveToDialog from './MoveToDialog.svelte';
import TreeRow from './TreeRow.svelte';
let roots = $state<EditNode[]>([]);
@@ -78,16 +88,8 @@
};
});
function toEditNode(node: LiveNode): EditNode {
return {
id: node.id,
...(node.parentId !== undefined && { parentId: node.parentId }),
title: node.title,
...(node.url !== undefined && { url: node.url }),
...(node.url === undefined && { children: (node.children ?? []).map(toEditNode) }),
...(node.unmodifiable !== undefined && { unmodifiable: node.unmodifiable }),
};
}
/** Bound to the current tree, so callers pass only the node. */
const isEditable = (node: EditNode): boolean => canEdit(roots, node);
async function load(): Promise<void> {
try {
@@ -121,27 +123,9 @@
const rows = $derived(visibleRows(roots, expanded, filtering ? search.visible : undefined));
const duplicateGroups = $derived(
findDuplicateGroups(flatten(roots).filter((node) => node.url !== undefined)),
findDuplicateGroups(flattenTree(roots).filter((node) => node.url !== undefined)),
);
function flatten(nodes: readonly EditNode[], into: EditNode[] = []): EditNode[] {
for (const node of nodes) {
into.push(node);
flatten(node.children ?? [], into);
}
return into;
}
/**
* Permanent roots and policy-managed nodes reject every write, so the UI must
* not offer the affordance at all — optimistically mutating first and finding
* out on rejection is how the tree ends up disagreeing with the browser.
*/
function isEditable(node: EditNode): boolean {
if (node.unmodifiable !== undefined) return false;
return !roots.some((root) => root.id === node.id);
}
/**
* Run a mutation, and on failure resync from the browser — the only source of
* truth. A snapshot restore would resurrect rows that earlier iterations of a
@@ -207,19 +191,22 @@
}
/**
* Only http(s) reach the browser. `javascript:` and `data:` are display-only
* (docs/09 T3) — Chromium also rejects them, but the app-side allowlist is
* the authoritative control.
* Open a bookmark, saying so when the scheme is refused.
*
* The boolean was previously discarded with `void`, so clicking ↗ on a
* `javascript:` bookmark did nothing at all and looked like a broken button
* rather than a deliberate refusal (docs/09 T3).
*/
async function openUrl(url: string): Promise<void> {
let scheme = '';
try {
scheme = new URL(url).protocol;
} catch {
return;
}
if (scheme !== 'http:' && scheme !== 'https:') return;
await browser.tabs.create({ url });
if (url === '') return;
if (!(await openBookmarkUrl(url))) pushToast(t('edit.unsafeUrl'), 'danger');
}
/** docs/06 §3.3's "Copy URL". Write-only, on an explicit click (docs/09 T8). */
async function copyUrl(url: string): Promise<void> {
if (url === '') return;
const copied = await copyToClipboard(url);
pushToast(t(copied ? 'edit.copied' : 'edit.copyFailed'), copied ? 'success' : 'danger');
}
async function commitRename(id: string, title: string): Promise<void> {
@@ -246,17 +233,7 @@
}
async function newFolder(): Promise<void> {
// Into the focused FOLDER, or alongside the focused bookmark. Using the
// focused node's parent unconditionally meant selecting a root resolved to
// the synthetic root "0", which every create rejects.
const focused = findNode(roots, focusedId ?? '');
const writableRoot = roots.find((root) => root.unmodifiable === undefined)?.id;
const parentId =
focused === undefined
? writableRoot
: focused.url === undefined
? focused.id
: (focused.parentId ?? writableRoot);
const parentId = resolveNewFolderParent(roots, findNode(roots, focusedId ?? ''));
if (parentId === undefined) return;
await guardEdit(async () => {
@@ -273,7 +250,7 @@
pendingKeepFirst = false;
// Snapshot the ids first: duplicateGroups is $derived from `roots`, so
// reading it inside the loop would recompute mid-iteration.
const doomed = duplicateGroups.flatMap((group) => group.nodes.slice(1).map((n) => n.id));
const doomed = extraCopyIds(duplicateGroups);
await guardEdit(async () => {
for (const id of doomed) {
roots = removeNode(roots, id);
@@ -319,30 +296,21 @@
searchInput?.select();
}
const descendantCount = $derived(
pendingDelete === undefined ? 0 : flatten(pendingDelete.children ?? []).length,
);
const descendantCount = $derived(countDescendants(pendingDelete));
</script>
{#if loadError !== undefined}
<Callout tone="danger">{loadError}</Callout>
{:else}
<div class="toolbar">
<input
bind:this={searchInput}
type="search"
placeholder={t('edit.search')}
aria-label={t('edit.search')}
value={query}
oninput={(e) => onQuery((e.currentTarget as HTMLInputElement).value)}
/>
<Button onclick={() => void newFolder()}>{t('edit.newFolder')}</Button>
<Button onclick={() => (showDuplicates = !showDuplicates)}>{t('edit.findDuplicates')}</Button>
<Button onclick={() => (expanded = new Set(flatten(roots).map((n) => n.id)))}
>{t('edit.expandAll')}</Button
>
<Button onclick={() => (expanded = new Set())}>{t('edit.collapseAll')}</Button>
</div>
<EditToolbar
bind:input={searchInput}
{query}
onquery={onQuery}
onnewFolder={() => void newFolder()}
ontoggleDuplicates={() => (showDuplicates = !showDuplicates)}
onexpandAll={() => (expanded = new Set(flattenTree(roots).map((node) => node.id)))}
oncollapseAll={() => (expanded = new Set())}
/>
{#if actionError !== undefined}
<div class="action-error">
@@ -388,6 +356,7 @@
oncancelRename={() => (renamingId = undefined)}
ondelete={() => (pendingDelete = row.node)}
onopen={() => void openUrl(row.node.url ?? '')}
oncopyUrl={() => void copyUrl(row.node.url ?? '')}
onmoveTo={() => (movingNode = row.node)}
ondragstart={() => (draggingId = row.node.id)}
ondropinto={() => onDrop(row.node.id)}
@@ -416,26 +385,16 @@
{/if}
{#if movingNode !== undefined}
<div class="move-to" role="dialog" aria-label={t('edit.moveTo')}>
<p>{t('edit.moveToBody', { title: movingNode.title })}</p>
<ul>
{#each targets as target (target.id)}
<li>
<button
onclick={() => {
const id = movingNode?.id;
movingNode = undefined;
if (id !== undefined) void moveInto(id, target.id);
}}>{target.label}</button
>
</li>
{/each}
{#if targets.length === 0}
<li class="muted">{t('edit.noMoveTargets')}</li>
{/if}
</ul>
<Button onclick={() => (movingNode = undefined)}>{t('common.cancel')}</Button>
</div>
<MoveToDialog
node={movingNode}
{targets}
onpick={(parentId) => {
const id = movingNode?.id;
movingNode = undefined;
if (id !== undefined) void moveInto(id, parentId);
}}
oncancel={() => (movingNode = undefined)}
/>
{/if}
<ConfirmDialog
@@ -443,7 +402,7 @@
danger
title={t('edit.deleteTitle')}
body={descendantCount > 0
? t('edit.deleteFolderBody', { title: pendingDelete?.title ?? '', n: descendantCount })
? t('edit.deleteFolderBody', { title: pendingDelete?.title ?? '', n: num(descendantCount) })
: t('edit.deleteBody', { title: pendingDelete?.title ?? '' })}
confirmLabel={t('edit.delete')}
cancelLabel={t('common.cancel')}
@@ -456,7 +415,7 @@
danger
title={t('edit.keepFirstTitle')}
body={t('edit.keepFirstBody', {
n: duplicateGroups.reduce((n, g) => n + g.nodes.length - 1, 0),
n: num(duplicateGroups.reduce((n, g) => n + g.nodes.length - 1, 0)),
})}
confirmLabel={t('edit.delete')}
cancelLabel={t('common.cancel')}
@@ -465,24 +424,6 @@
/>
<style>
.toolbar {
display: flex;
flex-wrap: wrap;
gap: var(--sp-2);
margin-bottom: var(--sp-3);
}
.toolbar input {
font: inherit;
flex: 1;
min-width: 12ch;
padding: var(--sp-2) var(--sp-3);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
background: var(--bg);
color: var(--fg);
}
.split {
display: grid;
grid-template-columns: 1fr;
@@ -537,53 +478,4 @@
text-align: center;
}
.move-to {
position: fixed;
inset-block-end: var(--sp-4);
inset-inline-end: var(--sp-4);
width: min(360px, calc(100vw - var(--sp-6)));
max-height: 60vh;
overflow: auto;
background: var(--bg);
border: 1px solid var(--accent);
border-radius: var(--radius);
padding: var(--sp-3);
box-shadow: 0 8px 32px rgb(0 0 0 / 0.25);
}
.move-to p {
margin: 0 0 var(--sp-2);
font-size: var(--fs-1);
color: var(--fg-muted);
}
.move-to ul {
list-style: none;
margin: 0 0 var(--sp-3);
padding: 0;
display: flex;
flex-direction: column;
gap: 2px;
}
.move-to button {
font: inherit;
width: 100%;
text-align: left;
background: none;
border: none;
border-radius: var(--radius-sm);
color: var(--fg);
cursor: pointer;
padding: var(--sp-1) var(--sp-2);
}
.move-to button:hover {
background: var(--bg-raised);
}
.muted {
color: var(--fg-muted);
font-size: var(--fs-1);
}
</style>
+61
View File
@@ -0,0 +1,61 @@
<script lang="ts">
import { t } from '../i18n/index.svelte';
import Button from './Button.svelte';
interface Props {
query: string;
/** Bound out so ⌘/Ctrl-F can focus it from the tab's window handler. */
input?: HTMLInputElement | undefined;
onquery: (value: string) => void;
onnewFolder: () => void;
ontoggleDuplicates: () => void;
onexpandAll: () => void;
oncollapseAll: () => void;
}
let {
query,
input = $bindable(),
onquery,
onnewFolder,
ontoggleDuplicates,
onexpandAll,
oncollapseAll,
}: Props = $props();
</script>
<div class="toolbar">
<input
bind:this={input}
type="search"
placeholder={t('edit.search')}
aria-label={t('edit.search')}
value={query}
oninput={(event) => onquery(event.currentTarget.value)}
/>
<Button onclick={onnewFolder}>{t('edit.newFolder')}</Button>
<Button onclick={ontoggleDuplicates}>{t('edit.findDuplicates')}</Button>
<Button onclick={onexpandAll}>{t('edit.expandAll')}</Button>
<Button onclick={oncollapseAll}>{t('edit.collapseAll')}</Button>
</div>
<style>
/* Copied verbatim from EditTab — this is a move, not a redesign. */
.toolbar {
display: flex;
flex-wrap: wrap;
gap: var(--sp-2);
margin-bottom: var(--sp-3);
}
.toolbar input {
font: inherit;
flex: 1;
min-width: 12ch;
padding: var(--sp-2) var(--sp-3);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
background: var(--bg);
color: var(--fg);
}
</style>
+26 -20
View File
@@ -6,8 +6,14 @@
import type { CsvDelimiter } from '../core/serialize/csv';
import type { MarkdownStyle } from '../core/serialize/markdown';
import { countSelected, FORMAT_META, runExport } from '../export/run-export';
import { t } from '../i18n/index.svelte';
import { num, t } from '../i18n/index.svelte';
import {
CSV_DELIMITER_CHOICES,
MARKDOWN_STYLE_CHOICES,
parseChoice,
} from '../settings/options';
import { getSettings } from '../stores/settings.svelte';
import { pushToast } from '../stores/toast.svelte';
import Button from './Button.svelte';
import Callout from './Callout.svelte';
import FolderPickTree from './FolderPickTree.svelte';
@@ -17,7 +23,6 @@
let selection = $state<ReadonlySet<string> | undefined>(undefined);
let format = $state<ExportFormat>('netscape-html');
let loadError = $state<string | undefined>();
let toast = $state<string | undefined>();
let csvDelimiter = $state<CsvDelimiter>(',');
let markdownStyle = $state<MarkdownStyle>('nested');
@@ -55,9 +60,11 @@
markdownStyle,
now: new Date(),
});
toast = t('export.saved', { name: result.filename });
pushToast(t('export.saved', { name: result.filename }), 'success');
} catch (err) {
toast = err instanceof BmBrowserError ? err.detail : t('errors.UNKNOWN');
// Tone matters: this used to share a variable with the success message
// and rendered failures in success-green.
pushToast(err instanceof BmBrowserError ? err.detail : t('errors.UNKNOWN'), 'danger');
}
})();
}
@@ -83,10 +90,14 @@
<span>{t('export.csvDelimiter')}</span>
<select
value={csvDelimiter}
onchange={(e) => (csvDelimiter = (e.currentTarget as HTMLSelectElement).value as CsvDelimiter)}
onchange={(e) => {
const next = parseChoice(e.currentTarget.value, CSV_DELIMITER_CHOICES);
if (next !== undefined) csvDelimiter = next;
}}
>
<option value=",">{t('export.comma')}</option>
<option value=";">{t('export.semicolon')}</option>
{#each CSV_DELIMITER_CHOICES as choice (choice.value)}
<option value={choice.value}>{t(choice.labelKey)}</option>
{/each}
</select>
</label>
{/if}
@@ -96,10 +107,14 @@
<span>{t('export.markdownStyle')}</span>
<select
value={markdownStyle}
onchange={(e) => (markdownStyle = (e.currentTarget as HTMLSelectElement).value as MarkdownStyle)}
onchange={(e) => {
const next = parseChoice(e.currentTarget.value, MARKDOWN_STYLE_CHOICES);
if (next !== undefined) markdownStyle = next;
}}
>
<option value="nested">{t('export.nested')}</option>
<option value="flat">{t('export.flat')}</option>
{#each MARKDOWN_STYLE_CHOICES as choice (choice.value)}
<option value={choice.value}>{t(choice.labelKey)}</option>
{/each}
</select>
</label>
{/if}
@@ -109,12 +124,9 @@
disabled={bookmarkCount === 0}
onclick={download}
>
{t('export.start', { n: bookmarkCount })}
{t('export.start', { n: num(bookmarkCount) })}
</Button>
{#if toast !== undefined}
<p class="toast" role="status">{toast}</p>
{/if}
</section>
</div>
{/if}
@@ -155,10 +167,4 @@
background: var(--bg);
color: var(--fg);
}
.toast {
margin: 0;
font-size: var(--fs-1);
color: var(--success);
}
</style>
+2 -2
View File
@@ -1,7 +1,7 @@
<script lang="ts">
import type { LiveNode } from '../browser/bookmarks';
import type { CheckState } from '../core/select';
import { t } from '../i18n/index.svelte';
import { num, t } from '../i18n/index.svelte';
import Self from './FolderPickNode.svelte';
interface Props {
@@ -53,7 +53,7 @@
onchange={(e) => ontoggle(node, (e.currentTarget as HTMLInputElement).checked)}
/>
<span class="title">{node.title}</span>
{#if bookmarks > 0}<span class="count">{bookmarks}</span>{/if}
{#if bookmarks > 0}<span class="count">{num(bookmarks)}</span>{/if}
</label>
</div>
+2 -2
View File
@@ -1,6 +1,6 @@
<script lang="ts">
import type { ImportMode } from '../browser/storage';
import { t } from '../i18n/index.svelte';
import { num, t } from '../i18n/index.svelte';
import Callout from './Callout.svelte';
interface Props {
@@ -46,7 +46,7 @@
disabled={mode === 'replace'}
onchange={(e) => onchange({ dedupe: (e.currentTarget as HTMLInputElement).checked })}
/>
<span>{t('import.dedupe', { n: duplicates })}</span>
<span>{t('import.dedupe', { n: num(duplicates) })}</span>
</label>
{#if mode === 'replace'}
+31 -15
View File
@@ -2,7 +2,7 @@
import { timestampSuffix } from '../browser/download';
import { BmAborted, BmBackupError, BmBrowserError } from '../browser/errors';
import { BmParseError } from '../core/model';
import { t } from '../i18n/index.svelte';
import { num, t } from '../i18n/index.svelte';
import { prepareImport, runImport } from '../import/run-import';
import { getSettings } from '../stores/settings.svelte';
import {
@@ -41,17 +41,26 @@
attestResolve = undefined;
}
function describeError(err: unknown): { message: string; detail: string | undefined } {
/**
* Map an error onto an i18n KEY plus a raw detail — never a resolved string.
* The session store outlives this component, and `t()` only re-runs where it
* is called, so a translated sentence stored here would never follow a
* language switch.
*/
function describeError(err: unknown): { messageKey: string; detail: string | undefined } {
if (err instanceof BmParseError) {
return { message: t(`errors.${err.code}`), detail: err.detail };
return { messageKey: `errors.${err.code}`, detail: err.detail };
}
if (err instanceof BmBackupError) {
return { message: t(`errors.${err.code}`), detail: err.message };
return { messageKey: `errors.${err.code}`, detail: err.message };
}
if (err instanceof BmBrowserError) {
return { message: t('errors.BROWSER'), detail: err.detail };
return { messageKey: 'errors.BROWSER', detail: err.detail };
}
return { message: t('errors.UNKNOWN'), detail: err instanceof Error ? err.message : undefined };
return {
messageKey: 'errors.UNKNOWN',
detail: err instanceof Error ? err.message : undefined,
};
}
async function onFile(file: File): Promise<void> {
@@ -122,7 +131,14 @@
}
}
/** ISO date + local time, matching the `import.folderName` key (docs/07 §3). */
/**
* ISO date + local time, matching the `import.folderName` key (docs/07 §3).
*
* Deliberately NOT run through Intl, unlike every count in this file: docs/07
* §3 pins the folder name to the localized *word* plus an ISO date
* (`Đã nhập 2026-07-03`). Localizing it here would change the names of
* bookmark folders this extension creates in the user's browser.
*/
function formatFolderDate(now: Date): string {
const pad = (n: number): string => String(n).padStart(2, '0');
return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}`;
@@ -136,7 +152,7 @@
<p class="muted">{t('import.reading', { name: session.filename })}</p>
{:else if session.kind === 'parsed'}
<div class="split">
<section aria-label="Preview">
<section aria-label={t('import.preview')}>
<TreePreview roots={session.result.roots} status={prepared?.status ?? new WeakMap()} />
</section>
<section class="side">
@@ -152,7 +168,7 @@
variant={options.mode === 'replace' ? 'danger' : 'primary'}
onclick={() => void start(session.filename)}
>
{t('import.start', { n: session.result.stats.bookmarks })}
{t('import.start', { n: num(session.result.stats.bookmarks) })}
</Button>
</section>
</div>
@@ -176,18 +192,18 @@
label={t('common.import')}
/>
<p class="muted">
{t('import.progress', { done: session.progress.done, total: session.progress.total })}
{t('import.progress', { done: num(session.progress.done), total: num(session.progress.total) })}
{#if session.progress.currentPath !== ''}<span class="path">{session.progress.currentPath}</span>{/if}
</p>
<Callout tone="warn">{t('import.keepTabOpen')}</Callout>
<Button onclick={cancelWrite}>{t('common.cancel')}</Button>
</div>
{:else if session.kind === 'done'}
<Callout tone="success">{t('import.doneSummary', { created: session.created })}</Callout>
<Callout tone="success">{t('import.doneSummary', { created: num(session.created) })}</Callout>
<p class="muted">
{t('import.skipped', {
existing: session.plan.stats.skippedExisting,
inFile: session.plan.stats.skippedInFile,
existing: num(session.plan.stats.skippedExisting),
inFile: num(session.plan.stats.skippedInFile),
})}
</p>
<div class="actions">
@@ -197,12 +213,12 @@
>
</div>
{:else if session.kind === 'cancelled'}
<Callout tone="warn">{t('import.cancelledSummary', { created: session.created })}</Callout>
<Callout tone="warn">{t('import.cancelledSummary', { created: num(session.created) })}</Callout>
<Button
onclick={resetImport}>{t('import.another')}</Button
>
{:else if session.kind === 'error'}
<Callout tone="danger">{session.message}</Callout>
<Callout tone="danger">{t(session.messageKey)}</Callout>
{#if session.detail !== undefined}
<pre class="detail">{session.detail}</pre>
{/if}
@@ -0,0 +1,70 @@
<script lang="ts">
import { t } from '../i18n/index.svelte';
import type { Locale } from '../i18n/resolve-locale';
import { LOCALE_CHOICES, parseChoice } from '../settings/options';
interface Props {
/**
* The stored *preference*, which includes `'auto'` — never `getLocale()`.
* Binding this to the resolved locale would make choosing "Automatic" snap
* the control straight to "English".
*/
value: Locale | 'auto';
onchange: (next: Locale | 'auto') => void;
/** Header variant: hides the visible label, keeps the accessible one. */
compact?: boolean;
}
let { value, onchange, compact = false }: Props = $props();
function select(raw: string): void {
const next = parseChoice(raw, LOCALE_CHOICES);
if (next === undefined) return;
onchange(next);
}
</script>
<label class:compact>
<span class="label">{t('settings.language')}</span>
<select
aria-label={compact ? t('settings.language') : undefined}
{value}
onchange={(event) => select(event.currentTarget.value)}
>
{#each LOCALE_CHOICES as choice (choice.value)}
<option value={choice.value}>{t(choice.labelKey)}</option>
{/each}
</select>
</label>
<style>
label {
display: flex;
align-items: center;
gap: var(--sp-2);
font-size: var(--fs-1);
}
.compact .label {
/* Visually hidden, still read aloud and still the select's accessible name. */
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
select {
font: inherit;
padding: var(--sp-1) var(--sp-2);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
background: var(--bg);
color: var(--fg);
}
select:hover {
border-color: var(--accent);
}
</style>
+201
View File
@@ -0,0 +1,201 @@
<script lang="ts">
import { t } from '../i18n/index.svelte';
import { LEGAL_URLS } from '../links';
import { acceptLegal, type LegalStatus } from '../stores/legal.svelte';
import Button from './Button.svelte';
import Callout from './Callout.svelte';
interface Props {
status: Extract<LegalStatus, { kind: 'required' }>;
/** Lets the shell move focus into the tab that mounts underneath. */
onaccepted: () => void;
}
let { status, onaccepted }: Props = $props();
/** How long to wait for `close()` before admitting it did nothing. */
const CLOSE_GRACE_MS = 150;
let checked = $state(false);
let saving = $state(false);
let saveFailed = $state(false);
let saveDetail = $state<string | undefined>();
let closeFailed = $state(false);
let heading: HTMLHeadingElement | undefined = $state();
let closeTimer: ReturnType<typeof setTimeout> | undefined;
// Replacing <main>'s content without moving focus leaves a screen-reader user
// reading the page they navigated away from (docs/06 §5).
$effect(() => {
heading?.focus();
return () => {
if (closeTimer !== undefined) clearTimeout(closeTimer);
};
});
function accept(): void {
if (!checked || saving) return;
saving = true;
saveFailed = false;
saveDetail = undefined;
// Timestamp taken at click time and passed down, so the store stays free of
// ambient time. Nothing is dismissed until the write resolves.
void acceptLegal(new Date().toISOString()).then((outcome) => {
saving = false;
if (outcome.ok) {
onaccepted();
return;
}
// The localized recovery sentence is the message; the raw browser error
// is the separate technical detail (docs/02 §7). Showing `detail` in its
// place made legal.saveFailed dead in all three locales — at the one
// moment a first-run user most needs an actionable instruction.
saveFailed = true;
saveDetail = outcome.detail;
});
}
/**
* Decline is "close the tab" (docs/14 §2) — nothing is written either way.
*
* The Manager is opened by `tabs.create` or by Chrome's options mechanism, so
* `window.opener` is null and close() is not guaranteed to work. Rather than
* bet the decline path on it, wait a beat and tell the user plainly if the
* document is still here. `tabs.remove` is not an option: it needs the `tabs`
* permission, which docs/08 §2 forbids.
*/
function closeTab(): void {
// Clear first: repeated clicks would otherwise stack timers, and only the
// last one would ever be cleaned up.
if (closeTimer !== undefined) clearTimeout(closeTimer);
globalThis.close();
closeTimer = setTimeout(() => {
closeTimer = undefined;
closeFailed = true;
}, CLOSE_GRACE_MS);
}
</script>
<section class="gate" aria-labelledby="legal-gate-title">
<header>
<img src="/icon/48.png" alt="" width="48" height="48" />
<h1 id="legal-gate-title" bind:this={heading} tabindex="-1">
{status.reason === 'updated' ? t('legal.updatedTitle') : t('legal.title')}
</h1>
</header>
{#if status.reason === 'updated'}
<Callout tone="warn">{t('legal.updatedBody')}</Callout>
{/if}
<p class="summary">{t('legal.summary')}</p>
<h2>{t('legal.documents')}</h2>
<ul>
{#each LEGAL_URLS as link (link.url)}
<li>
<a href={link.url} target="_blank" rel="noopener noreferrer">{t(link.labelKey)} ↗</a>
</li>
{/each}
</ul>
<p class="note">{t('legal.englishNote')}</p>
<label class="accept">
<input type="checkbox" bind:checked disabled={saving} />
<span>{t('legal.accept')}</span>
</label>
{#if saveFailed}
<Callout tone="danger">{t('legal.saveFailed')}</Callout>
{#if saveDetail !== undefined}
<pre class="detail">{saveDetail}</pre>
{/if}
{/if}
<div class="actions">
<Button variant="primary" disabled={!checked || saving} onclick={accept}>
{t('legal.continue')}
</Button>
<Button disabled={saving} onclick={closeTab}>{t('legal.close')}</Button>
</div>
{#if closeFailed}
<p class="note">{t('legal.closeManually')}</p>
{/if}
</section>
<style>
.gate {
display: flex;
flex-direction: column;
gap: var(--sp-3);
max-width: 56ch;
margin: 0 auto;
padding: var(--sp-5);
border: 1px solid var(--border);
border-radius: var(--radius);
background: var(--bg-raised);
}
header {
display: flex;
align-items: center;
gap: var(--sp-3);
}
h1 {
margin: 0;
font-size: var(--fs-4);
}
h2 {
margin: var(--sp-2) 0 0;
font-size: var(--fs-2);
}
.summary {
margin: 0;
font-size: var(--fs-1);
}
ul {
display: flex;
flex-wrap: wrap;
gap: var(--sp-2) var(--sp-4);
margin: 0;
padding: 0;
list-style: none;
font-size: var(--fs-1);
}
.note {
margin: 0;
color: var(--fg-muted);
font-size: var(--fs-0);
}
.accept {
display: flex;
align-items: center;
gap: var(--sp-2);
margin-top: var(--sp-2);
font-size: var(--fs-1);
}
.detail {
margin: 0;
padding: var(--sp-2);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
background: var(--bg);
color: var(--fg-muted);
font-size: var(--fs-0);
white-space: pre-wrap;
overflow-x: auto;
}
.actions {
display: flex;
gap: var(--sp-2);
}
</style>
+84
View File
@@ -0,0 +1,84 @@
<script lang="ts">
import type { MoveTarget } from '../edit/move-target';
import type { EditNode } from '../edit/patch-tree';
import { t } from '../i18n/index.svelte';
import Button from './Button.svelte';
interface Props {
/** The node being moved. Rendering is caller-gated on this existing. */
node: EditNode;
targets: readonly MoveTarget[];
onpick: (parentId: string) => void;
oncancel: () => void;
}
let { node, targets, onpick, oncancel }: Props = $props();
</script>
<!-- Keyboard parity for drag & drop (docs/06 §3.3): every move reachable
without a mouse. -->
<div class="move-to" role="dialog" aria-label={t('edit.moveTo')}>
<p>{t('edit.moveToBody', { title: node.title })}</p>
<ul>
{#each targets as target (target.id)}
<li><button onclick={() => onpick(target.id)}>{target.label}</button></li>
{/each}
{#if targets.length === 0}
<li class="muted">{t('edit.noMoveTargets')}</li>
{/if}
</ul>
<Button onclick={oncancel}>{t('common.cancel')}</Button>
</div>
<style>
/* Copied verbatim from EditTab — this is a move, not a redesign. */
.move-to {
position: fixed;
inset-block-end: var(--sp-4);
inset-inline-end: var(--sp-4);
width: min(360px, calc(100vw - var(--sp-6)));
max-height: 60vh;
overflow: auto;
background: var(--bg);
border: 1px solid var(--accent);
border-radius: var(--radius);
padding: var(--sp-3);
box-shadow: 0 8px 32px rgb(0 0 0 / 0.25);
}
.move-to p {
margin: 0 0 var(--sp-2);
font-size: var(--fs-1);
color: var(--fg-muted);
}
.move-to ul {
list-style: none;
margin: 0 0 var(--sp-3);
padding: 0;
display: flex;
flex-direction: column;
gap: 2px;
}
.move-to button {
font: inherit;
width: 100%;
text-align: left;
background: none;
border: none;
border-radius: var(--radius-sm);
color: var(--fg);
cursor: pointer;
padding: var(--sp-1) var(--sp-2);
}
.move-to button:hover {
background: var(--bg-raised);
}
.muted {
color: var(--fg-muted);
font-size: var(--fs-1);
}
</style>
+3
View File
@@ -10,6 +10,9 @@
const percent = $derived(total === 0 ? 0 : Math.round((done / total) * 100));
// Announce every 10% rather than on every tick — docs/06 §5.
const announced = $derived(Math.floor(percent / 10) * 10);
// Not run through Intl (unlike counts elsewhere): this is 0–100, and none of
// en-US/vi-VN/ja-JP groups a two-digit number — so it would cost a formatter
// lookup on the hottest render path in the app and change nothing.
</script>
<div class="wrap">
+58
View File
@@ -0,0 +1,58 @@
<script lang="ts">
import type { Snippet } from 'svelte';
interface Props {
label: string;
/** Explicit `| undefined` — exactOptionalPropertyTypes rejects the short form. */
description?: string | undefined;
control: Snippet;
}
let { label, description, control }: Props = $props();
</script>
<div class="row">
<div class="text">
<span class="label">{label}</span>
{#if description !== undefined}<span class="description">{description}</span>{/if}
</div>
<div class="control">{@render control()}</div>
</div>
<style>
.row {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--sp-4);
padding: var(--sp-3) 0;
border-bottom: 1px solid var(--border);
}
.text {
display: flex;
flex-direction: column;
gap: var(--sp-1);
}
.label {
font-size: var(--fs-2);
}
.description {
font-size: var(--fs-0);
color: var(--fg-muted);
}
.control {
flex-shrink: 0;
}
@media (max-width: 560px) {
.row {
flex-direction: column;
align-items: stretch;
gap: var(--sp-2);
}
}
</style>
+216
View File
@@ -0,0 +1,216 @@
<script lang="ts">
import type { Settings } from '../browser/storage';
import { t } from '../i18n/index.svelte';
import {
CSV_DELIMITER_CHOICES,
EXPORT_FORMAT_CHOICES,
IMPORT_MODE_CHOICES,
MARKDOWN_STYLE_CHOICES,
parseChoice,
type SettingChoice,
} from '../settings/options';
import { getSettings, resetSettings, updateSettings } from '../stores/settings.svelte';
import { pushToast } from '../stores/toast.svelte';
import Button from './Button.svelte';
import ConfirmDialog from './ConfirmDialog.svelte';
import LanguageSwitcher from './LanguageSwitcher.svelte';
import SettingRow from './SettingRow.svelte';
import ThemeToggle from './ThemeToggle.svelte';
const settings = $derived(getSettings());
let confirmingReset = $state(false);
/** Raw browser error behind the last failed save, if any. */
let saveDetail = $state<string | undefined>();
/**
* Every write reports what actually happened. The toast used to be the only
* feedback and fired before the write settled, which meant a failed save
* still said "Saved".
*/
function save(patch: Partial<Settings>, successKey = 'settings.saved'): void {
void updateSettings(patch).then((outcome) => {
if (outcome.ok) {
pushToast(t(successKey), 'success');
saveDetail = undefined;
return;
}
// The LOCALIZED sentence is the message; the raw browser error is the
// separate technical detail docs/02 §7 asks for. Putting `detail` first
// made every translation of settings.saveFailed dead code and showed a
// VI/JA user an untranslated Chrome string.
pushToast(t('settings.saveFailed'), 'danger');
saveDetail = outcome.detail;
});
}
/** Narrow a `<select>` value, then save — bailing before the patch is built. */
function saveChoice<K extends keyof Settings & string>(
key: K,
raw: string,
choices: readonly SettingChoice<Settings[K] & string>[],
): void {
const next = parseChoice(raw, choices);
if (next === undefined) return;
// SAFETY: `next` came out of a table typed against Settings[K], so this
// narrowing only re-states what parseChoice already proved.
save({ [key]: next } as Partial<Settings>);
}
function confirmReset(): void {
confirmingReset = false;
void resetSettings().then((outcome) => {
if (outcome.ok) {
pushToast(t('settings.resetDone'), 'success');
saveDetail = undefined;
return;
}
pushToast(t('settings.saveFailed'), 'danger');
saveDetail = outcome.detail;
});
}
</script>
<section aria-label={t('common.settings')}>
<p class="muted">{t('settings.autosave')}</p>
<SettingRow label={t('settings.language')} description={t('settings.languageNote')}>
{#snippet control()}
<LanguageSwitcher
compact
value={settings.locale}
onchange={(locale) => save({ locale })}
/>
{/snippet}
</SettingRow>
<SettingRow label={t('settings.theme')}>
{#snippet control()}
<ThemeToggle value={settings.theme} onchange={(theme) => save({ theme })} />
{/snippet}
</SettingRow>
<SettingRow
label={t('settings.defaultExportFormat')}
description={t('settings.defaultExportFormatNote')}
>
{#snippet control()}
<select
aria-label={t('settings.defaultExportFormat')}
value={settings.defaultExportFormat}
onchange={(event) =>
saveChoice('defaultExportFormat', event.currentTarget.value, EXPORT_FORMAT_CHOICES)}
>
{#each EXPORT_FORMAT_CHOICES as choice (choice.value)}
<option value={choice.value}>{t(choice.labelKey)}</option>
{/each}
</select>
{/snippet}
</SettingRow>
<SettingRow
label={t('settings.defaultImportMode')}
description={t('settings.defaultImportModeNote')}
>
{#snippet control()}
<select
aria-label={t('settings.defaultImportMode')}
value={settings.defaultMergeMode}
onchange={(event) =>
saveChoice('defaultMergeMode', event.currentTarget.value, IMPORT_MODE_CHOICES)}
>
{#each IMPORT_MODE_CHOICES as choice (choice.value)}
<option value={choice.value}>{t(choice.labelKey)}</option>
{/each}
</select>
{/snippet}
</SettingRow>
<SettingRow label={t('settings.csvDelimiter')} description={t('settings.csvDelimiterNote')}>
{#snippet control()}
<select
aria-label={t('settings.csvDelimiter')}
value={settings.csvDelimiter}
onchange={(event) =>
saveChoice('csvDelimiter', event.currentTarget.value, CSV_DELIMITER_CHOICES)}
>
{#each CSV_DELIMITER_CHOICES as choice (choice.value)}
<option value={choice.value}>{t(choice.labelKey)}</option>
{/each}
</select>
{/snippet}
</SettingRow>
<SettingRow label={t('settings.markdownStyle')} description={t('settings.markdownStyleNote')}>
{#snippet control()}
<select
aria-label={t('settings.markdownStyle')}
value={settings.markdownStyle}
onchange={(event) =>
saveChoice('markdownStyle', event.currentTarget.value, MARKDOWN_STYLE_CHOICES)}
>
{#each MARKDOWN_STYLE_CHOICES as choice (choice.value)}
<option value={choice.value}>{t(choice.labelKey)}</option>
{/each}
</select>
{/snippet}
</SettingRow>
{#if saveDetail !== undefined}
<pre class="detail">{saveDetail}</pre>
{/if}
<footer>
<Button onclick={() => (confirmingReset = true)}>{t('settings.reset')}</Button>
</footer>
</section>
<ConfirmDialog
open={confirmingReset}
title={t('settings.resetTitle')}
body={t('settings.resetBody')}
confirmLabel={t('settings.resetConfirm')}
cancelLabel={t('common.cancel')}
onconfirm={confirmReset}
oncancel={() => (confirmingReset = false)}
/>
<style>
section {
max-width: 640px;
}
.muted {
margin: 0 0 var(--sp-3);
color: var(--fg-muted);
font-size: var(--fs-1);
}
select {
font: inherit;
padding: var(--sp-1) var(--sp-2);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
background: var(--bg);
color: var(--fg);
}
select:hover {
border-color: var(--accent);
}
.detail {
margin: var(--sp-3) 0 0;
padding: var(--sp-2);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
background: var(--bg-raised);
color: var(--fg-muted);
font-size: var(--fs-0);
white-space: pre-wrap;
overflow-x: auto;
}
footer {
padding-top: var(--sp-4);
}
</style>
+5 -5
View File
@@ -1,5 +1,5 @@
<script lang="ts">
import { t } from '../i18n/index.svelte';
import { num, t } from '../i18n/index.svelte';
import type { TreeStats } from '../core/model';
interface Props {
@@ -11,10 +11,10 @@
</script>
<dl>
<div><dt>{t('import.stats.bookmarks')}</dt><dd>{stats.bookmarks}</dd></div>
<div><dt>{t('import.stats.folders')}</dt><dd>{stats.folders}</dd></div>
<div><dt>{t('import.stats.depth')}</dt><dd>{stats.maxDepth}</dd></div>
<div><dt>{t('import.stats.duplicates')}</dt><dd>{duplicates}</dd></div>
<div><dt>{t('import.stats.bookmarks')}</dt><dd>{num(stats.bookmarks)}</dd></div>
<div><dt>{t('import.stats.folders')}</dt><dd>{num(stats.folders)}</dd></div>
<div><dt>{t('import.stats.depth')}</dt><dd>{num(stats.maxDepth)}</dd></div>
<div><dt>{t('import.stats.duplicates')}</dt><dd>{num(duplicates)}</dd></div>
</dl>
<style>
+28 -4
View File
@@ -4,7 +4,15 @@
import { getRoute, navigate, type Route } from '../stores/route.svelte';
interface Props {
/** Routes the legal gate is currently blocking (docs/14 §2). */
/**
* Routes the legal gate is currently blocking (docs/14 §2).
*
* These stay CLICKABLE. What blocks them is App.svelte rendering the gate
* in place of the tab body, so the tab never mounts pre-acceptance. Making
* the buttons inert instead was a dead end: they are the only in-app
* navigation to a gated route, so a first-run user who reached #settings —
* the flow docs/14 §2 explicitly wants — had no way back to the accept UI.
*/
blocked?: readonly Route[];
}
@@ -17,13 +25,18 @@
];
</script>
<nav aria-label="Sections">
<nav aria-label={t('common.sections')}>
{#each TABS as tab (tab.route)}
<button
class:active={getRoute() === tab.route}
aria-current={getRoute() === tab.route ? 'page' : undefined}
disabled={blocked.includes(tab.route) || (isWriting() && getRoute() !== tab.route)}
title={isWriting() && getRoute() !== tab.route ? t('common.busy') : undefined}
class:locked={blocked.includes(tab.route)}
disabled={isWriting() && getRoute() !== tab.route}
title={blocked.includes(tab.route)
? t('legal.blocked')
: isWriting() && getRoute() !== tab.route
? t('common.busy')
: undefined}
onclick={() => navigate(tab.route)}
>
{t(tab.key)}
@@ -56,6 +69,17 @@
cursor: not-allowed;
}
/* Reachable, but visibly not yet usable — clicking shows the gate.
Deliberately NOT `opacity`, which composites the label against the page and
dropped --fg-muted from 5.98:1 to 2.83:1. The contrast test reads token
values out of tokens.css, so it cannot see an alpha applied on top: this
kind of dimming has to be avoided by hand. The padlock and the `title`
already carry the signal. */
.locked::after {
content: ' 🔒';
font-size: var(--fs-0);
}
.active {
background: var(--bg-raised);
border-color: var(--border);
+138
View File
@@ -0,0 +1,138 @@
<script lang="ts">
import type { ThemePreference } from '../browser/storage';
import { t } from '../i18n/index.svelte';
import { THEME_CHOICES } from '../settings/options';
interface Props {
value: ThemePreference;
onchange: (next: ThemePreference) => void;
/** Header variant: glyphs instead of words, labels moved to aria-label. */
compact?: boolean;
}
let { value, onchange, compact = false }: Props = $props();
// docs/06 §3 sketches a single ◐ that cycles. A segmented control instead:
// one code path for both placements, and the current choice is visible rather
// than inferred — a cycling button conflates "what am I" with "what's next".
// The compact header variant shows glyphs only, so they have to be legible at
// ~13px. U+263E (☾) was tried and is a thin crescent that reads as a capital
// "C" at that size — emoji are unambiguous and match the popup's existing
// ⬆/⬇/🗂 vocabulary. The accessible name comes from aria-label either way.
const GLYPH: Record<ThemePreference, string> = {
system: '◐',
light: '☀️',
dark: '🌙',
};
let buttons: HTMLButtonElement[] = $state([]);
/**
* The radiogroup keyboard pattern, which the ARIA roles above promise.
*
* Without this the roles are a lie: a screen reader announces "radio button,
* 1 of 3" and switches to forms mode, then the arrow keys do nothing and all
* three are separate tab stops — the inverse of the pattern (WCAG 4.1.2).
*
* Bound to each radio rather than the group, because only the radios are
* focusable — a keyboard handler on a non-focusable container never fires,
* which is exactly what svelte-check's `a11y_interactive_supports_focus`
* warns about.
*/
function onKeyDown(event: KeyboardEvent): void {
const index = THEME_CHOICES.findIndex((choice) => choice.value === value);
if (index === -1) return;
let next: number | undefined;
if (event.key === 'ArrowRight' || event.key === 'ArrowDown') {
next = (index + 1) % THEME_CHOICES.length;
} else if (event.key === 'ArrowLeft' || event.key === 'ArrowUp') {
next = (index - 1 + THEME_CHOICES.length) % THEME_CHOICES.length;
} else if (event.key === 'Home') {
next = 0;
} else if (event.key === 'End') {
next = THEME_CHOICES.length - 1;
}
if (next === undefined) return;
event.preventDefault();
const choice = THEME_CHOICES[next];
if (choice === undefined) return;
onchange(choice.value);
buttons[next]?.focus();
}
</script>
<div class="group" class:compact role="radiogroup" aria-label={t('settings.theme')}>
{#each THEME_CHOICES as choice, index (choice.value)}
<button
bind:this={buttons[index]}
type="button"
role="radio"
aria-checked={value === choice.value}
aria-label={compact ? t(choice.labelKey) : undefined}
tabindex={value === choice.value ? 0 : -1}
class:selected={value === choice.value}
onclick={() => onchange(choice.value)}
onkeydown={onKeyDown}
>
{#if compact}
<span aria-hidden="true">{GLYPH[choice.value]}</span>
{:else}
{t(choice.labelKey)}
{/if}
</button>
{/each}
</div>
<style>
/* No `overflow: hidden` here. It clipped the global :focus-visible ring,
which base.css draws at outline-offset: 2px — entirely outside the clip
region — leaving the theme control with no keyboard focus indicator at all.
The corner rounding it was for is done per-child instead. */
.group {
display: inline-flex;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
}
button {
font: inherit;
padding: var(--sp-1) var(--sp-3);
border: none;
border-right: 1px solid var(--border);
background: var(--bg);
color: var(--fg-muted);
cursor: pointer;
font-size: var(--fs-1);
}
button:first-child {
border-top-left-radius: var(--radius-sm);
border-bottom-left-radius: var(--radius-sm);
}
button:last-child {
border-right: none;
border-top-right-radius: var(--radius-sm);
border-bottom-right-radius: var(--radius-sm);
}
/* Inset so the ring stays inside the group's own border box. */
button:focus-visible {
outline-offset: -2px;
}
button:hover {
color: var(--fg);
}
.selected {
background: var(--accent);
color: var(--accent-fg);
}
.compact button {
padding: var(--sp-1) var(--sp-2);
}
</style>
+85
View File
@@ -0,0 +1,85 @@
<script lang="ts">
import { t } from '../i18n/index.svelte';
import { dismissToast, getVisibleToast } from '../stores/toast.svelte';
const toast = $derived(getVisibleToast());
</script>
<!-- Both live regions are ALWAYS in the DOM and only their text changes.
A live region inserted into the page already populated is not reliably
announced — screen readers derive announcements from mutations to a region
that was already present, so the earlier "whole thing inside {#if}" shape
meant success toasts were silently skipped.
Two fixed regions rather than one with a swapped aria-live, because
changing a live region's politeness at runtime is not reliably picked up.
Assertive interrupts, which is right for a failure and wrong for a
confirmation — the same split Callout already makes. -->
<div class="sr-only" role="status" aria-live="polite">
{toast !== undefined && toast.tone !== 'danger' ? toast.message : ''}
</div>
<div class="sr-only" role="alert" aria-live="assertive">
{toast?.tone === 'danger' ? toast.message : ''}
</div>
{#if toast !== undefined}
<div class="toast {toast.tone}">
<!-- Hidden from assistive tech: the live regions above already carry it,
and announcing it twice is worse than not styling it. -->
<span aria-hidden="true">{toast.message}</span>
<button aria-label={t('common.dismiss')} onclick={() => dismissToast(toast.id)}>✕</button>
</div>
{/if}
<style>
.sr-only {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
.toast {
position: fixed;
right: var(--sp-4);
bottom: var(--sp-4);
z-index: 10;
display: flex;
align-items: center;
gap: var(--sp-3);
max-width: 44ch;
padding: var(--sp-2) var(--sp-3);
border: 1px solid var(--border);
border-left: 3px solid var(--fg-muted);
border-radius: var(--radius-sm);
background: var(--bg-raised);
color: var(--fg);
font-size: var(--fs-1);
box-shadow: 0 4px 16px rgb(0 0 0 / 0.18);
}
.success {
border-left-color: var(--success);
}
.danger {
border-left-color: var(--danger);
}
button {
font: inherit;
flex-shrink: 0;
padding: 0;
border: none;
background: none;
color: var(--fg-muted);
cursor: pointer;
}
button:hover {
color: var(--fg);
}
</style>
+2 -1
View File
@@ -1,6 +1,7 @@
<script lang="ts">
import type { BookmarkNode } from '../core/model';
import type { NodeStatus } from '../core/diff';
import { t } from '../i18n/index.svelte';
import TreePreviewNode from './TreePreviewNode.svelte';
interface Props {
@@ -13,7 +14,7 @@
<!-- Read-only preview. Folders below depth 2 start collapsed and mount their
children lazily, so the DOM never holds the whole tree (docs/05 §9). -->
<ul class="tree" role="tree" aria-label="Preview">
<ul class="tree" role="tree" aria-label={t('import.preview')}>
{#each roots as node, i (i)}
<TreePreviewNode {node} {status} depth={1} />
{/each}
+32 -4
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { isBlockedUrl } from '../browser/open-url';
import type { EditNode } from '../edit/patch-tree';
import { t } from '../i18n/index.svelte';
@@ -17,6 +18,7 @@
onstartRename: () => void;
ondelete: () => void;
onopen: () => void;
oncopyUrl: () => void;
onmoveTo: () => void;
ondragstart: () => void;
ondropinto: () => void;
@@ -41,6 +43,7 @@
onstartRename,
ondelete,
onopen,
oncopyUrl,
onmoveTo,
ondragstart,
ondropinto,
@@ -51,6 +54,7 @@
const isFolder = $derived(node.url === undefined);
const domain = $derived(hostOf(node.url));
const blocked = $derived(!isFolder && isBlockedUrl(node.url));
function hostOf(url: string | undefined): string {
if (url === undefined) return '';
@@ -117,40 +121,57 @@
{:else}
<span class="title">{node.title}</span>
{#if domain !== ''}<span class="domain">{domain}</span>{/if}
{#if blocked}
<!-- docs/09 T3: a javascript:/data: bookmark must not look like an
ordinary link that merely does nothing when clicked. -->
<span class="unsafe" title={t('edit.unsafeUrl')} aria-label={t('edit.unsafeUrl')}>⚠</span>
{/if}
<span class="actions">
{#if editable}
<button
title={t('edit.rename')}
aria-label={t('edit.rename')}
onclick={(e) => {
e.stopPropagation();
onstartRename();
}}>✎</button
}}><span aria-hidden="true">✎</span></button
>
{/if}
{#if !isFolder}
<button
title={t('edit.open')}
aria-label={t('edit.open')}
onclick={(e) => {
e.stopPropagation();
onopen();
}}>↗</button
}}><span aria-hidden="true">↗</span></button
>
<button
title={t('edit.copyUrl')}
aria-label={t('edit.copyUrl')}
onclick={(e) => {
e.stopPropagation();
oncopyUrl();
}}><span aria-hidden="true">⧉</span></button
>
{/if}
{#if editable}
<button
title={t('edit.moveTo')}
aria-label={t('edit.moveTo')}
onclick={(e) => {
e.stopPropagation();
onmoveTo();
}}>⇄</button
}}><span aria-hidden="true">⇄</span></button
>
<button
title={t('edit.delete')}
aria-label={t('edit.delete')}
onclick={(e) => {
e.stopPropagation();
ondelete();
}}>🗑</button
}}><span aria-hidden="true">🗑</span></button
>
{/if}
</span>
@@ -212,6 +233,13 @@
white-space: nowrap;
}
.unsafe {
flex-shrink: 0;
font-size: var(--fs-0);
color: var(--warn);
cursor: help;
}
.rename {
font: inherit;
flex: 1;
+3 -3
View File
@@ -1,5 +1,5 @@
<script lang="ts">
import { t } from '../i18n/index.svelte';
import { tPlural } from '../i18n/index.svelte';
import type { ParseWarning } from '../core/model';
interface Props {
@@ -11,10 +11,10 @@
{#if warnings.length > 0}
<details>
<summary>{t('import.warnings.title', { n: warnings.length })}</summary>
<summary>{tPlural('import.warnings.title', warnings.length)}</summary>
<ul>
{#each warnings as warning (warning.code)}
<li>{t(`warnings.${warning.code}`, { n: warning.count })}</li>
<li>{tPlural(`warnings.${warning.code}`, warning.count)}</li>
{/each}
</ul>
</details>
+82
View File
@@ -0,0 +1,82 @@
/**
* Pure helpers over the `#edit` tree — docs/03 §3.
*
* Purpose: the tree logic that used to sit inline in `EditTab.svelte`, where it
* was untestable and pushed the component past the docs/10 §1 size limits.
* Inputs: `EditNode` trees, plus `LiveNode`s straight from the bookmarks API.
* Guarantees: pure — no `chrome.*`, no Svelte, no mutation of the input.
*/
import type { LiveNode } from '../browser/bookmarks';
import type { EditNode } from './patch-tree';
/**
* Project a live bookmark node onto the editable model.
*
* Absent keys are omitted rather than set to `undefined`, per the
* `exactOptionalPropertyTypes` rule in docs/10 §2. `children` is set only for
* folders, which is what makes `url === undefined` a reliable folder test.
*/
export function toEditNode(node: LiveNode): EditNode {
return {
id: node.id,
...(node.parentId !== undefined && { parentId: node.parentId }),
title: node.title,
...(node.url !== undefined && { url: node.url }),
...(node.url === undefined && { children: (node.children ?? []).map(toEditNode) }),
...(node.unmodifiable !== undefined && { unmodifiable: node.unmodifiable }),
};
}
/** Depth-first list of every node in the forest, parents before children. */
export function flattenTree(nodes: readonly EditNode[], into: EditNode[] = []): EditNode[] {
for (const node of nodes) {
into.push(node);
flattenTree(node.children ?? [], into);
}
return into;
}
/**
* Whether a node may be renamed, moved or deleted.
*
* Permanent roots and policy-managed nodes reject every write, so the UI must
* not offer the affordance at all — mutating optimistically and finding out on
* rejection is exactly how the tree ends up disagreeing with the browser.
*/
export function isEditable(roots: readonly EditNode[], node: EditNode): boolean {
if (node.unmodifiable !== undefined) return false;
return !roots.some((root) => root.id === node.id);
}
/**
* Where a new folder should be created, given what is focused.
*
* Into the focused FOLDER, or alongside the focused bookmark. Using the focused
* node's parent unconditionally meant selecting a root resolved to the
* synthetic root id `"0"`, which every `create` rejects.
*
* Returns `undefined` when there is nowhere writable to put it.
*/
export function resolveNewFolderParent(
roots: readonly EditNode[],
focused: EditNode | undefined,
): string | undefined {
const writableRoot = roots.find((root) => root.unmodifiable === undefined)?.id;
if (focused === undefined) return writableRoot;
// A policy-managed folder rejects every create, so falling back is the only
// way "New folder" does anything at all while one is selected.
if (focused.unmodifiable !== undefined) return writableRoot;
if (focused.url === undefined) return focused.id;
return focused.parentId ?? writableRoot;
}
/** How many nodes sit inside `node`. Drives the delete confirmation's count. */
export function countDescendants(node: EditNode | undefined): number {
if (node === undefined) return 0;
return flattenTree(node.children ?? []).length;
}
/** Ids to delete so one copy of each duplicated link survives. */
export function extraCopyIds(groups: readonly { nodes: readonly EditNode[] }[]): string[] {
return groups.flatMap((group) => group.nodes.slice(1).map((node) => node.id));
}
+9 -4
View File
@@ -6,6 +6,8 @@
* anchor path is enough here — unlike the Replace backup, a failed export
* loses nothing).
*/
import { getGeneratorVersion } from '../browser/app-info';
import { getRootChildren, getRoots, type LiveNode, toBookmarkNodes } from '../browser/bookmarks';
import { sanitizeFilename, timestampSuffix, triggerDownload } from '../browser/download';
import type { ExportFormat } from '../browser/storage';
@@ -15,8 +17,6 @@ import { type CsvDelimiter, serializeCsv } from '../core/serialize/csv';
import { type MarkdownStyle, serializeMarkdown } from '../core/serialize/markdown';
import { serializeNetscapeHtml } from '../core/serialize/netscape-html';
const APP_VERSION = '0.1.0';
export const FORMAT_META: Record<
ExportFormat,
{ extension: string; mimeType: string; importable: boolean }
@@ -44,7 +44,12 @@ export interface ExportPreview {
bookmarks: number;
}
/** ISO date for the Markdown heading — locale-independent by design (docs/07 §3). */
/**
* ISO date for the Markdown heading — locale-independent by design (docs/07 §3).
*
* Deliberately not `Intl`: file names and file *contents* stay locale-neutral so
* an exported file means the same thing whoever opens it.
*/
function isoDate(now: Date): string {
const pad = (n: number): string => String(n).padStart(2, '0');
return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
@@ -112,7 +117,7 @@ function serialize(nodes: ReturnType<typeof toBookmarkNodes>, options: ExportOpt
return serializeNetscapeHtml(nodes);
case 'bm-json':
return serializeBmJson(nodes, {
version: APP_VERSION,
version: getGeneratorVersion(),
exportedAt: options.now.toISOString(),
});
case 'csv':
+80
View File
@@ -0,0 +1,80 @@
/**
* Locale-aware number and date formatting — docs/07 §3.
*
* Purpose: the single place `Intl` is constructed, so every rendered count and
* timestamp follows the UI language rather than the browser's.
* Inputs: a resolved `Locale`, plus raw numbers / ISO 8601 strings.
* Guarantees: pure (no Svelte, no `chrome.*`), never throws — an unparseable
* date returns `undefined` rather than blowing up mid-render.
*/
import type { Locale } from './resolve-locale';
/** BCP 47 tags docs/07 §3 pins per locale. */
export type LocaleTag = 'en-US' | 'vi-VN' | 'ja-JP';
const TAGS: Record<Locale, LocaleTag> = {
en: 'en-US',
vi: 'vi-VN',
ja: 'ja-JP',
};
// Constructing an Intl formatter is expensive relative to a render, and
// StatsCard alone formats four counts per paint — so cache per tag.
const numberFormats = new Map<LocaleTag, Intl.NumberFormat>();
const dateFormats = new Map<LocaleTag, Intl.DateTimeFormat>();
const pluralRules = new Map<LocaleTag, Intl.PluralRules>();
/** The two forms docs/07 §5 requires every plural key to carry. */
export type PluralForm = 'one' | 'other';
/**
* Pick a plural form for a count.
*
* Narrowed to `one`/`other` deliberately: `Intl.PluralRules` can return `zero`,
* `two`, `few` and `many` for other languages, but en yields only one/other and
* vi/ja only ever yield other — so the two-form dictionaries docs/07 §5
* specifies are sufficient for exactly the locales we ship.
*/
export function selectPluralForm(count: number, tag: LocaleTag): PluralForm {
let rules = pluralRules.get(tag);
if (rules === undefined) {
rules = new Intl.PluralRules(tag);
pluralRules.set(tag, rules);
}
return rules.select(count) === 'one' ? 'one' : 'other';
}
export function localeTag(locale: Locale): LocaleTag {
return TAGS[locale];
}
/** Group a count for display — VI uses `.` thousands, EN `,`, JA `,`. */
export function formatCount(value: number, tag: LocaleTag): string {
let format = numberFormats.get(tag);
if (format === undefined) {
format = new Intl.NumberFormat(tag);
numberFormats.set(tag, format);
}
return format.format(value);
}
/**
* Format an ISO 8601 instant for display.
*
* Returns `undefined` — not a fallback string — when the input is unparseable.
* That is load-bearing: `readLegal` deliberately coerces a missing `acceptedAt`
* to `''` (browser/storage.ts), and `Intl.format(new Date(''))` throws a
* RangeError *inside a render*, which would blank the whole About tab. Forcing
* the caller to branch is the point.
*/
export function formatDateTime(iso: string, tag: LocaleTag): string | undefined {
const date = new Date(iso);
if (Number.isNaN(date.getTime())) return undefined;
let format = dateFormats.get(tag);
if (format === undefined) {
format = new Intl.DateTimeFormat(tag, { dateStyle: 'medium', timeStyle: 'short' });
dateFormats.set(tag, format);
}
return format.format(date);
}
+49
View File
@@ -1,3 +1,4 @@
import { formatCount, formatDateTime, localeTag, selectPluralForm } from './format';
import en from './locales/en';
import ja from './locales/ja';
import vi from './locales/vi';
@@ -19,6 +20,27 @@ export function setLocale(next: Locale): void {
locale = next;
}
/**
* The *resolved* locale (`en|vi|ja`).
*
* Not to be confused with `getSettings().locale`, the *preference*, which also
* carries `'auto'`. Language controls must bind to the preference — binding to
* this makes choosing "Automatic" instantly snap the control to "English".
*/
export function getLocale(): Locale {
return locale;
}
/** Group a count for the current locale (docs/07 §3). Reactive. */
export function num(value: number): string {
return formatCount(value, localeTag(locale));
}
/** Format an ISO instant for the current locale, or `undefined` if unparseable. */
export function dateTime(iso: string): string | undefined {
return formatDateTime(iso, localeTag(locale));
}
/**
* Resolve a dotted key path, falling back to English, then to the key itself.
* Interpolation is `{token}` replacement only — never concatenate sentence
@@ -26,6 +48,33 @@ export function setLocale(next: Locale): void {
*/
export function t(path: string, params?: Record<string, string | number>): string {
const raw = lookup(dicts[locale], path) ?? lookup(dicts.en, path) ?? path;
return interpolate(raw, params);
}
/**
* Resolve a plural key — an object of `{ one, other }` per docs/07 §5.
*
* `{n}` is supplied automatically, already grouped for the locale, so callers
* pass the raw count and never have to format it themselves. VI and JA carry
* both forms with the same text (one grammatical form), which is what keeps the
* `satisfies Dict` shape check meaningful.
*/
export function tPlural(
path: string,
count: number,
params?: Record<string, string | number>,
): string {
const form = selectPluralForm(count, localeTag(locale));
const raw =
lookup(dicts[locale], `${path}.${form}`) ??
lookup(dicts[locale], `${path}.other`) ??
lookup(dicts.en, `${path}.${form}`) ??
lookup(dicts.en, `${path}.other`) ??
path;
return interpolate(raw, { n: num(count), ...params });
}
function interpolate(raw: string, params?: Record<string, string | number>): string {
if (params === undefined) return raw;
return raw.replace(/\{(\w+)\}/g, (match, token: string) =>
Object.hasOwn(params, token) ? String(params[token]) : match,
+118 -10
View File
@@ -21,7 +21,10 @@ const dict = {
about: 'About',
busy: 'An import is in progress',
cancel: 'Cancel',
comingSoon: '{tab} arrives in a later build.',
// Distinct from `cancel`: this only hides a notification about something
// that already finished — there is nothing left to call off.
dismiss: 'Dismiss',
sections: 'Sections',
},
popup: {
import: 'Import bookmarks…',
@@ -32,6 +35,7 @@ const dict = {
import: {
dropHint: 'Drop a bookmark file or click to browse — .html, .json, .csv · max {size}',
reading: 'Reading {name}…',
preview: 'Preview',
folderName: 'Imported {date}',
start: 'Import {n} bookmarks',
backingUp:
@@ -68,7 +72,8 @@ const dict = {
replace: 'Replace everything',
},
warnings: {
title: '{n} warning(s)',
// Plural keys are `{ one, other }` objects in EVERY locale (docs/07 §5).
title: { one: '{n} warning', other: '{n} warnings' },
},
},
export: {
@@ -105,6 +110,10 @@ const dict = {
collapseAll: 'Collapse all',
rename: 'Rename',
open: 'Open',
copyUrl: 'Copy link',
unsafeUrl: 'This address uses a scheme BookmarkMagic will not open.',
copied: 'Link copied',
copyFailed: 'Could not copy the link.',
moveTo: 'Move to…',
moveToBody: 'Move "{title}" into which folder?',
noMoveTargets: 'No other folder is available.',
@@ -123,15 +132,114 @@ const dict = {
keepFirstBody:
'Keep the first copy of each link and delete the other {n}? This cannot be undone.',
},
settings: {
autosave: 'Changes are saved as you make them.',
language: 'Language',
languageNote: 'Applies to this extension only, not to the browser.',
localeAuto: 'Automatic (follow the browser)',
lang: {
// Endonyms, deliberately identical in all three dictionaries: a Japanese
// user hunting for Vietnamese looks for "Tiếng Việt", not "ベトナム語".
en: 'English',
vi: 'Tiếng Việt',
ja: '日本語',
},
theme: 'Theme',
themes: {
system: 'System',
light: 'Light',
dark: 'Dark',
},
defaultExportFormat: 'Default export format',
defaultExportFormatNote: 'Pre-selected when you open the Export tab.',
defaultImportMode: 'Default import mode',
defaultImportModeNote: 'Pre-selected when you open the Import tab.',
csvDelimiter: 'CSV delimiter',
csvDelimiterNote: 'Use semicolons if your spreadsheet expects them.',
markdownStyle: 'Markdown layout',
markdownStyleNote: 'How exported Markdown arranges your folders.',
saved: 'Settings saved',
saveFailed: 'Your settings could not be saved.',
reset: 'Reset to defaults',
resetTitle: 'Reset all settings?',
resetBody:
'Language, theme and every default choice go back to how they started. Your bookmarks are not touched.',
resetConfirm: 'Reset',
resetDone: 'Settings reset to defaults',
},
about: {
tagline:
'Import, export and edit bookmarks between browsers — offline, no account, no cloud. Your data never leaves your device.',
version: 'Version {version}',
links: 'Links',
repo: 'GitHub repository',
issues: 'Report an issue',
changelog: 'Releases and changelog',
thirdParty: 'Third-party dependencies: None',
thirdPartyNote: 'BookmarkMagic ships no runtime libraries at all.',
donate: 'Support development',
donateNote: 'Entirely optional — BookmarkMagic is free software either way.',
legal: 'Legal',
accepted: 'Legal terms accepted on {date} · version {version}',
acceptedUndated: 'Legal terms accepted · version {version}',
notAccepted: 'You have not accepted the legal terms yet.',
},
legal: {
title: 'Before you start',
summary:
'BookmarkMagic runs entirely on your device. It has no servers, makes no network requests, and collects nothing — your bookmarks and settings never leave this browser. It is free software under the GPL-3.0 licence and comes with no warranty of any kind. Bookmark operations change your browser data, and the "Replace everything" mode deletes your current bookmarks, so keep your own backups of anything you care about.',
updatedTitle: 'The terms have been updated',
updatedBody:
'These documents changed since you accepted them. Please read them again to continue.',
documents: 'Documents',
eula: 'End User License Agreement',
license: 'License (GPL-3.0)',
disclaimer: 'Disclaimer',
privacy: 'Privacy Policy',
englishNote: 'The legally binding documents are in English.',
accept: 'I have read and accept the terms above',
continue: 'Accept & continue',
close: 'Close tab',
closeManually: 'You can close this tab now.',
saveFailed:
'Your acceptance could not be saved, so nothing was recorded. Check that this browser allows extension storage, then try again.',
blocked: 'Accept the terms to use the Import, Export and Edit tabs.',
},
/**
* Every code is a plural key, including the two that interpolate no count —
* `ParseWarning` always carries one, so a uniform shape lets `WarningList`
* call `tPlural` unconditionally instead of maintaining a list of which
* codes count things.
*/
warnings: {
NO_BOOKMARKS: 'This file contains no bookmarks.',
DESCRIPTIONS_DROPPED:
'{n} description(s) were dropped — they have no place in the bookmark model.',
FAVICONS_IGNORED: '{n} favicon(s) ignored — the bookmarks API cannot set favicons.',
INVALID_DATE: '{n} unreadable date(s) were left blank.',
MISSING_URL: '{n} entries had no address and were skipped.',
NEWER_VERSION: 'This file was written by a newer version — reading it as best we can.',
EMPTY_TITLE: '{n} bookmark(s) had no title; their address is shown instead.',
NO_BOOKMARKS: {
one: 'This file contains no bookmarks.',
other: 'This file contains no bookmarks.',
},
DESCRIPTIONS_DROPPED: {
one: '{n} description was dropped — it has no place in the bookmark model.',
other: '{n} descriptions were dropped — they have no place in the bookmark model.',
},
FAVICONS_IGNORED: {
one: '{n} favicon ignored — the bookmarks API cannot set favicons.',
other: '{n} favicons ignored — the bookmarks API cannot set favicons.',
},
INVALID_DATE: {
one: '{n} unreadable date was left blank.',
other: '{n} unreadable dates were left blank.',
},
MISSING_URL: {
one: '{n} entry had no address and was skipped.',
other: '{n} entries had no address and were skipped.',
},
NEWER_VERSION: {
one: 'This file was written by a newer version — reading it as best we can.',
other: 'This file was written by a newer version — reading it as best we can.',
},
EMPTY_TITLE: {
one: '{n} bookmark had no title; its address is shown instead.',
other: '{n} bookmarks had no title; their address is shown instead.',
},
},
errors: {
NOT_NETSCAPE: 'This does not look like a bookmark HTML file.',
+110 -11
View File
@@ -14,7 +14,8 @@ export default {
about: '概要',
busy: 'インポートを実行中です',
cancel: 'キャンセル',
comingSoon: '{tab}は今後のビルドで利用できます。',
dismiss: '閉じる',
sections: 'セクション',
},
popup: {
import: 'ブックマークをインポート…',
@@ -26,6 +27,7 @@ export default {
dropHint:
'ブックマークファイルをドロップするかクリックして選択してください — .html、.json、.csv · 最大 {size}',
reading: '{name} を読み込んでいます…',
preview: 'プレビュー',
folderName: 'インポート {date}',
start: '{n} 件のブックマークをインポート',
backingUp:
@@ -63,7 +65,9 @@ export default {
replace: 'すべて置き換える',
},
warnings: {
title: '警告 {n} 件',
// 日本語は単複の区別がありませんが、docs/07 §5 に従い両方のキーを
// 保持します(`satisfies Dict` の形状チェックを成立させるため)。
title: { one: '警告 {n} 件', other: '警告 {n} 件' },
},
},
export: {
@@ -99,6 +103,10 @@ export default {
collapseAll: 'すべて折りたたむ',
rename: '名前を変更',
open: '開く',
copyUrl: 'リンクをコピー',
unsafeUrl: 'このアドレスは BookmarkMagic が開かない形式です。',
copied: 'リンクをコピーしました',
copyFailed: 'リンクをコピーできませんでした。',
moveTo: '移動先…',
moveToBody: '「{title}」をどのフォルダへ移動しますか?',
noMoveTargets: '他に利用できるフォルダがありません。',
@@ -116,16 +124,107 @@ export default {
keepFirstTitle: '重複したコピーを削除しますか?',
keepFirstBody: '各リンクの最初のコピーを残し、他の {n} 件を削除しますか?元に戻せません。',
},
settings: {
autosave: '変更は自動的に保存されます。',
language: '言語',
languageNote: 'この拡張機能だけに適用され、ブラウザの言語は変わりません。',
localeAuto: '自動(ブラウザに合わせる)',
lang: {
// 自称表記。三つの辞書で意図的に同一にしています。
en: 'English',
vi: 'Tiếng Việt',
ja: '日本語',
},
theme: 'テーマ',
themes: {
system: 'システム',
light: 'ライト',
dark: 'ダーク',
},
defaultExportFormat: '既定のエクスポート形式',
defaultExportFormatNote: 'エクスポートタブを開いたときに選択されます。',
defaultImportMode: '既定のインポート方法',
defaultImportModeNote: 'インポートタブを開いたときに選択されます。',
csvDelimiter: 'CSV の区切り文字',
csvDelimiterNote: '表計算ソフトが必要とする場合はセミコロンを選んでください。',
markdownStyle: 'Markdown のレイアウト',
markdownStyleNote: 'エクスポートした Markdown でフォルダを並べる方法です。',
saved: '設定を保存しました',
saveFailed: '設定を保存できませんでした。',
reset: '既定値に戻す',
resetTitle: 'すべての設定を戻しますか?',
resetBody:
'言語・テーマ・すべての既定の選択が初期状態に戻ります。ブックマークには影響しません。',
resetConfirm: '戻す',
resetDone: '設定を既定値に戻しました',
},
about: {
tagline:
'ブラウザ間でブックマークをインポート・エクスポート・編集 — オフライン、アカウント不要、クラウド不要。データが端末から出ることはありません。',
version: 'バージョン {version}',
links: 'リンク',
repo: 'GitHub リポジトリ',
issues: '問題を報告',
changelog: 'リリースと変更履歴',
thirdParty: 'サードパーティ依存: なし',
thirdPartyNote: 'BookmarkMagic は実行時ライブラリを一切同梱していません。',
donate: '開発を支援する',
donateNote: '完全に任意です — BookmarkMagic はどちらにせよ自由ソフトウェアです。',
legal: '法的事項',
accepted: '{date} に規約に同意済み · バージョン {version}',
acceptedUndated: '規約に同意済み · バージョン {version}',
notAccepted: 'まだ法的規約に同意していません。',
},
legal: {
title: 'ご利用の前に',
summary:
'BookmarkMagic は完全にお使いの端末上で動作します。サーバーを持たず、ネットワーク通信を行わず、何も収集しません — ブックマークと設定がこのブラウザから出ることはありません。GPL-3.0 ライセンスの自由ソフトウェアであり、いかなる保証もありません。ブックマーク操作はブラウザのデータを変更し、「すべて置き換える」方法では現在のブックマークが削除されますので、大切なものはご自身でバックアップを保管してください。',
updatedTitle: '規約が更新されました',
updatedBody:
'ご同意いただいた後にこれらの文書が変更されました。続けるにはもう一度お読みください。',
documents: '文書',
eula: 'エンドユーザーライセンス契約',
license: 'ライセンス(GPL-3.0)',
disclaimer: '免責事項',
privacy: 'プライバシーポリシー',
englishNote: '法的効力を持つ文書は英語で書かれています。',
accept: '上記の規約を読み、同意します',
continue: '同意して続ける',
close: 'タブを閉じる',
closeManually: 'このタブを閉じていただいて構いません。',
saveFailed:
'同意を保存できなかったため、何も記録されていません。このブラウザで拡張機能のストレージが許可されているか確認してから、もう一度お試しください。',
blocked: 'インポート・エクスポート・編集タブを使うには規約に同意してください。',
},
warnings: {
NO_BOOKMARKS: 'このファイルにブックマークは含まれていません。',
DESCRIPTIONS_DROPPED:
'説明 {n} 件を破棄しました。ブックマークのモデルに該当する項目がありません。',
FAVICONS_IGNORED:
'ファビコン {n} 件を無視しました。ブックマーク API はファビコンを設定できません。',
INVALID_DATE: '読み取れない日付 {n} 件を空欄にしました。',
MISSING_URL: 'アドレスのない項目 {n} 件をスキップしました。',
NEWER_VERSION: 'このファイルは新しいバージョンで作成されています。可能な範囲で読み込みます。',
EMPTY_TITLE: 'タイトルのないブックマークが {n} 件あり、代わりにアドレスを表示します。',
NO_BOOKMARKS: {
one: 'このファイルにブックマークは含まれていません。',
other: 'このファイルにブックマークは含まれていません。',
},
DESCRIPTIONS_DROPPED: {
one: '説明 {n} 件を破棄しました。ブックマークのモデルに該当する項目がありません。',
other: '説明 {n} 件を破棄しました。ブックマークのモデルに該当する項目がありません。',
},
FAVICONS_IGNORED: {
one: 'ファビコン {n} 件を無視しました。ブックマーク API はファビコンを設定できません。',
other: 'ファビコン {n} 件を無視しました。ブックマーク API はファビコンを設定できません。',
},
INVALID_DATE: {
one: '読み取れない日付 {n} 件を空欄にしました。',
other: '読み取れない日付 {n} 件を空欄にしました。',
},
MISSING_URL: {
one: 'アドレスのない項目 {n} 件をスキップしました。',
other: 'アドレスのない項目 {n} 件をスキップしました。',
},
NEWER_VERSION: {
one: 'このファイルは新しいバージョンで作成されています。可能な範囲で読み込みます。',
other: 'このファイルは新しいバージョンで作成されています。可能な範囲で読み込みます。',
},
EMPTY_TITLE: {
one: 'タイトルのないブックマークが {n} 件あり、代わりにアドレスを表示します。',
other: 'タイトルのないブックマークが {n} 件あり、代わりにアドレスを表示します。',
},
},
errors: {
NOT_NETSCAPE: 'ブックマークの HTML ファイルではないようです。',
+109 -9
View File
@@ -11,7 +11,8 @@ export default {
about: 'Giới thiệu',
busy: 'Đang có tiến trình nhập',
cancel: 'Hủy',
comingSoon: '{tab} sẽ có ở bản sau.',
dismiss: 'Đóng',
sections: 'Các mục',
},
popup: {
import: 'Nhập bookmark…',
@@ -22,6 +23,7 @@ export default {
import: {
dropHint: 'Kéo thả tệp bookmark hoặc bấm để chọn — .html, .json, .csv · tối đa {size}',
reading: 'Đang đọc {name}…',
preview: 'Xem trước',
folderName: 'Đã nhập {date}',
start: 'Nhập {n} bookmark',
backingUp:
@@ -58,7 +60,9 @@ export default {
replace: 'Thay thế toàn bộ',
},
warnings: {
title: '{n} cảnh báo',
// Tiếng Việt chỉ có một dạng số, nhưng vẫn phải mang đủ hai khóa
// (docs/07 §5) để phép kiểm tra `satisfies Dict` còn ý nghĩa.
title: { one: '{n} cảnh báo', other: '{n} cảnh báo' },
},
},
export: {
@@ -98,6 +102,10 @@ export default {
collapseAll: 'Thu gọn tất cả',
rename: 'Đổi tên',
open: 'Mở',
copyUrl: 'Sao chép liên kết',
unsafeUrl: 'Địa chỉ này dùng lược đồ mà BookmarkMagic sẽ không mở.',
copied: 'Đã sao chép liên kết',
copyFailed: 'Không sao chép được liên kết.',
moveTo: 'Chuyển tới…',
moveToBody: 'Chuyển "{title}" vào thư mục nào?',
noMoveTargets: 'Không có thư mục nào khác.',
@@ -115,14 +123,106 @@ export default {
keepFirstTitle: 'Xóa các bản trùng?',
keepFirstBody: 'Giữ bản đầu tiên của mỗi liên kết và xóa {n} bản còn lại? Không thể hoàn tác.',
},
settings: {
autosave: 'Thay đổi được lưu ngay khi bạn chỉnh.',
language: 'Ngôn ngữ',
languageNote: 'Chỉ áp dụng cho tiện ích này, không đổi ngôn ngữ trình duyệt.',
localeAuto: 'Tự động (theo trình duyệt)',
lang: {
// Tên bản ngữ, cố ý giữ giống hệt nhau ở cả ba từ điển.
en: 'English',
vi: 'Tiếng Việt',
ja: '日本語',
},
theme: 'Giao diện',
themes: {
system: 'Theo hệ thống',
light: 'Sáng',
dark: 'Tối',
},
defaultExportFormat: 'Định dạng xuất mặc định',
defaultExportFormatNote: 'Được chọn sẵn khi bạn mở thẻ Xuất.',
defaultImportMode: 'Chế độ nhập mặc định',
defaultImportModeNote: 'Được chọn sẵn khi bạn mở thẻ Nhập.',
csvDelimiter: 'Ký tự phân cách CSV',
csvDelimiterNote: 'Dùng dấu chấm phẩy nếu bảng tính của bạn cần.',
markdownStyle: 'Bố cục Markdown',
markdownStyleNote: 'Cách sắp xếp thư mục trong tệp Markdown xuất ra.',
saved: 'Đã lưu cài đặt',
saveFailed: 'Không thể lưu cài đặt của bạn.',
reset: 'Khôi phục mặc định',
resetTitle: 'Khôi phục toàn bộ cài đặt?',
resetBody:
'Ngôn ngữ, giao diện và mọi lựa chọn mặc định sẽ trở về ban đầu. Bookmark của bạn không bị đụng tới.',
resetConfirm: 'Khôi phục',
resetDone: 'Đã khôi phục cài đặt mặc định',
},
about: {
tagline:
'Nhập, xuất và chỉnh sửa bookmark giữa các trình duyệt — ngoại tuyến, không tài khoản, không đám mây. Dữ liệu của bạn không bao giờ rời khỏi máy.',
version: 'Phiên bản {version}',
links: 'Liên kết',
repo: 'Kho mã trên GitHub',
issues: 'Báo lỗi',
changelog: 'Bản phát hành và nhật ký thay đổi',
thirdParty: 'Thư viện bên thứ ba: Không có',
thirdPartyNote: 'BookmarkMagic không đi kèm bất kỳ thư viện chạy nào.',
donate: 'Ủng hộ dự án',
donateNote: 'Hoàn toàn tự nguyện — BookmarkMagic vẫn là phần mềm tự do.',
legal: 'Pháp lý',
accepted: 'Đã chấp nhận điều khoản ngày {date} · phiên bản {version}',
acceptedUndated: 'Đã chấp nhận điều khoản · phiên bản {version}',
notAccepted: 'Bạn chưa chấp nhận các điều khoản pháp lý.',
},
legal: {
title: 'Trước khi bắt đầu',
summary:
'BookmarkMagic chạy hoàn toàn trên máy của bạn. Tiện ích không có máy chủ, không gửi yêu cầu mạng và không thu thập gì cả — bookmark và cài đặt của bạn không bao giờ rời khỏi trình duyệt này. Đây là phần mềm tự do theo giấy phép GPL-3.0 và không kèm bảo hành dưới bất kỳ hình thức nào. Các thao tác bookmark sẽ thay đổi dữ liệu trình duyệt, và chế độ "Thay thế toàn bộ" sẽ xóa bookmark hiện tại, nên hãy tự giữ bản sao lưu cho những gì bạn cần.',
updatedTitle: 'Các điều khoản đã được cập nhật',
updatedBody: 'Những tài liệu này đã thay đổi kể từ lần bạn chấp nhận. Hãy đọc lại để tiếp tục.',
documents: 'Tài liệu',
eula: 'Thỏa thuận cấp phép người dùng cuối',
license: 'Giấy phép (GPL-3.0)',
disclaimer: 'Tuyên bố miễn trừ',
privacy: 'Chính sách quyền riêng tư',
englishNote: 'Các tài liệu có hiệu lực pháp lý được viết bằng tiếng Anh.',
accept: 'Tôi đã đọc và chấp nhận các điều khoản trên',
continue: 'Chấp nhận & tiếp tục',
close: 'Đóng thẻ',
closeManually: 'Bạn có thể đóng thẻ này ngay bây giờ.',
saveFailed:
'Không thể lưu việc chấp nhận của bạn, nên chưa có gì được ghi lại. Hãy kiểm tra xem trình duyệt có cho phép tiện ích lưu trữ hay không, rồi thử lại.',
blocked: 'Hãy chấp nhận điều khoản để dùng các thẻ Nhập, Xuất và Chỉnh sửa.',
},
warnings: {
NO_BOOKMARKS: 'Tệp này không chứa bookmark nào.',
DESCRIPTIONS_DROPPED: 'Đã bỏ {n} phần mô tả — mô hình bookmark không có chỗ cho chúng.',
FAVICONS_IGNORED: 'Đã bỏ qua {n} favicon — API bookmark không thể đặt favicon.',
INVALID_DATE: 'Đã để trống {n} ngày không đọc được.',
MISSING_URL: 'Đã bỏ qua {n} mục không có địa chỉ.',
NEWER_VERSION: 'Tệp này được tạo bởi phiên bản mới hơn — đang đọc ở mức tốt nhất có thể.',
EMPTY_TITLE: '{n} bookmark không có tiêu đề; địa chỉ được hiển thị thay thế.',
NO_BOOKMARKS: {
one: 'Tệp này không chứa bookmark nào.',
other: 'Tệp này không chứa bookmark nào.',
},
DESCRIPTIONS_DROPPED: {
one: 'Đã bỏ {n} phần mô tả — mô hình bookmark không có chỗ cho chúng.',
other: 'Đã bỏ {n} phần mô tả — mô hình bookmark không có chỗ cho chúng.',
},
FAVICONS_IGNORED: {
one: 'Đã bỏ qua {n} favicon — API bookmark không thể đặt favicon.',
other: 'Đã bỏ qua {n} favicon — API bookmark không thể đặt favicon.',
},
INVALID_DATE: {
one: 'Đã để trống {n} ngày không đọc được.',
other: 'Đã để trống {n} ngày không đọc được.',
},
MISSING_URL: {
one: 'Đã bỏ qua {n} mục không có địa chỉ.',
other: 'Đã bỏ qua {n} mục không có địa chỉ.',
},
NEWER_VERSION: {
one: 'Tệp này được tạo bởi phiên bản mới hơn — đang đọc ở mức tốt nhất có thể.',
other: 'Tệp này được tạo bởi phiên bản mới hơn — đang đọc ở mức tốt nhất có thể.',
},
EMPTY_TITLE: {
one: '{n} bookmark không có tiêu đề; địa chỉ được hiển thị thay thế.',
other: '{n} bookmark không có tiêu đề; địa chỉ được hiển thị thay thế.',
},
},
errors: {
NOT_NETSCAPE: 'Đây có vẻ không phải tệp HTML bookmark.',
+5 -3
View File
@@ -8,6 +8,7 @@
* picker resolving, or by the user explicitly confirming the fallback
* download (docs/03 §1 step 6b).
*/
import { getGeneratorVersion } from '../browser/app-info';
import { clearRoots, getRootChildren, getRoots, toBookmarkNodes } from '../browser/bookmarks';
import {
isPickerAvailable,
@@ -37,8 +38,6 @@ const PARSERS = {
csv: parseCsv,
} as const;
const APP_VERSION = '0.1.0';
export interface PreparedImport {
result: ParseResult;
/** Bookmarks in the file whose URL already exists in the browser. */
@@ -160,7 +159,10 @@ export async function proveBackup(
): Promise<void> {
let content: string;
try {
content = serializeBmJson(snapshot, { version: APP_VERSION, exportedAt: now.toISOString() });
content = serializeBmJson(snapshot, {
version: getGeneratorVersion(),
exportedAt: now.toISOString(),
});
} catch (cause) {
throw new BmBackupError(
'BACKUP_SERIALIZE_FAILED',
+53
View File
@@ -0,0 +1,53 @@
/**
* Every outbound URL the product shows — docs/14 §4, docs/06 §3.5.
*
* Purpose: one place for the repo, legal and donate links, so the About tab and
* the Legal Gate cannot drift apart.
* Inputs: none — compile-time literals.
* Guarantees: no requests are made from here. These are hrefs the user chooses
* to follow; the extension itself stays offline (docs/09 §1).
*
* They are rendered as `<a target="_blank" rel="noopener noreferrer">`, unlike
* bookmark URLs, which docs/09 T3 forbids putting in an href and which #edit
* opens through `tabs.create` instead. Two mechanisms for two trust classes:
* these are literals in this file, those are untrusted data from a user's
* import file. Do not "harmonize" them.
*/
export const REPO_URL = 'https://github.com/poli0981/bookmarkmagic';
export const ISSUES_URL = `${REPO_URL}/issues`;
export const CHANGELOG_URL = `${REPO_URL}/blob/main/CHANGELOG.md`;
export interface LabelledLink {
labelKey: string;
url: string;
}
/**
* The four documents the gate and About link to (docs/14 §2).
*
* `blob/main/` and not a pinned tag on purpose: the gate asks the user to
* accept the *current* documents, and LEGAL_VERSION is the re-consent
* mechanism. Pinning would show terms that are no longer the ones in force.
*/
export const LEGAL_URLS: readonly LabelledLink[] = [
{ labelKey: 'legal.eula', url: `${REPO_URL}/blob/main/legal/EULA.md` },
{ labelKey: 'legal.license', url: `${REPO_URL}/blob/main/LICENSE` },
{ labelKey: 'legal.disclaimer', url: `${REPO_URL}/blob/main/legal/DISCLAIMER.md` },
{ labelKey: 'legal.privacy', url: `${REPO_URL}/blob/main/legal/PRIVACY.md` },
];
/**
* Donation platforms, from `.github/FUNDING.yml` (docs/14 §5).
*
* Labels are literals rather than i18n keys: these are brand names, which
* docs/07 §4 leaves untranslated. Only the section heading is localized.
*/
export const DONATE_LINKS: readonly { label: string; url: string }[] = [
{ label: 'GitHub Sponsors', url: 'https://github.com/sponsors/poli0981' },
{ label: 'Ko-fi', url: 'https://ko-fi.com/skullmute' },
{ label: 'Buy Me a Coffee', url: 'https://www.buymeacoffee.com/skullmute' },
{ label: 'Patreon', url: 'https://www.patreon.com/skullmute' },
{ label: 'PayPal', url: 'https://paypal.me/DungDang212' },
];
+76
View File
@@ -0,0 +1,76 @@
/**
* The choices each Settings row offers — docs/06 §3.4.
*
* Purpose: keep the six option tables out of the component so they can be
* asserted against the storage allow-lists, and give `<select>` handlers a
* way to narrow a raw string without an unexplained cast.
* Inputs: none — static tables plus one pure narrowing helper.
* Guarantees: pure. Lives in `settings/` rather than `core/` because it takes
* its types from `browser/storage.ts`, which `core/` may not touch
* (docs/02 §3 rule 1).
*/
import type { ExportFormat, ImportMode, ThemePreference } from '../browser/storage';
import type { CsvDelimiter } from '../core/serialize/csv';
import type { MarkdownStyle } from '../core/serialize/markdown';
import type { Locale } from '../i18n/resolve-locale';
export interface SettingChoice<T extends string> {
value: T;
/** Dotted i18n path — resolved at render time so it follows the locale. */
labelKey: string;
}
/** `'auto'` is a first-class option: it is what `DEFAULT_SETTINGS.locale` is. */
export const LOCALE_CHOICES: readonly SettingChoice<Locale | 'auto'>[] = [
{ value: 'auto', labelKey: 'settings.localeAuto' },
{ value: 'en', labelKey: 'settings.lang.en' },
{ value: 'vi', labelKey: 'settings.lang.vi' },
{ value: 'ja', labelKey: 'settings.lang.ja' },
];
export const THEME_CHOICES: readonly SettingChoice<ThemePreference>[] = [
{ value: 'system', labelKey: 'settings.themes.system' },
{ value: 'light', labelKey: 'settings.themes.light' },
{ value: 'dark', labelKey: 'settings.themes.dark' },
];
// The next four reuse the Export/Import tabs' own keys rather than inventing
// parallel wording. That is ~14 keys × 3 locales not written, and it makes it
// impossible for #settings and #export to describe the same choice differently.
export const EXPORT_FORMAT_CHOICES: readonly SettingChoice<ExportFormat>[] = [
{ value: 'netscape-html', labelKey: 'export.formats.netscape-html.name' },
{ value: 'bm-json', labelKey: 'export.formats.bm-json.name' },
{ value: 'csv', labelKey: 'export.formats.csv.name' },
{ value: 'markdown', labelKey: 'export.formats.markdown.name' },
];
export const IMPORT_MODE_CHOICES: readonly SettingChoice<ImportMode>[] = [
{ value: 'new-folder', labelKey: 'import.mode.newFolder' },
{ value: 'merge', labelKey: 'import.mode.merge' },
{ value: 'replace', labelKey: 'import.mode.replace' },
];
export const CSV_DELIMITER_CHOICES: readonly SettingChoice<CsvDelimiter>[] = [
{ value: ',', labelKey: 'export.comma' },
{ value: ';', labelKey: 'export.semicolon' },
];
export const MARKDOWN_STYLE_CHOICES: readonly SettingChoice<MarkdownStyle>[] = [
{ value: 'nested', labelKey: 'export.nested' },
{ value: 'flat', labelKey: 'export.flat' },
];
/**
* Narrow a raw control value against a choice table.
*
* Exists so `<select>` handlers never need `as SomeUnion`, which docs/10 §2
* would require a `// SAFETY:` comment for. Returns `undefined` for anything
* not in the table; callers must bail before building a settings patch, since
* `exactOptionalPropertyTypes` rejects an explicit `undefined` in the patch.
*/
export function parseChoice<T extends string>(
raw: string,
choices: readonly SettingChoice<T>[],
): T | undefined {
return choices.find((choice) => choice.value === raw)?.value;
}
+9 -1
View File
@@ -32,7 +32,15 @@ export type ImportState =
| { kind: 'writing'; filename: string; progress: WriteProgress }
| { kind: 'done'; filename: string; created: number; plan: ImportPlan }
| { kind: 'cancelled'; filename: string; created: number }
| { kind: 'error'; filename: string; message: string; detail: string | undefined };
/**
* `messageKey` is a dotted i18n path, NOT a resolved string.
*
* `t()` is only reactive where it is called, and this state outlives the
* component; storing the translated sentence froze it in whatever language
* was active when the error happened, so switching language left the error
* message behind in the old one.
*/
| { kind: 'error'; filename: string; messageKey: string; detail: string | undefined };
let state = $state<ImportState>({ kind: 'idle' });
let options = $state<ImportOptionsState>({ mode: 'new-folder', dedupe: true });
+118
View File
@@ -0,0 +1,118 @@
/**
* First-run legal acceptance — docs/14 §2.
*
* Purpose: decide whether the gate is required, and record acceptance.
* Inputs: `chrome.storage.local` via `browser/storage.ts`.
* Guarantees: never throws and never rejects — a storage failure fails CLOSED
* (gate shown), and `acceptLegal` returns an outcome instead of rejecting.
* Acceptance is only reflected in state AFTER the write resolves.
*/
import { type LegalAcceptance, readLegal, writeLegal } from '../browser/storage';
import { LEGAL_VERSION } from '../core/limits';
import type { Route } from './route.svelte';
import type { SaveOutcome } from './settings.svelte';
export type LegalStatus =
| { kind: 'loading' }
| { kind: 'accepted'; acceptance: LegalAcceptance }
/**
* `previous` carries the superseded record on the `updated` path. Without it
* the About tab would tell a user who accepted v1 that they have never
* accepted anything, the moment LEGAL_VERSION is bumped to 2.
*/
| { kind: 'required'; reason: 'first-run' | 'updated'; previous?: LegalAcceptance };
/**
* The three routes the gate blocks.
*
* Normative and stated identically in docs/03 §4, docs/14 §2 and the docs/15
* decision log: `#settings` and `#about` stay reachable, `#about` so the linked
* documents can be read before accepting and `#settings` so a VI/JA user can
* switch language first — which is why the gate carries no switcher of its own.
*/
const GATED_ROUTES: readonly Route[] = Object.freeze(['import', 'export', 'edit']);
const UNGATED: readonly Route[] = Object.freeze([]);
let status = $state<LegalStatus>({ kind: 'loading' });
/**
* Pure gate decision, so the rule is testable without touching storage.
*
* A stored version GREATER than the current one still counts as accepted: it
* means the user ran a newer build, and re-gating them on a downgrade would be
* noise, not consent.
*/
export function decideLegalStatus(
acceptance: LegalAcceptance | null,
currentVersion: number,
): LegalStatus {
if (acceptance === null) return { kind: 'required', reason: 'first-run' };
if (acceptance.acceptedVersion < currentVersion) {
return { kind: 'required', reason: 'updated', previous: acceptance };
}
return { kind: 'accepted', acceptance };
}
export function getLegalStatus(): LegalStatus {
return status;
}
export function isGateRequired(): boolean {
return status.kind === 'required';
}
/**
* The most recent acceptance on record, current or superseded.
*
* About renders this, so it must survive a `LEGAL_VERSION` bump — the user did
* accept the older terms, and saying otherwise is simply false.
*/
export function getAcceptance(): LegalAcceptance | undefined {
if (status.kind === 'accepted') return status.acceptance;
if (status.kind === 'required') return status.previous;
return undefined;
}
/** `[]` unless the gate is up. Never `undefined`, so the TabBar prop is simple. */
export function getBlockedRoutes(): readonly Route[] {
return status.kind === 'required' ? GATED_ROUTES : UNGATED;
}
export function isGatedRoute(route: Route): boolean {
return GATED_ROUTES.includes(route);
}
/**
* Read the stored acceptance. Call once per page, before the first render.
*
* `readLegal` already swallows storage failures and returns null, so an
* unreadable store lands on `required`. That is the correct direction: showing
* the gate to someone who accepted is recoverable in one click; skipping it for
* someone who has not is not recoverable at all.
*/
export async function loadLegal(): Promise<void> {
status = decideLegalStatus(await readLegal(), LEGAL_VERSION);
}
/**
* Record acceptance.
*
* The ordering is the whole point: write, await, and flip to `accepted` ONLY
* once the write resolves. Dismissing optimistically would leave the user
* accepted in the UI and unaccepted on disk, so the gate would silently
* reappear on the next launch with no explanation.
*
* @param nowIso supplied by the caller so this module stays free of ambient
* time, matching the discipline `browser/storage.ts` set up.
*/
export async function acceptLegal(nowIso: string): Promise<SaveOutcome> {
try {
await writeLegal(LEGAL_VERSION, nowIso);
} catch (err) {
// Returned, not thrown: a rejection here would need a .catch() at every
// call site, and one miss is an unhandled rejection with the gate stuck.
return { ok: false, ...(err instanceof Error && { detail: err.message }) };
}
status = { kind: 'accepted', acceptance: { acceptedVersion: LEGAL_VERSION, acceptedAt: nowIso } };
return { ok: true };
}
+111 -15
View File
@@ -1,9 +1,13 @@
/**
* Persisted settings — docs/03 §4.
*
* Writes are debounced 200 ms so dragging a control does not hammer storage.
* Theme is applied to <html data-theme> here, because that is the one place
* that knows both the preference and when it changed.
* Purpose: the single source of truth for locale, theme and the per-tab
* defaults, plus the only path that writes them to storage.
* Inputs: `updateSettings` patches from the Settings tab and header controls.
* Guarantees: writes are debounced 200 ms; the returned promise resolves when
* that write has actually *settled*, and never rejects — so UI feedback can
* report what happened instead of guessing. Theme and locale apply
* synchronously, before the write is even scheduled.
*/
import { browser } from 'wxt/browser';
import {
@@ -13,14 +17,22 @@ import {
type ThemePreference,
writeSettings,
} from '../browser/storage';
import { setLocale } from '../i18n/index.svelte';
import { getLocale, setLocale } from '../i18n/index.svelte';
import { resolveLocale } from '../i18n/resolve-locale';
const SAVE_DEBOUNCE_MS = 200;
let settings = $state<Settings>({ ...DEFAULT_SETTINGS });
/** What a persistence attempt actually did. Never thrown, always returned. */
export interface SaveOutcome {
ok: boolean;
detail?: string;
}
const settings = $state<Settings>({ ...DEFAULT_SETTINGS });
let loaded = $state(false);
let saveTimer: ReturnType<typeof setTimeout> | undefined;
/** Everyone who called `updateSettings` since the last write shares this. */
let pending: { promise: Promise<SaveOutcome>; resolve: (outcome: SaveOutcome) => void } | undefined;
export function getSettings(): Settings {
return settings;
@@ -32,37 +44,107 @@ export function isSettingsLoaded(): boolean {
/** Read persisted settings and apply locale + theme. Call once per page. */
export async function loadSettings(): Promise<void> {
settings = await readSettings();
Object.assign(settings, await readSettings());
applyLocale();
applyTheme(settings.theme);
loaded = true;
}
export function updateSettings(patch: Partial<Settings>): void {
settings = { ...settings, ...patch };
/**
* Apply a patch now, persist it shortly.
*
* Returns the outcome of the resulting write rather than firing and forgetting,
* so the Settings tab's "Saved" toast cannot claim a persistence that failed.
*/
export function updateSettings(patch: Partial<Settings>): Promise<SaveOutcome> {
// Mutated in place, never replaced. A replacement would strand any component
// that captured `getSettings()` into a local, and four components read this.
Object.assign(settings, patch);
if (patch.theme !== undefined) applyTheme(patch.theme);
if (patch.locale !== undefined) applyLocale();
scheduleSave();
return scheduleSave();
}
export async function resetSettings(): Promise<void> {
settings = { ...DEFAULT_SETTINGS };
/**
* Restore every documented default and persist immediately.
*
* The pending debounced write is cancelled rather than allowed to fire first —
* otherwise a reset issued within 200 ms of a change writes twice, and the
* first write persists values the user just discarded.
*/
export function resetSettings(): Promise<SaveOutcome> {
if (saveTimer !== undefined) clearTimeout(saveTimer);
saveTimer = undefined;
Object.assign(settings, DEFAULT_SETTINGS);
applyLocale();
applyTheme(settings.theme);
await writeSettings(settings);
return flushNow();
}
function scheduleSave(): void {
/**
* Write any pending change immediately.
*
* Called on `visibilitychange` → hidden, which fires on tab close, navigation
* and backgrounding. It shrinks the window in which a just-made change is lost
* from 200 ms to roughly nothing — it does not make it zero, because an async
* write started while the document is hidden is not guaranteed to finish.
*/
export function flushSettings(): Promise<SaveOutcome> {
if (saveTimer === undefined && pending === undefined) return Promise.resolve({ ok: true });
return flushNow();
}
function scheduleSave(): Promise<SaveOutcome> {
if (saveTimer !== undefined) clearTimeout(saveTimer);
// Rapid changes coalesce onto one promise, so every caller awaiting a save
// learns the outcome of the single write that actually happened.
if (pending === undefined) {
let resolve!: (outcome: SaveOutcome) => void;
const promise = new Promise<SaveOutcome>((r) => {
resolve = r;
});
pending = { promise, resolve };
}
saveTimer = setTimeout(() => {
saveTimer = undefined;
void writeSettings(settings);
void flushNow();
}, SAVE_DEBOUNCE_MS);
return pending.promise;
}
/** Write now and settle whoever is waiting on the coalesced promise. */
async function flushNow(): Promise<SaveOutcome> {
if (saveTimer !== undefined) clearTimeout(saveTimer);
saveTimer = undefined;
const waiting = pending;
pending = undefined;
const outcome = await save();
waiting?.resolve(outcome);
return outcome;
}
async function save(): Promise<SaveOutcome> {
try {
// $state proxies are not structured-cloneable, and chrome.storage.local.set
// clones its argument — passing the proxy straight through throws
// DataCloneError in a real browser. Settings is flat primitives, so a
// spread is a provably sufficient snapshot.
await writeSettings({ ...settings });
return { ok: true };
} catch (err) {
// Conditional spread, not `detail: undefined` — exactOptionalPropertyTypes
// makes an explicit undefined a type error (docs/10 §2).
return { ok: false, ...(err instanceof Error && { detail: err.message }) };
}
}
function applyLocale(): void {
if (settings.locale !== 'auto') {
setLocale(settings.locale);
applyDocumentLanguage();
return;
}
// A failing i18n lookup must not stop settings from loading — fall back to
@@ -74,6 +156,20 @@ function applyLocale(): void {
uiLanguage = 'en';
}
setLocale(resolveLocale(uiLanguage));
applyDocumentLanguage();
}
/**
* Keep `<html lang>` in step with the UI language.
*
* Both entrypoint documents ship `lang="en"`, so without this a screen reader
* reads Vietnamese and Japanese text with an English voice and pronunciation
* rules — the strings change and the announced language does not.
*/
function applyDocumentLanguage(): void {
const root = globalThis.document?.documentElement;
if (root === undefined) return;
root.lang = getLocale();
}
/**
+91
View File
@@ -0,0 +1,91 @@
/**
* Transient status messages — docs/06 §4 (queue, auto-dismiss 4 s, ARIA status).
*
* Purpose: one place that owns toast state AND its timers.
* Inputs: `pushToast` calls from anywhere in the Manager.
* Guarantees: exactly one toast is visible at a time; a timer can only ever
* dismiss the item that started it; nothing here touches the DOM, so a fired
* timer is harmless even when no `<Toast>` is rendered.
*
* The store owns the timers rather than the component because `<Toast>` mounts
* once at the App root while the route chain below it unmounts on every
* navigation. Component-owned timers would leak by construction; this way there
* is nothing to clean up.
*/
export type ToastTone = 'success' | 'danger' | 'info';
export interface ToastItem {
id: string;
message: string;
tone: ToastTone;
}
const AUTO_DISMISS_MS = 4000;
/** Overflow drops the oldest *pending* item — never the one on screen. */
const MAX_QUEUED = 3;
let queue = $state<ToastItem[]>([]);
let timer: ReturnType<typeof setTimeout> | undefined;
let nextId = 0;
export function getVisibleToast(): ToastItem | undefined {
return queue[0];
}
export function pushToast(message: string, tone: ToastTone = 'info'): void {
const visible = queue[0];
// A repeat of what is already on screen restarts its timer instead of
// queueing a twin. One debounced settings save resolves one promise that may
// have several subscribers, and without this the user gets three identical
// "Settings saved" toasts in a row.
if (visible !== undefined && visible.message === message && visible.tone === tone) {
startTimer(visible.id);
return;
}
nextId += 1;
const item: ToastItem = { id: `toast-${nextId}`, message, tone };
if (queue.length >= MAX_QUEUED) queue = [...queue.slice(0, 1), ...queue.slice(2), item];
else queue = [...queue, item];
if (queue.length === 1) startTimer(item.id);
}
export function dismissToast(id: string): void {
if (queue[0]?.id !== id) return;
shift();
}
/** Test teardown — module state outlives a single `it()`. */
export function clearToasts(): void {
clearTimer();
queue = [];
nextId = 0;
}
function shift(): void {
clearTimer();
queue = queue.slice(1);
const next = queue[0];
if (next !== undefined) startTimer(next.id);
}
function startTimer(id: string): void {
clearTimer();
timer = setTimeout(() => {
timer = undefined;
// The identity check is what stops a user dismiss racing this timeout from
// shifting twice and flashing the next toast for a single frame.
if (queue[0]?.id !== id) return;
shift();
}, AUTO_DISMISS_MS);
}
function clearTimer(): void {
if (timer === undefined) return;
clearTimeout(timer);
timer = undefined;
}
+23 -6
View File
@@ -1,5 +1,10 @@
/* Design tokens — docs/06 §1. Theme via data-theme on <html>; default follows
prefers-color-scheme, manual override persisted in Settings. */
prefers-color-scheme, manual override persisted in Settings.
Every `*-fg`/`*` pair and every token used as TEXT clears 4.5:1 against both
--bg and --bg-raised, in both themes (docs/06 §5). The numbers are not a
matter of taste: tests/unit/styles/contrast.test.ts parses this file and
fails the build if any pair drops below. Re-run it after changing a colour. */
:root {
--bg: #ffffff;
@@ -9,9 +14,13 @@
--fg-muted: #5b6472;
--accent: #6d4aff; /* violet — "magic" identity */
--accent-fg: #ffffff;
--danger: #d8384a;
--success: #1f9d55;
--warn: #b7791f;
/* danger/success/warn are darker than an eyeball would pick, because all
three are used as text on --bg-raised: at the original values they measured
4.27, 3.26 and 3.40 against a 4.5 requirement. */
--danger: #ce3547;
--danger-fg: #ffffff;
--success: #198045;
--warn: #99651a;
--radius: 10px;
--radius-sm: 6px;
@@ -37,8 +46,13 @@
--border: #2b3039;
--fg: #e8eaee;
--fg-muted: #9aa3b0;
--accent: #8b6dff;
--accent: #8f72ff;
/* Dark mode lightens --accent for contrast against --bg, which drops white
ink on it under the 4.5:1 docs/06 §5 requires. --accent-fg must be
redefined alongside it, in the opposite direction. */
--accent-fg: #16181d;
--danger: #ff6b7d;
--danger-fg: #16181d;
--success: #3ecf8e;
--warn: #e2b93b;
}
@@ -50,8 +64,11 @@
--border: #2b3039;
--fg: #e8eaee;
--fg-muted: #9aa3b0;
--accent: #8b6dff;
--accent: #8f72ff;
/* Keep in step with the [data-theme='dark'] block above. */
--accent-fg: #16181d;
--danger: #ff6b7d;
--danger-fg: #16181d;
--success: #3ecf8e;
--warn: #e2b93b;
}
+69
View File
@@ -0,0 +1,69 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { copyToClipboard } from '@/lib/browser/clipboard';
/**
* The docs/09 T8 surface. jsdom provides no `navigator.clipboard`, so every
* case here installs one — which also exercises the "no clipboard at all" path
* that a non-secure context would take.
*/
function stubClipboard(impl: ((text: string) => Promise<void>) | undefined): string[] {
const written: string[] = [];
if (impl === undefined) {
Object.defineProperty(globalThis.navigator, 'clipboard', {
value: undefined,
configurable: true,
});
return written;
}
Object.defineProperty(globalThis.navigator, 'clipboard', {
value: {
writeText: async (text: string) => {
written.push(text);
await impl(text);
},
},
configurable: true,
});
return written;
}
afterEach(() => {
Reflect.deleteProperty(globalThis.navigator, 'clipboard');
vi.restoreAllMocks();
});
describe('copyToClipboard', () => {
it('writes the text and reports success', async () => {
const written = stubClipboard(async () => {});
expect(await copyToClipboard('https://example.com/')).toBe(true);
expect(written).toEqual(['https://example.com/']);
});
it('reports failure instead of throwing when the write rejects', async () => {
// The real one this guards: Chrome rejects with NotAllowedError
// ("Document is not focused") if the manager page lost focus between the
// click and the promise. The user gets a toast, not an unhandled rejection.
stubClipboard(async () => {
throw new DOMException('Document is not focused', 'NotAllowedError');
});
await expect(copyToClipboard('https://example.com/')).resolves.toBe(false);
});
it('reports failure when there is no clipboard API at all', async () => {
stubClipboard(undefined);
await expect(copyToClipboard('https://example.com/')).resolves.toBe(false);
});
it('never reads the clipboard', async () => {
// docs/09 T8 is explicit: write only. A readText call here would be a
// privacy regression that no other test would notice.
const readText = vi.fn();
Object.defineProperty(globalThis.navigator, 'clipboard', {
value: { writeText: async () => {}, readText },
configurable: true,
});
await copyToClipboard('https://example.com/');
expect(readText).not.toHaveBeenCalled();
});
});
+62
View File
@@ -0,0 +1,62 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fakeBrowser } from 'wxt/testing';
import { openBookmarkUrl } from '@/lib/browser/open-url';
/**
* The docs/09 T3 control: bookmark URLs come from someone's import file and are
* stored verbatim, so this allowlist is the only thing between a crafted
* `javascript:` bookmark and the browser acting on it. It had no test.
*/
let created: { url?: string }[] = [];
beforeEach(() => {
fakeBrowser.reset();
vi.restoreAllMocks();
created = [];
// fakeBrowser stubs tabs.* with "not implemented" throws.
vi.spyOn(fakeBrowser.tabs, 'create').mockImplementation(async (props) => {
created.push(props);
// SAFETY: the caller ignores the return value; only the recorded call
// matters, and building a full Tab here would assert nothing.
return {} as Awaited<ReturnType<typeof fakeBrowser.tabs.create>>;
});
});
describe('openBookmarkUrl', () => {
it.each([
'https://example.com/',
'http://example.com/path?q=1',
'https://example.com:8443/#frag',
])('opens %s', async (url) => {
expect(await openBookmarkUrl(url)).toBe(true);
expect(created).toEqual([{ url }]);
});
it.each([
['javascript:alert(1)', 'the classic bookmarklet payload'],
['data:text/html,<script>alert(1)</script>', 'inline document'],
['file:///etc/passwd', 'local file read'],
['chrome://settings', 'privileged browser page'],
['ftp://example.com/', 'not in the allowlist'],
['vbscript:msgbox(1)', 'legacy script scheme'],
])('refuses %s (%s)', async (url) => {
expect(await openBookmarkUrl(url)).toBe(false);
expect(created).toEqual([]);
});
it('refuses an unparseable URL without throwing', async () => {
for (const url of ['', 'not a url', '///', 'http://']) {
await expect(openBookmarkUrl(url)).resolves.toBe(false);
}
expect(created).toEqual([]);
});
it('is case-insensitive about the scheme, as the URL parser is', async () => {
// `new URL('JavaScript:…').protocol` normalizes to lowercase, so an
// attacker cannot dodge the allowlist by shouting.
expect(await openBookmarkUrl('JaVaScRiPt:alert(1)')).toBe(false);
expect(await openBookmarkUrl('HTTPS://example.com/')).toBe(true);
expect(created).toEqual([{ url: 'HTTPS://example.com/' }]);
});
});
+143
View File
@@ -0,0 +1,143 @@
import { describe, expect, it } from 'vitest';
import type { LiveNode } from '@/lib/browser/bookmarks';
import {
countDescendants,
extraCopyIds,
flattenTree,
isEditable,
resolveNewFolderParent,
toEditNode,
} from '@/lib/edit/edit-node';
import type { EditNode } from '@/lib/edit/patch-tree';
const BAR: EditNode = {
id: '1',
title: 'Bookmarks bar',
children: [
{
id: '10',
parentId: '1',
title: 'Docs',
children: [{ id: '11', parentId: '10', title: 'A', url: 'https://a.test/' }],
},
{ id: '12', parentId: '1', title: 'B', url: 'https://b.test/' },
],
};
const MANAGED: EditNode = { id: '2', title: 'Managed', unmodifiable: 'managed', children: [] };
const ROOTS: EditNode[] = [BAR, MANAGED];
describe('toEditNode', () => {
it('omits absent keys rather than setting them undefined', () => {
// exactOptionalPropertyTypes (docs/10 §2): an explicit undefined is a type
// error at every construction site, and `'url' in node` must stay reliable.
const live = { id: '5', title: 'Folder', children: [] } as LiveNode;
const node = toEditNode(live);
expect(Object.hasOwn(node, 'url')).toBe(false);
expect(Object.hasOwn(node, 'parentId')).toBe(false);
expect(Object.hasOwn(node, 'unmodifiable')).toBe(false);
});
it('gives folders children and bookmarks none, which is what folder tests rely on', () => {
const folder = toEditNode({ id: '5', title: 'F', children: [] } as LiveNode);
const link = toEditNode({ id: '6', title: 'L', url: 'https://x.test/' } as LiveNode);
expect(folder.children).toEqual([]);
expect(Object.hasOwn(link, 'children')).toBe(false);
});
it('recurses, preserving order', () => {
const live = {
id: '1',
title: 'root',
children: [
{ id: '2', parentId: '1', title: 'first', url: 'https://1.test/' },
{ id: '3', parentId: '1', title: 'second', children: [] },
],
} as LiveNode;
expect(toEditNode(live).children?.map((child) => child.id)).toEqual(['2', '3']);
});
it('carries unmodifiable through, since it gates every destructive affordance', () => {
const live = { id: '2', title: 'Managed', unmodifiable: 'managed', children: [] } as LiveNode;
expect(toEditNode(live).unmodifiable).toBe('managed');
});
});
describe('flattenTree', () => {
it('lists every node depth-first, parents before children', () => {
expect(flattenTree(ROOTS).map((node) => node.id)).toEqual(['1', '10', '11', '12', '2']);
});
it('handles an empty forest', () => {
expect(flattenTree([])).toEqual([]);
});
});
describe('isEditable', () => {
it('refuses the permanent roots', () => {
expect(isEditable(ROOTS, BAR)).toBe(false);
});
it('refuses policy-managed nodes', () => {
expect(isEditable(ROOTS, MANAGED)).toBe(false);
});
it('allows ordinary descendants', () => {
expect(isEditable(ROOTS, ROOTS[0]?.children?.[0] as EditNode)).toBe(true);
});
});
describe('resolveNewFolderParent', () => {
it('nests inside the focused folder', () => {
expect(resolveNewFolderParent(ROOTS, ROOTS[0]?.children?.[0])).toBe('10');
});
it('puts it beside a focused bookmark, not inside it', () => {
expect(resolveNewFolderParent(ROOTS, ROOTS[0]?.children?.[1])).toBe('1');
});
it('falls back to the first WRITABLE root when nothing is focused', () => {
// Using the focused node's parent unconditionally resolved a selected root
// to the synthetic root "0", which every create rejects.
expect(resolveNewFolderParent(ROOTS, undefined)).toBe('1');
expect(resolveNewFolderParent([MANAGED, BAR], undefined)).toBe('1');
});
it('returns undefined when every root is unmodifiable', () => {
expect(resolveNewFolderParent([MANAGED], undefined)).toBeUndefined();
});
it('treats a focused root as the target folder itself', () => {
expect(resolveNewFolderParent(ROOTS, BAR)).toBe('1');
});
it('falls back rather than targeting a focused UNMODIFIABLE folder', () => {
// A managed folder rejects every create, so returning its id made "New
// folder" silently do nothing whenever one happened to be selected.
expect(resolveNewFolderParent(ROOTS, MANAGED)).toBe('1');
});
});
describe('countDescendants', () => {
it('counts everything inside, at any depth', () => {
expect(countDescendants(BAR)).toBe(3);
});
it('is 0 for a bookmark and for nothing', () => {
expect(countDescendants(ROOTS[0]?.children?.[1])).toBe(0);
expect(countDescendants(undefined)).toBe(0);
});
});
describe('extraCopyIds', () => {
it('keeps the first of each group and names the rest', () => {
const groups = [
{ nodes: [{ id: 'a1' }, { id: 'a2' }, { id: 'a3' }] as EditNode[] },
{ nodes: [{ id: 'b1' }, { id: 'b2' }] as EditNode[] },
];
expect(extraCopyIds(groups)).toEqual(['a2', 'a3', 'b2']);
});
it('names nothing for a group of one', () => {
expect(extraCopyIds([{ nodes: [{ id: 'only' }] as EditNode[] }])).toEqual([]);
});
});
+100
View File
@@ -0,0 +1,100 @@
import { describe, expect, it } from 'vitest';
import en from '@/lib/i18n/locales/en';
import ja from '@/lib/i18n/locales/ja';
import vi from '@/lib/i18n/locales/vi';
/**
* Runtime companions to the `satisfies Dict` compile check (docs/07 §2).
*
* The compile check proves the *shape* matches. It is blind to what these
* assert: interpolation tokens drifting between locales, empty leaves, and the
* check itself being silently disabled by someone changing `satisfies` to `as`.
*/
type Node = { [key: string]: Node | string };
const LOCALES: [name: string, dict: Node][] = [
['vi', vi as Node],
['ja', ja as Node],
];
/** Every leaf as a dotted path → value. */
function flatten(node: Node, prefix = ''): Map<string, string> {
const out = new Map<string, string>();
for (const [key, value] of Object.entries(node)) {
const path = prefix === '' ? key : `${prefix}.${key}`;
if (typeof value === 'string') out.set(path, value);
else for (const [inner, text] of flatten(value, path)) out.set(inner, text);
}
return out;
}
/** `{token}` names, sorted, so two orderings of the same set compare equal. */
function tokens(text: string): string[] {
return [...text.matchAll(/\{(\w+)\}/gu)].map((match) => match[1] ?? '').sort();
}
/** Every branch node as a dotted path → its own key names. */
function branches(node: Node, prefix = ''): Map<string, string[]> {
const out = new Map<string, string[]>();
for (const [key, value] of Object.entries(node)) {
if (typeof value === 'string') continue;
const path = prefix === '' ? key : `${prefix}.${key}`;
out.set(path, Object.keys(value));
for (const [inner, keys] of branches(value, path)) out.set(inner, keys);
}
return out;
}
const english = flatten(en as Node);
describe('dictionary completeness', () => {
it.each(LOCALES)('%s has exactly the same key paths as en', (_name, dict) => {
expect([...flatten(dict).keys()].sort()).toEqual([...english.keys()].sort());
});
it.each(LOCALES)('%s uses the same interpolation tokens as en in every string', (_name, dict) => {
// `satisfies Dict` cannot see this: a translation that drops {total} from
// 'Importing… {done} / {total}' type-checks and renders a broken sentence.
const drift: string[] = [];
for (const [path, text] of flatten(dict)) {
const expected = tokens(english.get(path) ?? '');
const actual = tokens(text);
if (actual.join('|') !== expected.join('|')) {
drift.push(`${path}: expected {${expected.join('}, {')}}, got {${actual.join('}, {')}}`);
}
}
expect(drift).toEqual([]);
});
it.each([['en', en as Node], ...LOCALES])('%s has no empty leaves', (_name, dict) => {
const empty = [...flatten(dict)].filter(([, text]) => text.trim() === '').map(([path]) => path);
expect(empty).toEqual([]);
});
it('carries every plural key as { one, other } in all three locales', () => {
// docs/07 §5. VI/JA have one grammatical form and repeat the same string,
// but they must still carry both keys or the `satisfies Dict` shape check
// §2 relies on for completeness stops proving anything.
const pluralPaths = [...branches(en as Node)]
.filter(([, keys]) => keys.includes('one') && keys.includes('other'))
.map(([path]) => path);
expect(pluralPaths.length).toBeGreaterThan(0);
for (const [name, dict] of LOCALES) {
const leaves = flatten(dict);
for (const path of pluralPaths) {
expect(leaves.get(`${path}.one`), `${name}: ${path}.one`).toBeTypeOf('string');
expect(leaves.get(`${path}.other`), `${name}: ${path}.other`).toBeTypeOf('string');
}
}
});
it('gives every plural key exactly the two forms, and no stray siblings', () => {
const malformed = [...branches(en as Node)]
.filter(([, keys]) => keys.includes('one') || keys.includes('other'))
.filter(([, keys]) => keys.length !== 2)
.map(([path]) => path);
expect(malformed).toEqual([]);
});
});
+130
View File
@@ -0,0 +1,130 @@
import { afterEach, describe, expect, it } from 'vitest';
import { formatCount, formatDateTime, localeTag, selectPluralForm } from '@/lib/i18n/format';
import { dateTime, getLocale, num, setLocale, tPlural } from '@/lib/i18n/index.svelte';
afterEach(() => {
setLocale('en');
});
describe('localeTag', () => {
it('maps each locale onto the BCP 47 tag docs/07 §3 pins', () => {
expect(localeTag('en')).toBe('en-US');
expect(localeTag('vi')).toBe('vi-VN');
expect(localeTag('ja')).toBe('ja-JP');
});
});
describe('formatCount', () => {
it('groups thousands for English', () => {
expect(formatCount(1_234_567, 'en-US')).toBe('1,234,567');
});
it('groups thousands for vi/ja with a locale-appropriate separator', () => {
// Asserted structurally rather than glyph-for-glyph: ICU separator data can
// shift between Node releases, and a brittle assertion here would block an
// unrelated Node bump for no real gain.
expect(formatCount(1_234_567, 'vi-VN')).toMatch(/^1\D234\D567$/u);
expect(formatCount(1_234_567, 'ja-JP')).toMatch(/^1\D234\D567$/u);
expect(formatCount(1_234_567, 'vi-VN')).not.toBe(formatCount(1_234_567, 'en-US'));
});
it('keeps the cache keyed by tag — interleaved calls do not bleed', () => {
const en = formatCount(1_000, 'en-US');
const vi = formatCount(1_000, 'vi-VN');
expect(formatCount(1_000, 'en-US')).toBe(en);
expect(formatCount(1_000, 'vi-VN')).toBe(vi);
expect(en).not.toBe(vi);
});
it('leaves small numbers alone in every locale', () => {
expect(formatCount(0, 'en-US')).toBe('0');
expect(formatCount(42, 'ja-JP')).toBe('42');
});
});
describe('formatDateTime', () => {
it('renders a valid instant, differently per locale', () => {
const en = formatDateTime('2026-07-25T10:00:00.000Z', 'en-US');
const ja = formatDateTime('2026-07-25T10:00:00.000Z', 'ja-JP');
// Not an exact string: output is timezone-dependent and the suite does not
// pin TZ (doing so would change every existing date test's environment).
expect(en).toContain('2026');
expect(ja).toContain('2026');
expect(en).not.toBe(ja);
});
it('returns undefined instead of throwing on an unparseable date', () => {
// readLegal coerces a missing acceptedAt to '' (browser/storage.ts), and
// Intl.format(new Date('')) throws RangeError *inside a render*, which
// would blank the About tab. This is the guard against that.
expect(formatDateTime('', 'en-US')).toBeUndefined();
expect(formatDateTime('not-a-date', 'en-US')).toBeUndefined();
expect(() => formatDateTime('', 'ja-JP')).not.toThrow();
});
});
describe('selectPluralForm', () => {
it('distinguishes one from other in English', () => {
expect(selectPluralForm(1, 'en-US')).toBe('one');
expect(selectPluralForm(0, 'en-US')).toBe('other');
expect(selectPluralForm(2, 'en-US')).toBe('other');
});
it('always returns other for vi and ja, which have one grammatical form', () => {
for (const count of [0, 1, 2, 100]) {
expect(selectPluralForm(count, 'vi-VN')).toBe('other');
expect(selectPluralForm(count, 'ja-JP')).toBe('other');
}
});
});
describe('tPlural', () => {
it('picks the singular form and supplies a formatted {n}', () => {
setLocale('en');
expect(tPlural('warnings.INVALID_DATE', 1)).toBe('1 unreadable date was left blank.');
});
it('picks the plural form and groups the count', () => {
setLocale('en');
expect(tPlural('warnings.INVALID_DATE', 1234)).toBe('1,234 unreadable dates were left blank.');
});
it('resolves in vi and ja without falling back to English', () => {
for (const locale of ['vi', 'ja'] as const) {
setLocale(locale);
const text = tPlural('warnings.INVALID_DATE', 3);
expect(text).not.toBe('warnings.INVALID_DATE');
expect(text).not.toContain('unreadable');
expect(text).toContain('3');
}
});
it('returns the path itself for an unknown key rather than throwing', () => {
setLocale('en');
expect(tPlural('warnings.NOT_A_REAL_CODE', 2)).toBe('warnings.NOT_A_REAL_CODE');
});
});
describe('reactive wrappers', () => {
it('getLocale() reports the resolved locale, not the stored preference', () => {
// The preference (getSettings().locale) also carries 'auto'; this never
// does. Language controls must bind to the preference, not to this.
setLocale('ja');
expect(getLocale()).toBe('ja');
});
it('num() follows setLocale', () => {
setLocale('vi');
expect(num(1_234_567)).toBe(formatCount(1_234_567, 'vi-VN'));
setLocale('en');
expect(num(1_234_567)).toBe('1,234,567');
});
it('dateTime() follows setLocale and propagates the undefined guard', () => {
setLocale('ja');
expect(dateTime('2026-07-25T10:00:00.000Z')).toBe(
formatDateTime('2026-07-25T10:00:00.000Z', 'ja-JP'),
);
expect(dateTime('')).toBeUndefined();
});
});
+94
View File
@@ -0,0 +1,94 @@
import { existsSync } from 'node:fs';
import { basename, join } from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
import { getAppVersion } from '@/lib/browser/app-info';
import { setLocale, t } from '@/lib/i18n/index.svelte';
import type { Locale } from '@/lib/i18n/resolve-locale';
import { CHANGELOG_URL, DONATE_LINKS, ISSUES_URL, LEGAL_URLS, REPO_URL } from '@/lib/links';
const LOCALES: Locale[] = ['en', 'vi', 'ja'];
/** Vitest runs with cwd at the project root, which is where `legal/` lives. */
const REPO_ROOT = process.cwd();
afterEach(() => {
setLocale('en');
});
describe('outbound links', () => {
it('are all absolute https URLs', () => {
const urls = [
REPO_URL,
ISSUES_URL,
CHANGELOG_URL,
...LEGAL_URLS.map((link) => link.url),
...DONATE_LINKS.map((link) => link.url),
];
for (const url of urls) {
expect(() => new URL(url)).not.toThrow();
expect(new URL(url).protocol).toBe('https:');
}
});
it('points every legal link at a file that exists in the repo', () => {
// A rename would otherwise ship four dead links from inside a legal gate,
// and nothing else in the build would notice.
for (const link of LEGAL_URLS) {
const path = new URL(link.url).pathname.replace('/poli0981/bookmarkmagic/blob/main/', '');
expect(existsSync(join(REPO_ROOT, path)), `missing ${path}`).toBe(true);
expect(basename(path)).not.toBe('');
}
});
it('labels every legal link in all three locales', () => {
const missing: string[] = [];
for (const locale of LOCALES) {
setLocale(locale);
for (const link of LEGAL_URLS) {
if (t(link.labelKey) === link.labelKey) missing.push(`${locale}: ${link.labelKey}`);
}
}
expect(missing).toEqual([]);
});
it('lists exactly the four documents docs/14 §2 requires', () => {
expect(LEGAL_URLS.map((link) => link.labelKey)).toEqual([
'legal.eula',
'legal.license',
'legal.disclaimer',
'legal.privacy',
]);
});
it('lists all five funding handles from .github/FUNDING.yml (docs/14 §5)', () => {
expect(DONATE_LINKS).toHaveLength(5);
expect(DONATE_LINKS.map((link) => link.label)).toEqual([
'GitHub Sponsors',
'Ko-fi',
'Buy Me a Coffee',
'Patreon',
'PayPal',
]);
});
it('links a CHANGELOG.md that actually exists', () => {
// It pointed at /releases through Phase 4 because the file did not exist.
// Same check as the legal documents: a link from inside the product must
// not 404 because someone renamed or deleted the target.
expect(CHANGELOG_URL.endsWith('/blob/main/CHANGELOG.md')).toBe(true);
expect(existsSync(join(REPO_ROOT, 'CHANGELOG.md'))).toBe(true);
});
it('links a README the badges and install steps live in', () => {
expect(existsSync(join(REPO_ROOT, 'README.md'))).toBe(true);
});
});
describe('getAppVersion', () => {
it('returns an empty string rather than throwing when the manifest is unreadable', () => {
// fakeBrowser has no packaged manifest, so this exercises the fallback.
// A wrong-but-plausible version in a footer users quote in bug reports is
// worse than no version at all.
expect(() => getAppVersion()).not.toThrow();
expect(typeof getAppVersion()).toBe('string');
});
});
+90
View File
@@ -0,0 +1,90 @@
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
/**
* The permission list is the product's most load-bearing public claim: it is in
* the README, the privacy policy, the store listing's privacy tab, and
* CLAUDE.md's first hard rule. Until this file existed, nothing enforced it —
* a single added string in wxt.config.ts would have shipped silently.
*
* Read as text rather than imported, so the assertion cannot be satisfied by a
* value computed at build time; what ships is what is written here.
*/
const RAW = readFileSync(join(process.cwd(), 'wxt.config.ts'), 'utf8');
/**
* Comments stripped first. The file's own header says "No host_permissions, no
* content_scripts", so a naive substring check fails on the prose that promises
* the very thing it is checking.
*/
const CONFIG = RAW.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, '');
/** Anything that widens the extension's reach beyond bookmarks + storage. */
const FORBIDDEN_KEYS = [
'host_permissions',
'optional_permissions',
'optional_host_permissions',
'content_scripts',
'web_accessible_resources',
'externally_connectable',
'content_security_policy',
'declarative_net_request',
'devtools_page',
'chrome_url_overrides',
];
describe('manifest', () => {
it('declares the permissions array exactly once', () => {
// Two arrays (e.g. a browser-specific override) would mean this file only
// ever checks the first, which might not be the one that ships.
expect(CONFIG.match(/(?<![a-z_])permissions:/gi)?.length ?? 0).toBe(1);
});
it('builds the permissions array from string literals only', () => {
// Without this, a spread, an identifier or a `.concat()` tail would be
// dropped by the literal-harvesting regex below and the assertion would
// still pass while extra permissions shipped.
const match = CONFIG.match(/permissions:\s*\[([^\]]*)\]/);
const residue = (match?.[1] ?? '').replace(/'[^']*'|"[^"]*"|[\s,]/g, '');
expect(residue, 'permissions array contains non-literal entries').toBe('');
});
it('requests exactly ["bookmarks", "storage"]', () => {
const match = CONFIG.match(/permissions:\s*\[([^\]]*)\]/);
expect(match?.[1], 'no permissions array found in wxt.config.ts').toBeDefined();
const requested = [...(match?.[1] ?? '').matchAll(/'([^']+)'|"([^"]+)"/g)].map(
(entry) => entry[1] ?? entry[2],
);
// Adding one is a minor-version event that also requires updating docs
// 08/09/13 and the store privacy tab (docs/09 §4). Update this list last.
expect(requested).toEqual(['bookmarks', 'storage']);
});
it.each(FORBIDDEN_KEYS)('declares no %s', (key) => {
expect(CONFIG).not.toContain(key);
});
it('declares no background service worker', () => {
// docs/15 decision log, 2026-07-03: no background worker in v1. One would
// also change the store review posture.
expect(CONFIG).not.toMatch(/\bbackground\s*:/);
});
it('keeps the manifest at v3 by not overriding WXT’s default', () => {
// WXT emits manifest_version 3 for the chrome-mv3 target. An explicit
// downgrade here would be the only way to lose it.
expect(CONFIG).not.toMatch(/manifest_version\s*:\s*2/);
});
it('still points default_locale at the three shipped dictionaries', () => {
expect(CONFIG).toMatch(/default_locale:\s*'en'/);
for (const locale of ['en', 'vi', 'ja']) {
const path = join(process.cwd(), 'src/public/_locales', locale, 'messages.json');
const messages: unknown = JSON.parse(readFileSync(path, 'utf8'));
expect(messages, `${locale}/messages.json`).toHaveProperty('appName');
expect(messages, `${locale}/messages.json`).toHaveProperty('appDesc');
}
});
});
+86
View File
@@ -0,0 +1,86 @@
import { afterEach, describe, expect, it } from 'vitest';
import { DEFAULT_SETTINGS } from '@/lib/browser/storage';
import { setLocale, t } from '@/lib/i18n/index.svelte';
import type { Locale } from '@/lib/i18n/resolve-locale';
import {
CSV_DELIMITER_CHOICES,
EXPORT_FORMAT_CHOICES,
IMPORT_MODE_CHOICES,
LOCALE_CHOICES,
MARKDOWN_STYLE_CHOICES,
parseChoice,
type SettingChoice,
THEME_CHOICES,
} from '@/lib/settings/options';
const TABLES: [name: string, choices: readonly SettingChoice<string>[]][] = [
['LOCALE_CHOICES', LOCALE_CHOICES],
['THEME_CHOICES', THEME_CHOICES],
['EXPORT_FORMAT_CHOICES', EXPORT_FORMAT_CHOICES],
['IMPORT_MODE_CHOICES', IMPORT_MODE_CHOICES],
['CSV_DELIMITER_CHOICES', CSV_DELIMITER_CHOICES],
['MARKDOWN_STYLE_CHOICES', MARKDOWN_STYLE_CHOICES],
];
const LOCALES: Locale[] = ['en', 'vi', 'ja'];
afterEach(() => {
setLocale('en');
});
describe('choice labels', () => {
it.each(TABLES)('%s resolves every labelKey in all three locales', (_name, choices) => {
// t() falls back to the key path on a miss, so a typo renders as literal
// "settings.markdownStyle" in the UI and nothing else would catch it.
const missing: string[] = [];
for (const locale of LOCALES) {
setLocale(locale);
for (const choice of choices) {
if (t(choice.labelKey) === choice.labelKey) missing.push(`${locale}: ${choice.labelKey}`);
}
}
expect(missing).toEqual([]);
});
});
describe('choice values match the storage allow-lists', () => {
// coerceSettings in browser/storage.ts is the gatekeeper for what can be
// persisted. If a value can be stored but has no row, it is unreachable; if a
// row offers a value coerceSettings rejects, choosing it silently does
// nothing. Both are caught here.
it.each([
['locale', LOCALE_CHOICES, ['auto', 'en', 'vi', 'ja']],
['theme', THEME_CHOICES, ['system', 'light', 'dark']],
['defaultExportFormat', EXPORT_FORMAT_CHOICES, ['netscape-html', 'bm-json', 'csv', 'markdown']],
['defaultMergeMode', IMPORT_MODE_CHOICES, ['new-folder', 'merge', 'replace']],
['csvDelimiter', CSV_DELIMITER_CHOICES, [',', ';']],
['markdownStyle', MARKDOWN_STYLE_CHOICES, ['nested', 'flat']],
] as [string, readonly SettingChoice<string>[], string[]][])('%s', (_key, choices, allowed) => {
expect(choices.map((choice) => choice.value).sort()).toEqual([...allowed].sort());
});
it('offers a row for every field the default settings carry', () => {
// Six persisted fields, six rows (docs/06 §3.4 as amended in Phase 4).
expect(Object.keys(DEFAULT_SETTINGS).sort()).toEqual([
'csvDelimiter',
'defaultExportFormat',
'defaultMergeMode',
'locale',
'markdownStyle',
'theme',
]);
});
});
describe('parseChoice', () => {
it('returns the narrowed value for a known option', () => {
expect(parseChoice('dark', THEME_CHOICES)).toBe('dark');
expect(parseChoice(';', CSV_DELIMITER_CHOICES)).toBe(';');
});
it('returns undefined for anything not in the table', () => {
expect(parseChoice('klingon', LOCALE_CHOICES)).toBeUndefined();
expect(parseChoice('', CSV_DELIMITER_CHOICES)).toBeUndefined();
expect(parseChoice('DARK', MARKDOWN_STYLE_CHOICES)).toBeUndefined();
});
});
+161
View File
@@ -0,0 +1,161 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fakeBrowser } from 'wxt/testing';
import { LEGAL_VERSION } from '@/lib/core/limits';
import {
acceptLegal,
decideLegalStatus,
getAcceptance,
getBlockedRoutes,
getLegalStatus,
isGatedRoute,
isGateRequired,
loadLegal,
} from '@/lib/stores/legal.svelte';
const ACCEPTED_AT = '2026-07-25T10:00:00.000Z';
beforeEach(() => {
fakeBrowser.reset();
// reset() clears data but leaves spies, so a rejecting storage.local.set
// would otherwise leak into every later test in this file.
vi.restoreAllMocks();
});
describe('decideLegalStatus', () => {
it('gates a fresh profile as first-run', () => {
expect(decideLegalStatus(null, 1)).toEqual({ kind: 'required', reason: 'first-run' });
});
it('gates an older acceptance as an update, KEEPING the superseded record', () => {
// Without `previous`, the About tab tells a user who accepted v1 that they
// have never accepted anything the moment LEGAL_VERSION becomes 2.
const previous = { acceptedVersion: 0, acceptedAt: ACCEPTED_AT };
expect(decideLegalStatus(previous, 1)).toEqual({
kind: 'required',
reason: 'updated',
previous,
});
});
it('accepts a matching version', () => {
const acceptance = { acceptedVersion: 1, acceptedAt: ACCEPTED_AT };
expect(decideLegalStatus(acceptance, 1)).toEqual({ kind: 'accepted', acceptance });
});
it('accepts a version NEWER than the current one', () => {
// The user ran a newer build. Re-gating them on a downgrade would be noise,
// not consent.
const acceptance = { acceptedVersion: 2, acceptedAt: ACCEPTED_AT };
expect(decideLegalStatus(acceptance, 1)).toEqual({ kind: 'accepted', acceptance });
});
});
describe('blocked routes', () => {
it('names exactly the three routes docs/14 §2 blocks', async () => {
await loadLegal();
expect(isGateRequired()).toBe(true);
expect([...getBlockedRoutes()]).toEqual(['import', 'export', 'edit']);
});
it('leaves #settings and #about reachable', () => {
// Normative in docs/03 §4, docs/14 §2 and the docs/15 decision log:
// #about so the documents can be read first, #settings so a VI/JA user can
// switch language -- which is why the gate has no switcher of its own.
expect(isGatedRoute('settings')).toBe(false);
expect(isGatedRoute('about')).toBe(false);
expect(isGatedRoute('import')).toBe(true);
});
it('blocks nothing once accepted', async () => {
await fakeBrowser.storage.local.set({
legal: { acceptedVersion: LEGAL_VERSION, acceptedAt: ACCEPTED_AT },
});
await loadLegal();
expect(isGateRequired()).toBe(false);
expect([...getBlockedRoutes()]).toEqual([]);
});
});
describe('loadLegal', () => {
it('fails closed on a malformed record', async () => {
await fakeBrowser.storage.local.set({ legal: { acceptedVersion: 'yes' } });
await loadLegal();
expect(isGateRequired()).toBe(true);
});
it('fails closed, without throwing, when the read rejects', async () => {
vi.spyOn(fakeBrowser.storage.local, 'get').mockRejectedValue(new Error('storage disabled'));
await expect(loadLegal()).resolves.toBeUndefined();
expect(getLegalStatus()).toEqual({ kind: 'required', reason: 'first-run' });
});
it('still reports the superseded acceptance after a version bump', async () => {
await fakeBrowser.storage.local.set({
legal: { acceptedVersion: LEGAL_VERSION - 1, acceptedAt: ACCEPTED_AT },
});
await loadLegal();
expect(isGateRequired()).toBe(true);
expect(getAcceptance()).toEqual({
acceptedVersion: LEGAL_VERSION - 1,
acceptedAt: ACCEPTED_AT,
});
});
it('reports no acceptance at all on a fresh profile', async () => {
await loadLegal();
expect(getAcceptance()).toBeUndefined();
});
it('exposes the stored acceptance for the About tab', async () => {
await fakeBrowser.storage.local.set({
legal: { acceptedVersion: LEGAL_VERSION, acceptedAt: ACCEPTED_AT },
});
await loadLegal();
expect(getAcceptance()).toEqual({ acceptedVersion: LEGAL_VERSION, acceptedAt: ACCEPTED_AT });
});
});
describe('acceptLegal', () => {
it('persists the version and timestamp, then unlocks', async () => {
await loadLegal();
expect(await acceptLegal(ACCEPTED_AT)).toEqual({ ok: true });
const stored = await fakeBrowser.storage.local.get('legal');
expect(stored.legal).toEqual({ acceptedVersion: LEGAL_VERSION, acceptedAt: ACCEPTED_AT });
expect(isGateRequired()).toBe(false);
});
it('KEEPS THE GATE UP when the write rejects, and writes nothing', async () => {
// The flagship test of this phase. The recurring defect shape in this
// project is: dismiss optimistically, await a chrome.* call that can
// reject, never handle it. Here that would leave the user accepted in the
// UI and unaccepted on disk, with the gate silently back next launch.
await loadLegal();
vi.spyOn(fakeBrowser.storage.local, 'set').mockRejectedValue(
new Error('QUOTA_BYTES quota exceeded'),
);
const outcome = await acceptLegal(ACCEPTED_AT);
expect(outcome.ok).toBe(false);
expect(outcome.detail).toContain('QUOTA_BYTES');
expect(isGateRequired()).toBe(true);
expect(getAcceptance()).toBeUndefined();
const stored = await fakeBrowser.storage.local.get('legal');
expect(stored.legal).toBeUndefined();
});
it('never rejects, so no call site can leak an unhandled rejection', async () => {
vi.spyOn(fakeBrowser.storage.local, 'set').mockRejectedValue(new Error('nope'));
await expect(acceptLegal(ACCEPTED_AT)).resolves.toMatchObject({ ok: false });
});
it('writes nothing at all when the user declines', async () => {
// docs/14 §2: "no nagging -- closing the tab is the decline. Nothing is
// written." Closing is a component action; the contract is that merely
// showing the gate never touches the legal key.
await loadLegal();
const all = await fakeBrowser.storage.local.get(null);
expect(Object.keys(all)).not.toContain('legal');
});
});
+120 -5
View File
@@ -1,8 +1,10 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fakeBrowser } from 'wxt/testing';
import { DEFAULT_SETTINGS } from '@/lib/browser/storage';
import { getLocale } from '@/lib/i18n/index.svelte';
import {
applyTheme,
flushSettings,
getSettings,
isSettingsLoaded,
loadSettings,
@@ -12,6 +14,9 @@ import {
beforeEach(async () => {
fakeBrowser.reset();
// fakeBrowser.reset() clears stored data but leaves spies in place, so a
// rejecting storage.local.set would leak into every later test in the file.
vi.restoreAllMocks();
// fakeBrowser stubs i18n with a throwing "not implemented".
vi.spyOn(fakeBrowser.i18n, 'getUILanguage').mockReturnValue('en-US');
document.documentElement.removeAttribute('data-theme');
@@ -45,16 +50,16 @@ describe('settings store', () => {
});
it('applies a theme change immediately, before the debounced save', () => {
updateSettings({ theme: 'light' });
void updateSettings({ theme: 'light' });
expect(document.documentElement.getAttribute('data-theme')).toBe('light');
});
it('debounces writes — rapid changes produce one save', async () => {
vi.useFakeTimers();
try {
updateSettings({ theme: 'dark' });
updateSettings({ theme: 'light' });
updateSettings({ csvDelimiter: ';' });
void updateSettings({ theme: 'dark' });
void updateSettings({ theme: 'light' });
void updateSettings({ csvDelimiter: ';' });
// Storage still holds what the beforeEach reset wrote — none of the three
// changes has been flushed yet.
@@ -69,6 +74,98 @@ describe('settings store', () => {
}
});
it('writes a plain object, not the $state proxy', async () => {
// chrome.storage.local.set structured-clones its argument, and a Proxy is
// not cloneable — passing the reactive object straight through throws
// DataCloneError in a real browser. fakeBrowser stores the reference
// without cloning, so only an explicit clone here reproduces Chrome.
vi.useFakeTimers();
try {
void updateSettings({ theme: 'dark' });
await vi.advanceTimersByTimeAsync(250);
const stored = await fakeBrowser.storage.local.get('settings');
expect(() => structuredClone(stored.settings)).not.toThrow();
} finally {
vi.useRealTimers();
}
});
it('keeps a stable object identity so a captured reference cannot go stale', () => {
// The store mutates in place rather than replacing. A replacement would
// strand any component that read getSettings() into a local.
const before = getSettings();
void updateSettings({ theme: 'dark' });
expect(getSettings()).toBe(before);
expect(before.theme).toBe('dark');
});
it('resolves the outcome of the write, and never rejects, when storage fails', async () => {
vi.useFakeTimers();
try {
vi.spyOn(fakeBrowser.storage.local, 'set').mockRejectedValue(
new Error('QUOTA_BYTES quota exceeded'),
);
const saving = updateSettings({ theme: 'dark' });
await vi.advanceTimersByTimeAsync(250);
const outcome = await saving;
expect(outcome.ok).toBe(false);
expect(outcome.detail).toContain('QUOTA_BYTES');
// The in-session choice is still honoured — only persistence failed.
expect(getSettings().theme).toBe('dark');
} finally {
vi.useRealTimers();
}
});
it('reports success once the debounced write lands', async () => {
vi.useFakeTimers();
try {
const saving = updateSettings({ csvDelimiter: ';' });
await vi.advanceTimersByTimeAsync(250);
expect(await saving).toEqual({ ok: true });
} finally {
vi.useRealTimers();
}
});
it('flushSettings writes immediately without waiting out the debounce', async () => {
vi.useFakeTimers();
try {
const saving = updateSettings({ csvDelimiter: ';' });
expect(await flushSettings()).toEqual({ ok: true });
const stored = await fakeBrowser.storage.local.get('settings');
expect(stored.settings).toMatchObject({ csvDelimiter: ';' });
// The caller awaiting the debounced promise is settled by the flush too.
expect(await saving).toEqual({ ok: true });
} finally {
vi.useRealTimers();
}
});
it('flushSettings is a no-op when nothing is pending', async () => {
expect(await flushSettings()).toEqual({ ok: true });
});
it('resolves "auto" against the browser UI language', async () => {
vi.spyOn(fakeBrowser.i18n, 'getUILanguage').mockReturnValue('ja-JP');
await updateSettings({ locale: 'auto' });
expect(getLocale()).toBe('ja');
});
it('keeps <html lang> in step with the UI language', async () => {
// Both entrypoint documents ship lang="en"; without this a screen reader
// reads VI/JA text with an English voice and pronunciation rules.
await updateSettings({ locale: 'vi' });
expect(document.documentElement.lang).toBe('vi');
await updateSettings({ locale: 'ja' });
expect(document.documentElement.lang).toBe('ja');
vi.spyOn(fakeBrowser.i18n, 'getUILanguage').mockReturnValue('en-GB');
await updateSettings({ locale: 'auto' });
expect(document.documentElement.lang).toBe('en');
});
it('still loads when the browser i18n lookup throws', async () => {
vi.spyOn(fakeBrowser.i18n, 'getUILanguage').mockImplementation(() => {
throw new Error('not implemented');
@@ -78,10 +175,28 @@ describe('settings store', () => {
});
it('reset restores the documented defaults and persists them at once', async () => {
updateSettings({ theme: 'dark', csvDelimiter: ';' });
void updateSettings({ theme: 'dark', csvDelimiter: ';' });
await resetSettings();
expect(getSettings()).toEqual(DEFAULT_SETTINGS);
const stored = await fakeBrowser.storage.local.get('settings');
expect(stored.settings).toEqual(DEFAULT_SETTINGS);
});
it('reset cancels the pending debounced save rather than writing twice', async () => {
vi.useFakeTimers();
try {
const set = vi.spyOn(fakeBrowser.storage.local, 'set');
void updateSettings({ theme: 'dark' });
await resetSettings();
await vi.advanceTimersByTimeAsync(250);
// Exactly the reset's own write. Letting the debounce fire afterwards
// would persist the value the user just discarded.
expect(set).toHaveBeenCalledTimes(1);
const stored = await fakeBrowser.storage.local.get('settings');
expect(stored.settings).toEqual(DEFAULT_SETTINGS);
} finally {
vi.useRealTimers();
}
});
});
+106
View File
@@ -0,0 +1,106 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { clearToasts, dismissToast, getVisibleToast, pushToast } from '@/lib/stores/toast.svelte';
beforeEach(() => {
clearToasts();
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
clearToasts();
});
describe('toast queue', () => {
it('shows a pushed message and dismisses it after 4 s', () => {
pushToast('Saved', 'success');
expect(getVisibleToast()?.message).toBe('Saved');
vi.advanceTimersByTime(3999);
expect(getVisibleToast()).toBeDefined();
vi.advanceTimersByTime(1);
expect(getVisibleToast()).toBeUndefined();
});
it('is a queue, not a stack — the second waits for the first', () => {
pushToast('first');
pushToast('second');
expect(getVisibleToast()?.message).toBe('first');
vi.advanceTimersByTime(4000);
expect(getVisibleToast()?.message).toBe('second');
vi.advanceTimersByTime(4000);
expect(getVisibleToast()).toBeUndefined();
});
it('restarts the timer for a repeat of the visible message instead of queueing a twin', () => {
// One debounced settings save resolves one promise with several
// subscribers; without this the user gets three identical "Saved" toasts.
pushToast('Settings saved', 'success');
vi.advanceTimersByTime(3000);
pushToast('Settings saved', 'success');
vi.advanceTimersByTime(3000);
expect(getVisibleToast()?.message).toBe('Settings saved');
vi.advanceTimersByTime(1000);
expect(getVisibleToast()).toBeUndefined();
});
it('treats the same text with a different tone as a distinct toast', () => {
pushToast('Done', 'success');
pushToast('Done', 'danger');
vi.advanceTimersByTime(4000);
expect(getVisibleToast()?.tone).toBe('danger');
});
it('does not let a stale timer shift the next item early after a manual dismiss', () => {
pushToast('first');
const first = getVisibleToast();
pushToast('second');
vi.advanceTimersByTime(1000);
dismissToast(first?.id ?? '');
expect(getVisibleToast()?.message).toBe('second');
// The first item's original 4 s deadline passes here. Without the id check
// in the timeout it would shift again and flash "second" away instantly.
vi.advanceTimersByTime(3000);
expect(getVisibleToast()?.message).toBe('second');
vi.advanceTimersByTime(1000);
expect(getVisibleToast()).toBeUndefined();
});
it('ignores a dismiss for an item that is not on screen', () => {
pushToast('first');
pushToast('second');
const queuedId = 'toast-2';
dismissToast(queuedId);
expect(getVisibleToast()?.message).toBe('first');
});
it('caps the queue by dropping the oldest pending item, never the visible one', () => {
pushToast('visible');
pushToast('pending-a');
pushToast('pending-b');
pushToast('pending-c');
expect(getVisibleToast()?.message).toBe('visible');
vi.advanceTimersByTime(4000);
// 'pending-a' was the oldest queued item when the cap was hit.
expect(getVisibleToast()?.message).toBe('pending-b');
vi.advanceTimersByTime(4000);
expect(getVisibleToast()?.message).toBe('pending-c');
vi.advanceTimersByTime(4000);
expect(getVisibleToast()).toBeUndefined();
});
it('defaults to the info tone', () => {
pushToast('plain');
expect(getVisibleToast()?.tone).toBe('info');
});
});
+109
View File
@@ -0,0 +1,109 @@
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
/**
* docs/06 §5 requires ≥ 4.5:1 contrast "in both themes (tokens chosen
* accordingly)". Nothing enforced that, and they were not: shipping code had
* white ink on the dark-theme accent at 3.67:1 and three status colours used as
* text between 3.26 and 4.27 in light theme.
*
* Parsing the stylesheet rather than hardcoding the palette is the point — the
* test fails when someone edits a colour, which is exactly when it matters.
*/
const TOKENS = readFileSync(join(process.cwd(), 'src/styles/tokens.css'), 'utf8');
const REQUIRED_RATIO = 4.5;
function blockOf(pattern: RegExp): Record<string, string> {
const match = TOKENS.match(pattern);
if (match?.[1] === undefined) throw new Error(`tokens.css: no block matching ${pattern}`);
const out: Record<string, string> = {};
for (const declaration of match[1].matchAll(/(--[a-z-]+):\s*(#[0-9a-f]{6})\b/gi)) {
const [, name, value] = declaration;
if (name !== undefined && value !== undefined) out[name] = value;
}
return out;
}
function relativeLuminance(hex: string): number {
const channels = [1, 3, 5].map((i) => Number.parseInt(hex.slice(i, i + 2), 16) / 255);
const [r, g, b] = channels.map((c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4));
return 0.2126 * (r ?? 0) + 0.7152 * (g ?? 0) + 0.0722 * (b ?? 0);
}
function contrast(a: string, b: string): number {
const [lighter, darker] = [relativeLuminance(a), relativeLuminance(b)].sort((x, y) => y - x);
return ((lighter ?? 0) + 0.05) / ((darker ?? 0) + 0.05);
}
const light = blockOf(/:root\s*\{([\s\S]*?)\n\}/);
// The dark block overrides a subset; everything else inherits from :root.
const dark = { ...light, ...blockOf(/\[data-theme='dark'\]\s*\{([\s\S]*?)\n\}/) };
const darkMedia = {
...light,
...blockOf(/:root:not\(\[data-theme='light'\]\)\s*\{([\s\S]*?)\n\s{2}\}/),
};
/** [foreground, background] — every pair where the fg is rendered as TEXT. */
const TEXT_PAIRS: [fg: string, bg: string][] = [
['--fg', '--bg'],
['--fg', '--bg-raised'],
['--fg-muted', '--bg'],
['--fg-muted', '--bg-raised'],
// base.css colours every <a> with --accent, and rows/links sit on both.
['--accent', '--bg'],
['--accent', '--bg-raised'],
// Rendered as text: DuplicatePanel counts, TreePreviewNode badges,
// WarningList's summary, TreeRow's ⚠ unsafe-scheme marker. Checked against
// BOTH surfaces — a row sits on --bg until it is hovered or focused.
['--danger', '--bg-raised'],
['--danger', '--bg'],
['--success', '--bg-raised'],
['--success', '--bg'],
['--warn', '--bg-raised'],
['--warn', '--bg'],
// Ink on a filled control: Button .primary/.danger, ConfirmDialog .danger,
// ThemeToggle .selected.
['--accent-fg', '--accent'],
['--danger-fg', '--danger'],
];
const THEMES: [name: string, tokens: Record<string, string>][] = [
['light', light],
['dark (data-theme)', dark],
['dark (prefers-color-scheme)', darkMedia],
];
describe('token contrast', () => {
it.each(THEMES)('%s meets 4.5:1 on every text pair', (_name, tokens) => {
const failures: string[] = [];
for (const [fg, bg] of TEXT_PAIRS) {
const fgValue = tokens[fg];
const bgValue = tokens[bg];
if (fgValue === undefined || bgValue === undefined) {
failures.push(`${fg} or ${bg} is undefined in this theme`);
continue;
}
const ratio = contrast(fgValue, bgValue);
if (ratio < REQUIRED_RATIO) {
failures.push(`${fg} (${fgValue}) on ${bg} (${bgValue}) = ${ratio.toFixed(2)}:1`);
}
}
expect(failures).toEqual([]);
});
it('keeps the two dark blocks identical', () => {
// tokens.css carries the dark palette twice — once for the explicit
// override and once for prefers-color-scheme. They drifted once already:
// --accent-fg was added to one and not the other.
expect(darkMedia).toEqual(dark);
});
it('defines an explicit ink for every token used as a filled background', () => {
for (const pair of ['accent', 'danger']) {
expect(dark[`--${pair}-fg`], `--${pair}-fg missing from the dark block`).toBeDefined();
expect(light[`--${pair}-fg`], `--${pair}-fg missing from :root`).toBeDefined();
}
});
});