Compare commits

...
Author SHA1 Message Date
poli0981andClaude Opus 5.5 82a46cf1a8 fix(scripts): check-manifest takes no path argument
SonarCloud's second pass still flagged S8707: the directory to check came
from argv and flowed into file reads, and a startsWith() allowlist did not
count as sanitizing it. The CLI now only ever checks the repository's own
.output/chrome-mv3; the logic is an exported checkExtension(dir) (typed by
check-manifest.d.mts) that the tests call directly, so no command-line path
reaches a file read at all.

Path resolution moved inside the entry point: under Vitest's jsdom
environment import.meta.url is not a file: URL, so resolving it at module
load threw on import. The two Node-script suites now run in the node
environment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 23:58:18 +07:00
poli0981andClaude Opus 5.5 bc02c2ede7 fix(security): clear SonarCloud's findings on the new gates, and close remote stylesheets
The first CI-based SonarCloud scan failed the quality gate on its new-code
security rating, with two findings in check-manifest.mjs:
- S8707: it read whatever directory the CLI argument named. It now accepts
  only paths inside this repository or the OS temp directory (where its
  tests build fake extensions), and says so when it refuses.
- S8689: its success line echoed values read from the file. It now prints
  constants — the manifest has just been proven equal to them.

And four S8786 regexes in guard.mjs plus one in the sanitizer, where a \s*
beside an optional quote beside another \s* could backtrack: each is now
written so no two quantifiers compete for the same characters, and the
markup rule is two linear steps (find the tag, then look inside it). The
sanitizer's JSON tokenizer no longer reassigns its loop counter (S2310).

While here: with no default-src, style-src was open, so a remote stylesheet
could still load. The CSP now adds `style-src 'self' 'unsafe-inline'`
(Svelte sets style attributes); check-manifest pins the new string.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 23:51:28 +07:00
poli0981andClaude Opus 5.5 e1a4163f74 fix(scripts): the sanitizer stops leaking Chrome profile titles, and every script is checked
sanitize-bookmarks.mjs accepted any JSON object and rewrote only "url" and
"title". Chrome's profile Bookmarks file keeps titles under "name" (plus
meta_info and a base64 sync_metadata blob), so it came out with every title
intact, passed the host-only leak check, and was written as "sanitized" —
the exact file a reporter whose import failed would attach.

- JSON dialects are recognised by shape (BookmarkMagic, Chrome profile,
  Firefox backup); any other JSON is refused. Rewriting is default-deny: a
  small tokenizer tracks the key of every string value and replaces all of
  them except structural keys (types, ids, timestamps, root GUIDs), by span,
  so layout and key order stay byte-identical.
- The backstop now reads the output's TEXT: for HTML it strips markup and
  refuses on any word that is not a placeholder — independent of the
  rewriting rules, unlike the old host-only check whose test shared its
  blind spots. <DD class=…> notes, file: ICON_URIs and <H1>/<TITLE>
  owner names are rewritten.
- Attribute values decode in one pass (CodeQL js/double-escaping), <DD>
  bodies are found in linear time (Sonar S8786), the input is never
  overwritten, size is checked before reading, and bytes are bytes.
- The 627-line file is split into scripts/sanitize/ modules; the
  user-facing entry stays plain .mjs for reporters on any Node.

gen-fixture.mjs validates its flags (whole numbers >= 1, values required, no
unknown flags) and its loop visibly advances (Sonar S2189 blocker).
gen-icons.mjs says what is true: it is the icons' source of truth.

Every script now carries // @ts-check and tsconfig.scripts.json runs them
through the TS 7 tsc in `npm run check`; docs/10's size rule names .mjs.
Regenerated icons are byte-identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 23:34:15 +07:00
poli0981andClaude Opus 5.5 3244aad002 fix(security): enforce zero-network in the browser, and gates that cannot be talked past
The "no network access" claim rested on one grep gate. An audit ran its
exact patterns against 28 bypasses and every one got through — an alias
(`const go = fetch`), computed global access, a call split over two lines,
`innerHTML +=`, `{ @html }`, remote url() in CSS — and a checkout path with
a space or diacritic made it scan nothing and print "clean". Now:

1. The production manifest declares an extension-page CSP with
   `connect-src 'none'` (plus closed img/font/media/frame/form sources), so
   Chrome itself refuses every fetch, XHR, WebSocket, EventSource and beacon.
   No default-src, so Svelte styles are untouched; dev builds omit it so
   the HMR websocket works. docs/08 used to say "never add a CSP" because
   MV3 forbids loosening — tightening was always allowed.
2. check:manifest scans every shipped .js for network APIs (dependency code
   included), pins the exact CSP and the Chrome floor, checks that every
   file the manifest and pages reference exists, resolves paths from the
   script instead of the cwd, and sets exitCode instead of exit().
   Vite's modulepreload polyfill — the one network call in the bundle — is
   disabled; every Chrome at the floor supports modulepreload natively.
3. guard.mjs matches whole files (so \s* spans newlines), bans the API
   identifiers outright, bans computed access on globals, scans .html and
   .css, has no test-file exemption, uses fileURLToPath, and fails when it
   scanned nothing. docs/08 §3 points at the file instead of restating it;
   the restated copy had already drifted.

Both scripts finally have tests (48 + 18 cases, every audited bypass
included). One src comment named the API in prose and is reworded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 23:24:08 +07:00
poli0981andClaude Opus 5.5 32b5ab93b6 ci: SonarCloud CI analysis with coverage, and a release that never installs while holding a write token
SonarCloud ran Automatic Analysis: no coverage, and a scan of the repo rather
than of what CI builds. sonarcloud.yml replaces it — full-history checkout,
the coverage run, then the scan with the package version as the new-code
baseline. It is its own workflow so a Sonar outage or gate opinion can never
turn CI red, the scan action is pinned to a commit because it holds
SONAR_TOKEN, the token reaches only the two steps that use it, and runs
without secrets (Dependabot, forks) skip with a notice instead of failing.

Coverage now measures every src/**/*.ts module and emits lcov, but the CI
gate is unchanged: a glob threshold applies the docs/11 §1 numbers to
src/lib/core/** only (verified to still fail a run below them).

Hardening, from SonarCloud's findings and the scripts/config audit:
- npm ci --ignore-scripts everywhere, with `wxt prepare` run explicitly;
- checkouts drop persisted credentials;
- release.yml is split: gates and zip run with a read-only token; only a
  job that installs nothing and runs no repo code creates the Release; the
  store submit uses the local wxt binary, never `npx` with secrets in scope;
- reusables get named secrets instead of `inherit`. The announce job could
  never have worked: this repo stores RELEASES_WEBHOOK/REPO_WEBHOOK, the
  reusable reads DISCORD_*, and inherit passed neither;
- CI runs `npm audit --omit=dev`, which docs/09 already claimed it did;
- a non-required Windows smoke job (guard + unit tests).

serializeMarkdown's trailing-newline trim used /\n+$/, which backtracks
quadratically over a long newline run that is not at the end (S8786); it is
now a single backward scan, with a 20k-newline regression test.

docs/12 no longer copies the workflow YAML — the copies drifted three times,
and under docs-win a stale copy invites reverting a pinned action.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 23:17:16 +07:00
poli0981andClaude Opus 5.5 58f75232a1 build(deps): take the dev toolchain to its newest week-old releases
Every dev dependency moves to the newest release that has been public for
at least 7 days, and that rule is now enforced rather than remembered:
.npmrc sets min-release-age=7 and Dependabot gets a 7-day cooldown on both
ecosystems. `npm ci` was verified to ignore the age rule for versions
already in the lockfile, so it only shapes what gets locked.

  vitest / coverage-v8  4.1.10 -> 5.0.5   (suite passed unchanged)
  @biomejs/biome        2.5.5  -> 2.6.2   (exact)
  svelte                5.56.8 -> 5.57.2
  vite-plugin-svelte    7.2.0  -> 7.3.1
  svelte-check          4.7.4  -> 4.7.7
  jsdom                 30.0.1 -> 30.1.3  (dom-environment canary first)
  knip                  6.29.0 -> 6.42.1
  wxt                   0.21.3 -> 0.21.4  (+ transitive vite 8.3.5)

npm audit: 13 (7 high) -> 3 low, all one deepmerge advisory with no fixed
release, inside vite-plugin-svelte's dev-time option merging; documented in
docs/09 §3.1. --omit=dev stays 0. This supersedes Dependabot #19-#25.

The six-entry overrides block is deleted: none of those packages is in the
tree any more (WXT 0.21 dropped web-ext-run, Vite 8 bundles with rolldown),
and a stale override would silently pin a package the day it came back.

WXT got the built-manifest diff the 2026-08-03 decision requires: identical
keys and values apart from the deliberate minimum_chrome_version, identical
file inventory. Biome 2.6 began formatting Markdown and YAML, so both are
excluded rather than letting a formatter reflow hand-written docs.
dependabot.yml now keeps WXT out of the routine group and ignores majors of
the TypeScript pair and @types/node.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 23:09:26 +07:00
poli0981andClaude Opus 5.5 96ac16bb38 build: Node 26 LTS, TypeScript 7 alongside the TS 6 API, ES2025 at a Chrome 136 floor
Node 26 entered Active LTS on 2026-10-28 and Node 24 went to maintenance on
2026-10-20, so the toolchain moves with them: .nvmrc, engines and @types/node
all say 26.

TypeScript 7.0 is GA but still has no programmatic API, and svelte-check
peers `typescript ^5 || ^6`. So this uses Microsoft's documented
side-by-side aliases instead of choosing one:

  "@typescript/native": "npm:typescript@~7.0.2"           -> tsc (7.0.2)
  "typescript": "npm:@typescript/typescript6@~6.0.2"     -> the 6.0.3 API

`npm run check` therefore type-checks .svelte files with TS 6 (svelte-check)
and every .ts file with both. `tsc --version` is 7.0.2; `tsc6` is 6.0.3.

tsconfig targets ES2025 with lib ES2025, which is only honest if the oldest
Chrome allowed to install has every ES2025 built-in. That is Chrome 136
(RegExp.escape), so minimum_chrome_version goes 120 -> 136 and Vite's
build.target follows the same CHROME_FLOOR constant. manifest.test.ts pins
all three so they cannot drift apart. Users below 136 keep what they have
installed; they just stop receiving updates.

Built output: the manifest changes only minimum_chrome_version, the JS chunks
are byte-identical apart from a CSS hash, and the CSS loses one
-webkit-user-select prefix Chrome 136 no longer needs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 23:04:05 +07:00
poli0981andClaude Opus 5.5 d01e746644 docs: record that v1.0.1 is published
The listing has shown version 1.0.1 since it cleared review; the suite still
said "in review, not yet approved" in docs/00, docs/15 and CLAUDE.md, the
exact mirror of the week it spent claiming review after 1.0.0 was live.

Recorded only what was observed (2026-10-28: listing shows 1.0.1, 5 users).
The approval date and the 13 §1b step-10 clean-profile check of the
published build stay marked as unrecorded rather than inferred. CLAUDE.md's
EditTab figures were the v1.0.0 numbers; they are now the current ones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 23:00:15 +07:00
poli0981andClaude Opus 5.5 919b79d3c0 chore: check text files out with LF on every platform
A Windows clone with core.autocrlf=true checked every text file out with
CRLF, and Biome's formatter (which expects LF) then failed `npm run lint`
on all 114 files before a single line had been edited. The two scripts
with a `#!/usr/bin/env node` line were also unusable from WSL.

`eol=lf` fixes the checkout, not the repository: the index already held
LF everywhere (`git add --renormalize .` stages nothing else), and
tests/fixtures/** stays -text so the CRLF records the CSV fixtures exist
to exercise are untouched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 22:59:07 +07:00
poli0981andClaude Opus 5 3fc8fd1d5d docs: record that v1.0.1 is released and submitted — and only that
The owner tagged, released and uploaded v1.0.1 to the dashboard on 2026-08-03.
Recorded as **submitted, in review** — deliberately not as published.

That distinction is the whole reason Phase 6 existed. This suite spent a week
asserting "in review" after the listing had already gone public, and the
opposite error is the worse half of the same mistake: telling a future reader
that users have a fix they have not received yet. Users are on 1.0.0 until the
review clears.

docs/15's progress table gains two rows — released (signed tag, checksum-verified
zip, announce and store-publish both correctly skipped for want of their repo
variables) and submitted. docs/00 §10 gains item 11: what to write down when it
clears, and the pointer to §7 if it is rejected instead, because a rejection and
its resolution are the only memory this project would have of what reviewers
actually object to.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 21:25:38 +07:00
poli0981andClaude Opus 5 d09a118c3c docs(ci): record branch protection, and correct the check names it needs
Applying the §5 checklist item exposed two errors in it.

The required check is `Build + package / build`, not `Build + package`. A job
that calls a reusable workflow publishes its check as `<caller job> / <reusable
job>`, so requiring the caller's name alone matches nothing that will ever be
reported — every PR waits forever and `main` becomes permanently unmergeable.
The doc was confidently specific about this ("the job names — not the workflow
name") and confidently wrong, which is the worst combination.

"Require review" is set to zero approvals, deliberately. It is correct advice
for a team and a lockout for one maintainer, who cannot approve their own pull
request. Zero still forces every change through a PR and through the checks;
it only drops a second pair of eyes that does not exist. Admins are not
enforced, for the same reason: with a single maintainer, an escape hatch from
your own rules is what separates a safety net from a locked door.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:35:22 +07:00
poli0981andClaude Opus 5 4654086b5b fix(deps): declare @types/node, which CI proved was never really there
The first CI run on this branch failed `npm run check` with 18 errors —
"Cannot find name 'node:fs'" — including in `tests/unit/styles/contrast.test.ts`,
which this branch never touched. So it was not the new test: the package has
always used Node types without declaring them.

Two things hid it. WXT 0.20 supplied `@types/node` transitively and 0.21 does
not, and this worktree sits under the parent checkout, so TypeScript walked up
to `E:\bookmarkmagic\node_modules\@types\node` and resolved them anyway — even
after a correct `npm ci` in the worktree itself. A green local type-check in a
worktree is therefore weaker evidence than it looks, which is now written down
in CLAUDE.md next to the existing worktree gotcha.

Types only: erased at build, nothing ships, so hard rule 2 — zero *runtime*
dependencies — is untouched, and the built manifest and bundle are unchanged.
docs/01 §2 records it with the reason, since that table is the pinned-version
spec rather than a summary of it.

This is the failure the tag run would otherwise have hit, and the reason a red
CI is worth reading before merging rather than after tagging.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:20:05 +07:00
poli0981andClaude Opus 5 302dc2e4dd chore(release): 1.0.1
Exactly the two files a patch touches — package.json's version and CHANGELOG.md,
section plus the link references at the bottom. wxt.config.ts declares no
version key, so it must not appear in this diff, and it does not; the built
manifest reads 1.0.1 and `npm run zip` emits bookmarkmagic-1.0.1-chrome.zip.

`npm run verify:full` green: lint, svelte-check + tsc, knip, the grep gate, 694
tests, core coverage 97.4%/92.1%, the build, and check:manifest against the
built artifact. The built manifest is byte-identical to the pre-phase baseline —
same permissions, same key set — across ten commits and a WXT major-slot bump.

The changelog is written for users rather than for the diff: what changed for
someone who already has this installed, and the fact that they need do nothing.

⚠️ Stops here, deliberately. The tag and the store upload are human steps:
  git tag -s v1.0.1 && git push origin v1.0.1
and then docs/13 §1b from step 5 — which begins with the manual QA pass,
including the 1.0.0 → 1.0.1 upgrade over an existing profile that nothing here
can perform.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:20:05 +07:00
poli0981andClaude Opus 5 28f6befcd0 fix: close the eighteen findings the Phase 6 review confirmed
Six lenses over the branch, each finding independently attacked by a verifier
told to refute it. 31 filed, 18 survived, clustering into five real defects —
and the pattern held: every one is in work added earlier in this same branch.

**The sanitizer did not keep its promise (9 findings).** It is the single
privacy control in the intake flow, named as mandatory in SECURITY.md, README,
CONTRIBUTING, the privacy policy and the issue form — and it leaked in nine
distinct ways. Worst: `detectKind` fell back to 'csv' for anything it could not
identify, `sanitizeCsv` then matched no columns, and the input was emitted
verbatim with exit code 0. The users who run this tool are by definition the
ones whose file did not import, so a truncated or hand-excerpted file is the
TYPICAL input — and `tests/fixtures/malformed/no-doctype.html`, already in the
repo, reproduced it. The test could not catch any of this: it returned early
whenever the original failed to parse, so it passed vacuously on precisely the
dangerous inputs.

Nine holes found in one pass is not a signal to patch nine holes. The rules are
regexes over untrusted markup, so "we thought of every shape" is not a claim
anyone can make honestly. So the tool now fails safe:

- unidentified input is REFUSED, matching core detectFormat rather than being
  weaker than the parser it fronts;
- the output is checked before it is written — any host that is not one of our
  own `*.example` aliases means a rule missed something, and the file is refused
  with the leaked host named. A rule this misses now degrades into an annoying
  refusal instead of a published browsing history.

The individual holes are fixed too: single-quoted and bare attribute values were
never matched (a straight leak); `spansFrom` located capture groups by searching
the match text, landing on the wrong copy — replaced with the `d` flag's exact
offsets; overlapping spans spliced already-rewritten text using offsets measured
against the original; `[^<]*` made a title containing a raw `<` fail to match
entirely; `<DD>` stopped at the first newline, publishing the rest of a wrapped
note; and replaceSpans rebuilt the whole string per span, O(spans x file).

**The import report pointed users at a backup that was never written.** The
guard was "mode is replace and this is not a BmBackupError", but runImport
resolves the roots BEFORE proving the backup — so NO_WRITABLE_ROOTS, added in
this same branch, reaches the catch with nothing on disk. Now keyed on the
onClearing callback, which is the only signal that proveBackup actually
returned.

**Cancelling a Replace after the clear read as a harmless no-op.** The tree is
gone and only `created` of it rebuilt; "N items created" alone, on a browser
that is now nearly empty, is the wrong story. It now says so and names the
backup.

**Collapsing a folder while a search was active re-opened it instantly.** The
$effect read and wrote the same two `$state` sets, making it its own dependency:
every write re-invalidated it and it re-merged an unchanged `search.expand`.
Reproduced against the real Svelte runtime — `$effect` is stripped under this
repo's vitest config, so no unit test could have seen it. Fixed with `untrack`,
which also removes the self-retrigger loop.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:20:05 +07:00
poli0981andClaude Opus 5 dc0672ea28 fix(ci): remove a keyword GitHub rejects on reusable-workflow callers
`continue-on-error` is not allowed on a job that calls a reusable workflow.
GitHub answers with "Property continue-on-error is not allowed" and refuses the
**whole file** — a startup_failure with zero jobs and no log, not one failed
job. Confirmed against two GitHub community discussions, one of which is an
open, unanswered feature request asking for the capability.

release.yml's announce job has carried that keyword since 5f4c6e7. That commit
landed *after* the v1.0.0 tag object and no tag has been pushed since, so the
first v1.0.1 tag would have been its first execution — and the release would
have died before running a single job, in exactly the silent shape this project
already hit once with the `contents: write` grant (2c8fba9). The previous commit
in this branch then copied the same mistake into notify-ci-failure.yml.

Both are now gated with `if:` on a repo variable instead. A variable and not a
secret because secrets cannot be referenced in a job-level `if:`, and unset
means skipped — so the release stays green and CI stays quiet until the owner
opts in by setting DISCORD_ANNOUNCE / DISCORD_CI_NOTIFY alongside the webhooks.
Same idiom as the CWS_AUTOPUBLISH gate already in release.yml.

docs/12's samples and its §5 checklist updated in the same commit; docs are
binding here, and leaving the invalid keyword in the spec would have had the
next reader put it straight back.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:20:05 +07:00
poli0981andClaude Opus 5 f3d4dfb023 chore(deps): take the two open Dependabot bumps, with the manifest proved unchanged
Applied directly rather than merged: both branches predate this phase and would
have reverted `verify:full`.

**wxt ^0.20.27 → ^0.21.3.** A 0.x minor is semver's breaking slot, and WXT is
what emits the shipped manifest — so the acceptance test was a byte diff of the
built artifact, not a green suite. Manifest, file inventory (content hashes
stripped) and bundle size all came out identical, permissions unchanged, zip
name unchanged. It *did* break two things, both dev-only: `wxt/testing` split
into `wxt/testing/fake-browser` and `wxt/testing/vitest-plugin`, and
`tabs.create` is now typed as returning void.

That split is the point of the ritual. `npm run test` passed before the bump and
the *config load* failed after it — while `tests/unit/manifest.test.ts`, the
test that looks like it guards the manifest, would have stayed green whatever
WXT emitted, because it reads wxt.config.ts and a WXT upgrade cannot change that
file. The check-manifest key-set gate added in the previous commit is what makes
the next one CI's problem rather than a manual comparison someone has to
remember to do.

**jsdom ^29.1.1 → ^30.0.1.** Canary first: tests/unit/dom-environment.test.ts
pins the parse5 behaviour the Netscape walk depends on — implied end tags, and
`:scope >` from an element root. It passed, then the parser, fixture and
round-trip suites, then coverage, all unchanged. The 2 869 ms figure in
docs/11 §6 is now labelled as a jsdom 29 number; a DOM major invalidates it
rather than updating it.

**svelte-check ^4.7.3 → ^4.7.4.** A patch.

npm audit stays at 0, and none of the six `overrides` can be dropped yet.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:20:05 +07:00
poli0981andClaude Opus 5 f6e6999a4d ci: stop CI being red for a reason nobody acts on, and gate the manifest key set
notify-ci-failure.yml called a reusable that declares DISCORD_CI_WEBHOOK as
`required: true`, which GitHub validates before any of the reusable's own logic
runs. With the secret unset — docs/00 §10.6 lists it as still open — that
workflow failed on *every* CI completion, success included, from the first push
after it landed. The file's own header comment admitted it. This is precisely
the failure mode commit 5f4c6e7 fixed for releases: a run that is red for a
reason nobody acts on teaches everyone to stop reading the colour, and the next
genuine failure goes unnoticed.

release.yml's `gh release create` had no existence check, so any failure after
it — realistically the CWS publish step, once autopublish is on — stranded the
tag: a re-run could not get past that line, and recovery meant deleting the
Release and the tag by hand. v1.0.1 is the first tag to exercise that path at
all, since both the continue-on-error announce fix and tag_override landed
after the v1.0.0 tag object.

check-manifest.mjs now asserts the exact top-level key SET, not just the absence
of ten enumerated reach-widening keys. The forbidden list can only catch what
someone thought to name; this catches a build tool that starts emitting a key
nobody asked for. That matters immediately: WXT is a 0.x dependency, so a
routine minor bump is exactly when it happens, and tests/unit/manifest.test.ts
is structurally blind to it — it reads wxt.config.ts, which a WXT upgrade cannot
change. Verified by injecting a `commands` key into a built manifest and
watching the gate fail.

docs/12's sample YAML updated in the same commit, so the drift this phase just
finished correcting does not immediately start again.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:20:05 +07:00
poli0981andClaude Opus 5 3b6bc42897 feat(about): link the Chrome Web Store listing
docs/13 §6 counts store ratings and reviews as one of the three post-launch
channels this project has, and there was no way to reach the listing from
inside the extension — the listing URL appeared in exactly one place in the
repo, the README, which a user who installed from the store never reads.

Deliberately no support email alongside it. Publishing an address on an
in-product surface invites people to mail their real bookmarks file, and a
bookmarks export is a browsing history — the exact receipt of personal data
legal/PRIVACY.md and docs/09 §6 are written to bound. contact@poli0981.dev
stays in SECURITY.md and CONTRIBUTING.md, where it arrives next to the
instruction to sanitize first. A test asserts links.ts contains no address, so
the decision has to be made again on purpose rather than by accident.

docs/06 §3.5 sanctioned the fourth link in PR A, before the code added it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:20:05 +07:00
poli0981andClaude Opus 5 741c07ffad feat(settings): make two Manager tabs agree with each other
docs/15 recorded this as a known v1 limitation, and with real users it is a
one-star review waiting to happen: `save()` writes the whole settings object
rather than a patch, so a tab opened before the language changed reverted that
change the moment its own theme toggle fired. From the user's side that reads as
"I changed it and it didn't stick" — unfalsifiable, and indistinguishable from
a bug. Accepting the legal terms in one tab likewise left the other padlocked
until reload.

The adoption rule is field equality plus an in-flight guard, and between them
they solve the echo problem and the debounce problem at once:

1. If this context has an unflushed write, ignore the incoming change entirely.
   It is about to overwrite that value anyway, and adopting first would clobber
   the choice the user just made — in the UI *and* in what gets persisted 200 ms
   later. That is last-write-wins, exactly the semantic docs/15 documented, and
   it converges because our write fires the same event in the other tab.
2. Otherwise adopt only fields that actually differ. Our own write always
   matches what we already hold, so self-echo suppression falls out for free —
   no `lastWritten` snapshot to keep in step and go stale, and no dependence on
   key order, which a $state spread and coerceSettings do not agree on.

The fake-timer test covering rule 1 is the one that matters; without it the
guard is an unverified assertion about a race.

Legal acceptance is adopted **one way only, toward accepted.** App.svelte
renders the gate in place of the tab body, so an externally-raised gate would
unmount ImportTab mid-write and strand the import it was driving — recreating,
through a third door, the deadlock the routing guard and the store-held
attestation resolver were just written to close. Clearing storage elsewhere
therefore does nothing; a reload re-evaluates it, and a reload has no in-flight
work to strand. Three tests pin that asymmetry so a future simplification that
makes it symmetrical fails loudly.

subscribeStorage coerces through the same functions the read path uses — a
second tab is not a more trustworthy source than disk, it is the same disk — and
swallows a throwing handler, because an exception inside a chrome.* listener
surfaces in chrome://extensions and docs/11 §5 counts that as a failed QA pass.

Verified before writing any of it that WXT's fakeBrowser does implement
storage.onChanged (unlike bookmarks.*), so no injectable event source was
needed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:20:05 +07:00
poli0981andClaude Opus 5 cfd1e77cb2 fix(edit): localized failures, and a search that collapses again
**#edit and #export showed a raw English Chrome string as the entire message.**
docs/02 §7 requires a localized sentence plus a separate technical block, and
LegalGate carries a comment describing this exact mistake as a defect that was
already fixed once — writing `detail ?? t(key)` looks like a sensible fallback,
but the raw string is almost always present, so the translation becomes dead
code. Three sites still had it: EditTab's load failure, ExportTab's load
failure, and ExportTab's export toast. A Vietnamese or Japanese user got an
untranslated Chrome message as their whole explanation.

One ErrorCallout now owns that contract, so there is a single place it can be
got wrong, and all three tabs go through the shared describeError.

**Clearing the search box rendered the whole tree in one synchronous pass.**
Search-opened ancestors merge into `expanded` (deliberately — a render-time
union made the disclosure button and ArrowLeft dead keys), but nothing ever
un-merged them. A one-character query expands most of a large profile, and
clearing the box then rendered every row the search had opened at once, with no
virtualization behind it; the 150 ms debounce delayed that growth without
bounding it. src/lib/edit/search-expansion.ts tracks search-owned ids
separately, and toggling a folder transfers it to the user so the collapse
cannot steal it back.

**"Keep the first of each" targeted nodes it cannot delete, then gave up
silently.** The duplicate list had no isEditable filter — unlike the
single-delete path — so duplicates inside a policy-managed subtree were offered
for bulk deletion, and the browser rejects every one of them. The loop then
abandoned the rest on the first rejection, leaving a partial delete measured
against a dialog that had promised an exact number, with no way to tell how many
copies remained. deleteEach never throws and reports how far it got.

EditTab was at 481/500 before this, so the ARIA tree container came out into
TreeList.svelte first — 466 now, and the tree pattern lives somewhere it is not
surrounded by loading, searching, mutation and five dialogs. That extraction
immediately caught a real bug the shorthand had hidden: `{ontoggle}` bound
`window.ontoggle`, not the local `toggle`.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:20:05 +07:00
poli0981andClaude Opus 5 d8bbd4ca79 fix(import): never lose the count, and close the Back-button deadlock
Three defects on the paths that touch a user's real bookmarks.

**A mid-import rejection used to lose everything needed to recover.**
writeTree awaited create() and let a rejection propagate bare — while the
bookmarks it had already written sat in the user's tree, uncounted. The
neighbouring BmAborted has always carried `done` for exactly this reason.
clearRoots was worse: it is the one path that deletes, and it reported nothing
at all, plus threw BmAborted(0) on cancellation regardless of how many root
children were already gone. Both now throw BmPartialWrite{phase, done}, and the
error state carries the safety backup's filename — which `attesting` knew and
`error` threw away, so the one string that lets someone restore a half-replaced
tree was the one thing not on screen. Only when a backup was actually produced:
on a BmBackupError the file may never have been written, and sending a
frightened user to look for a backup that does not exist is worse than silence.

BmAborted is re-thrown before the wrap, with a test pinning it. Wrapping it
would relabel every user cancellation as a failure and make the `cancelled`
state — and its copy in three languages — unreachable.

**Browser Back during the backup attestation deadlocked the Manager
permanently.** The attestation resolver was a component-local `let`, so Back
unmounted ImportTab, stranded the promise runImport was awaiting, and left
isWriting() true forever: every tab and footer control disabled, beforeunload
prompting, and a remounted tab rendering two inert buttons against a fresh empty
resolver. Closing the tab was the only escape. Phase 4 closed this same hole for
the footer and the tab bar; hashchange was the door left open.

Two independent fixes, because one is not enough: startRouting now takes an
injected isBlocked predicate (injected, not imported, so route stays uncoupled
from the import session), and the resolver moved into the store where it
outlives any component. A stale or reset resolver settles **false** — an
unanswered attestation is not consent, and this is the last gate before deleting
every bookmark someone has. The restore-the-hash path has an explicit test for
not recursing; an infinite hashchange loop in a released extension, on the path
a panicking user takes, is not a defect worth discovering from a review.

**Nothing told users their imported bookmarks are re-dated to today.** docs/05
§6 instructs saying so in the import report and docs/00 §8 repeats it as a
success criterion; no string ever did. The README and store listing say it to
prospective users, and the product never said it to actual ones — so someone
migrating a decade-old archive finds every bookmark dated today with no
explanation and no way to tell it from corruption. Now shown before the import
as well as after: telling someone before they commit is worth more.

Also: a profile whose every root is policy-managed now reports
NO_WRITABLE_ROOTS rather than "the browser refused a bookmark operation". The
browser refused nothing; it is an absence, not a refusal, and the old wording
sent people looking for a permission problem that was not there.

describeError moves out of ImportTab into browser/describe-error.ts so #edit and
#export can share it next, with tests asserting the two properties that have
been defects before: it returns a key rather than a resolved sentence, and it
omits `detail` rather than setting it to undefined.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:20:05 +07:00
poli0981andClaude Opus 5 875eae5de5 feat: build the intake the v1.0.x plan has always assumed
docs/13 §6 stated as present-tense fact that "GitHub issues — templates route
bug reports with sample files", and docs/12 §5 carried the same as an unticked
box. Neither was true: .github/ held only FUNDING.yml, dependabot.yml and
workflows. Meanwhile the entire v1.0.x roadmap is "fixture + test per report",
which cannot happen if reports arrive without the file that broke.

Five issue forms plus a chooser, blank issues disabled. parser_report.yml is
the one that matters: it requires the sanitized sample, asks which browser
*version* produced the file, and asks explicitly for consent to commit the
sample as a GPL-3.0 fixture — it lives in a public repo forever, and nothing
previously asked.

scripts/sanitize-bookmarks.mjs makes "attach a sanitized sample" something a
reporter can actually do. It works by span replacement rather than by
reparsing, so every byte outside a replaced address or title is provably
untouched: BOM, doctype, line endings, tag and attribute case, quoting,
indentation and every timestamp survive, and so do the properties a parser
branches on — port, path depth, trailing slash, query-parameter count and
order, percent-escapes, HTML entities, and the distinctness of hosts that
dedupe depends on.

Its test asserts the promise rather than the implementation: for every fixture
in the repo, the sanitized file must detect as the same format, parse to the
same stats, warnings and topology — or fail with the same error code — and leak
no original hostname. Writing it immediately found three real defects: a data:
URL containing markup broke the title regex and left that bookmark's title
unsanitized; an &amp; in an HREF came back as a bare &, silently repairing the
escaping of the file being reported; and Firefox's ICON_URI leaked a full
hostname past every other check. The last one is why URL-valued attributes are
now swept by value shape instead of by an enumerated list.

scripts/gen-fixture.mjs is the generator docs/11 §2 named, .gitignore has
always reserved a directory for, and the 2 s parse budget needed in order to be
measurable at all.

CONTRIBUTING.md collects the five-file ritual for turning a user's file into a
regression test, which was previously spread across CLAUDE.md, docs/04 and
docs/11 with no single entry point — including the .gitattributes rule that
stops EOL normalization destroying the bytes a bug depends on.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:20:05 +07:00
poli0981andClaude Opus 5 20ddba5472 docs(store): put the listing copy under version control
docs/13 §4 has always said the VI/JA listing text should live in
store/listing.{vi,ja}.md "so listing text is version-controlled". It never did,
which meant every listing edit — one of the three things the v1.0.x roadmap
anticipates — would be made straight into the dashboard with no diff, no
history and no reviewer.

Reconstructed from docs/13 §3, with EN added as the canonical file since it is
the one CWS requires. Marked ⚠️ throughout: these were written after the listing
went live, so they are a copy of the specified copy, not a transcript of what
the dashboard shows. Until someone diffs the two, the dashboard wins.

Summary lengths are recorded per file and verified against the 132-character
dashboard cap — VI has only 7 characters of slack, which is worth knowing
before someone edits it and gets rejected at submission time.

JA carries the same TODO(review-ja) caveat as the in-app dictionary.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:20:05 +07:00
poli0981andClaude Opus 5 1c0da6f0e8 docs: write the runbooks a shipped extension needs
docs/13 had only a first-submission runbook, so nothing described how to ship
v1.0.1 — nor what to do when an update is rejected, when the item is taken
down, or when a tag was pushed and the release run died half-way. All four are
now reachable in a way they were not before the listing went public.

- docs/13: §1 marked historical (and its never-performed step 8 handed to
  docs/11 §5). New §1b update runbook — the bump must reach main *before* the
  tag, because release.yml compares the built manifest against the tag; the
  store artifact is the Release asset, not the CI artifact, because that is
  what SHA256SUMS.txt covers. New §7: a rejected update leaves the published
  version live, so it is not an emergency; a rejected version string can never
  be reused, so the fix ships as the next patch, not as a re-upload; and there
  is no rollback in CWS at all — only a higher version carrying the revert.
- docs/12: the sample YAML had drifted twice (setup-node v6 vs the live v7, and
  a missing check:manifest in the release job). Docs win here, so reconciling
  the wrong way would have downgraded a pinned action and deleted a gate — both
  fixed, with a note that this is the one doc where the running pipeline is the
  ground truth. §2.4 gains the if:/continue-on-error that stops
  notify-ci-failure failing on every green CI run for want of a secret.
  §5's checklist now distinguishes verified from unknown instead of reading as
  eight things nobody did.
- docs/11: §2's inventory named four fixtures that do not exist and omitted two
  that do; each phantom is removed only after naming the test that actually
  covers its behaviour. §5 gains the upgrade pass — installing the published
  build, updating over it, and proving the legal flag and settings survive —
  which is the only failure mode that hits every user at once. §6's parse
  budget gains a procedure now that a generator exists to make the file.
- docs/14 §3 stopped embedding drafts of documents users have already accepted
  (its copy still carried `Last updated: 2026-⚠️`). It now points at the
  committed files and specifies when a change bumps LEGAL_VERSION, since that
  re-shows the gate to everybody.
- SECURITY.md: supported versions (latest published only — Chrome auto-updates,
  so there is no population to back-port for), an email fallback for reporters
  without a GitHub account, and an honest split between "fix prepared in 14
  days" and "fix reaching users", which additionally needs store review.
- legal/PRIVACY.md: says what happens to a file you send us. Deliberately not a
  LEGAL_VERSION bump — it clarifies handling of data a user chooses to send,
  which was never inside "what the Extension collects", and re-gating every
  installed user over a clarification is the worse outcome.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:20:05 +07:00
poli0981andClaude Opus 5 18d112a00f docs: record that v1.0.0 is published, not in review
The suite froze at the moment of submission and still said "in review" a week
after the listing went public. Since docs win over code here, a stale spec is a
false spec — and one of its "still open" items (the store URL for the README)
had already been closed by ea246aa.

- docs/00: status is published with the listing URL; the store item id and
  listing URL join the §9 canonical identifiers table, because the id is also
  the CHROME_EXTENSION_ID secret v1.1 automation needs; §8's approval criterion
  marked achieved; §10 item 5 resolved and item 6 rewritten — DISCORD_CI_WEBHOOK
  is not optional in practice, since notify-ci-failure.yml fails on every CI
  completion without it. Two new post-launch items: the JA native review pass
  (now shipping to users) and the never-performed post-approval smoke test.
- docs/15: the progress table gains a published row and a Phase 6 row; v1.0.x
  stops being speculative and becomes the live workstream, with the intake path
  spelled out end to end and a release trigger. Decision log: the Changelog-link
  row is marked resolved, the two-tab known limitation superseded, and twelve
  rows added for the Phase 6 design — recorded before the code, as the project's
  own docs-first rule requires.
- docs/06 §3.5: the Changelog link points at CHANGELOG.md (it has since Phase 5)
  and About gains a store listing entry. Also states why no support email
  appears in the UI: an in-product address invites unsanitized bookmark files.
- CLAUDE.md: leads with the fact that this is shipped software, and what that
  changes. Records EditTab.svelte back at 481 lines rather than the 459 it
  claimed, adds a Phase 6 section, and adds the worktree bootstrap gotcha.

Also adds `verify:full`, because hard rule 8 now points at it. `verify` omits
coverage, build and check:manifest, all of which a tag run enforces — so a core
change can pass every documented local step and fail only after the tag is
pushed, when gh release create has already run and cannot be re-run.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:20:05 +07:00
poli0981 ea246aad68 Update Chrome Web Store link in README 2026-07-27 11:12:22 +07:00
poli0981andClaude Opus 5 bbf0ae73b2 docs: record the v1.0.0 release and what is still open
Status header, the docs/15 progress table and the docs/00 §10 manual list now
say where the project actually is: all six phases done, v1.0.0 tagged and
released, submitted to the Chrome Web Store and in review.

§10 gains two items that were being carried in commit messages and memory
rather than anywhere a reader would find them:

- `npm run dev:firefox` is untested against the dependency overrides. Four of
  them sit under web-ext-run and no gate exercises that script. Firefox is a
  v1.0 non-goal so it blocks nothing, but nobody should assume it works.
- The 2 s parse budget is unmeasured on a real browser. The recorded 2869 ms is
  a jsdom figure and settles nothing either way.

The decision log gains the overrides rationale and why the release
announcement is continue-on-error.

The review-habit note is updated with phase 4 and 5 (19-of-33 and 8-of-20
confirmed), plus the two patterns this build kept demonstrating: the worst
findings were in work added earlier in the same branch, and three defects
reached main that no automated gate could have caught — a missing space, a
glyph that reads as a letter, and a permission grant that failed CI at startup
with no jobs and no log.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 18:35:45 +07:00
poli0981andClaude Opus 5 5f4c6e7b1f fix(ci): a missing Discord webhook must not fail a good release
The real v1.0.0 run went red. The release job itself succeeded — the GitHub
Release, bookmarkmagic-1.0.0-chrome.zip and SHA256SUMS.txt all published, and
`sha256sum -c` verifies against the downloaded asset. Only `announce` failed,
with "No webhooks configured", because DISCORD_RELEASES_WEBHOOK and
DISCORD_REPO_WEBHOOK are unset — which docs/12 §5 lists as optional.

A red run on a correct release is worse than a missing announcement: it trains
you to stop reading the colour. `continue-on-error: true` on the announce job.

The tag_override fix from the Phase 5 review did work — the job reached the
webhook check, which it could only do after resolving the tag.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 17:45:42 +07:00
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
149 changed files with 12477 additions and 5319 deletions

No files matched your search

+7 -2
View File
@@ -1,5 +1,10 @@
# Default: normalize to LF in the repo, check out native.
* text=auto
# Default: normalize to LF in the repo AND in every checkout.
#
# `eol=lf` and not "check out native": Biome's formatter (and every gate built
# on it) expects LF, so a Windows clone with core.autocrlf=true used to fail
# `npm run lint` on all 114 files before a single line had been edited. The
# two `#!/usr/bin/env node` scripts are also unusable from WSL with CRLF.
* text=auto eol=lf
# Fixtures are byte-exact samples of what real browsers and spreadsheets emit.
# EOL normalization would rewrite the CRLF records in the CSV exports, so a
+100
View File
@@ -0,0 +1,100 @@
name: Something else is broken
description: Anything that is not a bookmark file failing to import.
title: '[bug] '
labels: [bug]
body:
- type: markdown
attributes:
value: |
If a **bookmark file** will not import correctly, please use the
"A bookmark file will not import correctly" form instead — it asks for
the one thing that makes those fixable.
If this is a **security** problem, do not file it here. See
[SECURITY.md](https://github.com/poli0981/bookmarkmagic/blob/main/SECURITY.md).
- type: input
id: version
attributes:
label: BookmarkMagic version
description: Shown in the About tab and at the bottom of the window.
placeholder: '1.0.0'
validations:
required: true
- type: input
id: browser
attributes:
label: Browser and version
placeholder: Chrome 138, or Brave 1.79, or Edge 138
validations:
required: true
- type: dropdown
id: os
attributes:
label: Operating system
options:
- Windows
- macOS
- Linux
- ChromeOS
- Other
validations:
required: true
- type: dropdown
id: area
attributes:
label: Where does it happen?
options:
- Import
- Export
- Edit
- Settings
- About / legal gate
- The toolbar popup
- Somewhere else
validations:
required: true
- type: textarea
id: steps
attributes:
label: Steps to reproduce
placeholder: |
1. Open the manager
2. …
validations:
required: true
- type: textarea
id: expected-actual
attributes:
label: What did you expect, and what happened instead?
validations:
required: true
- type: textarea
id: console
attributes:
label: Console output
description: >-
Go to `chrome://extensions`, turn on Developer mode, and check whether
BookmarkMagic shows an "Errors" button. If it does, paste what is
there. Blank is a perfectly good answer.
render: shell
validations:
required: false
- type: checkboxes
id: confirmations
attributes:
label: Before submitting
options:
- label: >-
Anything I attached contains no real addresses, titles or personal
data.
required: true
- label: I searched the existing issues first.
required: false
+21
View File
@@ -0,0 +1,21 @@
# Issue chooser — docs/12 §5, docs/13 §6.
#
# Blank issues are disabled on purpose. The whole v1.0.x plan is "fixture +
# test per report" (docs/15), and that only works if a parser report arrives
# with a sanitized sample. A blank issue is the path that skips that ask.
blank_issues_enabled: false
contact_links:
- name: Security vulnerability
url: https://github.com/poli0981/bookmarkmagic/security/advisories/new
about: Report privately, never as a public issue. See SECURITY.md.
- name: Rate or review on the Chrome Web Store
url: https://chromewebstore.google.com/detail/bookmarkmagic/eghnciphhegekmnofffpgbdfefckdhmg
about: Reviews are read, but a bug reported here gets fixed faster.
- name: Question, or no GitHub account
url: mailto:contact@poli0981.dev
about: >-
Email works. Please do not attach your real bookmarks file — see the
privacy policy for what happens to anything you send.
@@ -0,0 +1,56 @@
name: Suggest a feature
description: An idea for something BookmarkMagic should do.
title: '[feature] '
labels: [enhancement]
body:
- type: markdown
attributes:
value: |
Before writing: this project has a short, deliberate
[never list](https://github.com/poli0981/bookmarkmagic/blob/main/docs/15_ROADMAP.md).
Cloud sync, accounts, analytics of any kind, and anything that would
require new browser permissions are out of scope permanently — not
because they are hard, but because "offline, two permissions, no
network" is the entire point of the extension.
Everything else is genuinely open. The roadmap in that same file lists
what is already planned.
- type: textarea
id: problem
attributes:
label: What are you trying to do?
description: >-
The situation, not the solution. "I move between four machines and
cannot tell which export is newest" tells us more than "add a
timestamp column".
validations:
required: true
- type: textarea
id: proposal
attributes:
label: What would you like it to do?
validations:
required: true
- type: textarea
id: workaround
attributes:
label: How do you handle it today?
description: Including "I don't" — that is useful signal about severity.
validations:
required: false
- type: checkboxes
id: confirmations
attributes:
label: Before submitting
options:
- label: >-
As far as I can tell, this would not need any new browser
permission, and does not involve a server, an account, or sending
data anywhere.
required: true
- label: I checked the roadmap and the never list.
required: false
+118
View File
@@ -0,0 +1,118 @@
name: A bookmark file will not import correctly
description: A file was rejected, or imported with the wrong structure, titles or dates.
title: '[parser] '
labels: [bug, parser]
body:
- type: markdown
attributes:
value: |
Thank you — this is the most useful kind of report this project gets.
A sanitized sample of the file becomes a permanent test, so the same
bug can never come back.
**Please sanitize the file first.** From a clone of this repository:
```bash
node scripts/sanitize-bookmarks.mjs your-file.html
```
It replaces every address and title but keeps the structure, encoding
and date format the bug actually depends on — so the sanitized file
still reproduces the problem, without telling us where you browse.
- type: input
id: source-browser
attributes:
label: Which browser produced the file, and which version?
description: >-
The exact version matters more than you would expect — export formats
differ between browsers and change between versions.
placeholder: Firefox 145, or Safari 18.2 on macOS, or "no idea, it is old"
validations:
required: true
- type: dropdown
id: format
attributes:
label: File format
options:
- HTML (the usual "bookmarks.html" export)
- Chrome / Edge / Brave profile "Bookmarks" file
- Firefox JSON backup (bookmarks-YYYY-MM-DD.json)
- BookmarkMagic JSON
- CSV
- Not sure
validations:
required: true
- type: dropdown
id: symptom
attributes:
label: What went wrong?
options:
- The whole file was rejected
- It imported, but folders are missing
- It imported, but the nesting is wrong
- It imported, but titles are mangled or empty
- It imported, but the dates are wrong
- Duplicates were detected wrongly (too many, or not at all)
- Something else
validations:
required: true
- type: textarea
id: message
attributes:
label: The exact message the extension showed
description: Copy it as shown, including the technical detail block if there was one.
render: text
validations:
required: false
- type: textarea
id: expected
attributes:
label: What did you expect instead?
description: >-
For a structure problem, describing the shape you expected — "these
three folders should be inside Bookmarks Bar" — is usually enough.
validations:
required: true
- type: textarea
id: sample
attributes:
label: Sanitized sample file
description: >-
Drag the sanitized file into this box to attach it. If the file is
large, a trimmed sanitized version that still reproduces the problem is
better than a complete one.
placeholder: Attach the file here.
validations:
required: true
- type: input
id: version
attributes:
label: BookmarkMagic version
description: Shown in the About tab and at the bottom of the window.
placeholder: '1.0.0'
validations:
required: true
- type: checkboxes
id: confirmations
attributes:
label: Before submitting
options:
- label: >-
I ran the sanitizer, or I checked the file by hand and it contains
no real addresses, titles or personal data.
required: true
- label: >-
I agree that this sanitized sample may be committed to this
repository as a test fixture under GPL-3.0, where it will stay
permanently and publicly.
required: true
- label: I searched the existing issues first.
required: false
+73
View File
@@ -0,0 +1,73 @@
name: A translation is wrong or awkward
description: Vietnamese or Japanese wording that is incorrect, unnatural, or untranslated.
title: '[i18n] '
labels: [i18n]
body:
- type: markdown
attributes:
value: |
Native speakers are the only people who can catch this. English is the
source language; Vietnamese is reviewed by the maintainer and Japanese
is best-effort until a native pass, so JA reports are especially
welcome.
You do **not** need to open a pull request or install anything — just
tell us the wording. If you would rather send the change yourself,
[CONTRIBUTING.md](https://github.com/poli0981/bookmarkmagic/blob/main/CONTRIBUTING.md)
has the whole path.
- type: dropdown
id: locale
attributes:
label: Language
options:
- Tiếng Việt (vi)
- 日本語 (ja)
validations:
required: true
- type: input
id: location
attributes:
label: Where does the text appear?
description: >-
A tab name and a description is plenty — "the Export tab, on the CSV
format card". If you happen to know the key path from
`src/lib/i18n/locales/`, even better.
placeholder: Settings tab, the theme row — or export.formats.csv.hint
validations:
required: true
- type: textarea
id: current
attributes:
label: Current text
description: Copy it exactly as it appears.
validations:
required: true
- type: textarea
id: proposed
attributes:
label: Suggested text
validations:
required: true
- type: textarea
id: why
attributes:
label: Why is the current wording wrong?
description: >-
Grammar, register, an unnatural loanword, a term inconsistent with the
rest of the UI — whatever it is. This is the part that makes the change
reviewable by someone who does not speak the language.
validations:
required: false
- type: markdown
attributes:
value: |
**One constraint worth knowing:** placeholders like `{n}` or `{name}`
must appear in the translation exactly as they do in English — same
names, same count. A build gate enforces it, so a suggestion that drops
one cannot be merged as-is.
+47
View File
@@ -0,0 +1,47 @@
<!--
Thank you for sending a patch. Delete anything below that does not apply —
a translation fix does not need the parser section, and vice versa.
-->
## What and why
<!-- What changes, and what problem it solves. Link the issue if there is one. -->
## Checklist
- [ ] `npm run verify` is green. (Release-bearing? `npm run verify:full` —
`verify` does not run coverage, build or the built-manifest gate.)
- [ ] Conventional Commits title (`fix(import): …`, `feat(edit): …`, `docs: …`).
- [ ] `CHANGELOG.md` `[Unreleased]` updated, if a user would notice this.
### If it changes behaviour
- [ ] The relevant `docs/` chapter is updated. **The docs are the specification
here** — when code and docs disagree, the docs win, so a behaviour change
that skips the doc leaves the spec lying.
### If it touches user-visible text
- [ ] The key exists in **all three** locales — `en`, `vi`, `ja`. `en.ts` is the
schema; `vi`/`ja` use `satisfies Dict`, so a missing key fails the type
check. Never add `as const` to a locale file.
- [ ] Interpolation tokens (`{n}`, `{name}`) match across all three.
### If it is a parser fix
- [ ] A fixture is committed under `tests/fixtures/`, sanitized, with the
reporter's consent recorded in the issue.
- [ ] A regression test lands **in this same PR** — a fixture with no test is
just a file.
- [ ] The quirk is noted in the parser source **and** in `docs/04 §1.2`.
- [ ] `docs/11 §2`'s inventory lists the new fixture.
### Things that are never OK
- [ ] No new runtime dependency. (Zero is the number, and it is a public claim
in the store listing and the README. A new dep needs approval first —
`docs/01 §4`.)
- [ ] No new permission. The manifest is exactly `["bookmarks", "storage"]`, and
changing that is a minor-version event that also requires re-certifying
the Chrome Web Store privacy answers.
- [ ] No `fetch`, `eval`, `{@html}` or `innerHTML`. `npm run guard` enforces it.
+72
View File
@@ -0,0 +1,72 @@
# 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, and they ignore `cooldown`.
# BookmarkMagic has zero runtime dependencies, so `npm audit --omit=dev`
# reports 0 and an advisory against the dev toolchain never reaches the
# published extension (docs/09 T5).
#
# `.npmrc` sets `min-release-age=7`, the same rule as `cooldown` below, for
# installs made by hand. A security PR for a version younger than 7 days can
# therefore fail to resolve until that version ages — the price of not being
# the first to install a compromised release. `npm ci` is unaffected: it
# installs whatever the lockfile pins.
version: 2
updates:
- package-ecosystem: npm
directory: /
schedule:
interval: weekly
day: monday
open-pull-requests-limit: 5
# Supply-chain cooldown (docs/01 §6): only propose releases that have been
# public for a week.
cooldown:
default-days: 7
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
# WXT is 0.x, so its "minor" is semver's breaking slot, and every WXT
# bump needs the BUILT manifest diffed by hand (docs/15 decision log,
# 2026-08-03). It gets its own PR so it can never ride along unseen.
exclude-patterns:
- 'wxt'
- '@wxt-dev/*'
ignore:
# The TypeScript pair is held on purpose (docs/01 §2): `@typescript/native`
# is the TS 7 `tsc`, `typescript` is the TS 6 API that svelte-check needs.
# A major on either is a documented decision, not a weekly bump.
- dependency-name: typescript
update-types: [version-update:semver-major]
- dependency-name: '@typescript/native'
update-types: [version-update:semver-major]
# Tracks the Node major in .nvmrc (docs/01 §2), so it moves with Node.
- dependency-name: '@types/node'
update-types: [version-update:semver-major]
- package-ecosystem: github-actions
directory: /
schedule:
interval: weekly
day: monday
open-pull-requests-limit: 3
cooldown:
default-days: 7
commit-message:
prefix: ci
include: scope
groups:
actions:
patterns: ['*']
+110
View File
@@ -0,0 +1,110 @@
# 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, audit 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
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version-file: .nvmrc
cache: npm
# --ignore-scripts: no dependency runs code at install time. `wxt prepare`
# (our postinstall) generates .wxt/tsconfig.json, which tsconfig.json
# extends, so it runs explicitly from the local binary.
- run: npm ci --ignore-scripts
- run: npx --no-install wxt prepare
- run: npm run lint # biome check .
- run: npm run check # svelte-check (TS 6 API) + tsc (TS 7) + scripts checkJs
- run: npm run knip
- run: npm run coverage # vitest --coverage, thresholds per docs/11 §1
- run: npm run guard # the zero-network / no-raw-HTML gate, docs/08 §3
# Zero runtime dependencies is a public claim (README, docs/09 T5); this
# is the check that keeps it true. Dev-only advisories are tracked by
# Dependabot and docs/09 §3.1, not here.
- run: npm audit --omit=dev --audit-level=low
# 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
windows:
# Not a required check. The owner develops on Windows, and the paths that
# only break there — drive letters and percent-encoding in script paths,
# CRLF in a checkout — had no CI coverage at all.
name: Windows smoke (guard + unit tests)
runs-on: windows-latest
timeout-minutes: 20
permissions:
contents: read
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version-file: .nvmrc
cache: npm
- run: npm ci --ignore-scripts
- run: npx --no-install wxt prepare
- run: npm run guard
- run: npm test
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'
# A string input, so it cannot read .nvmrc — keep it equal by hand
# (docs/01 §2).
node-version: '26'
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"]'
+45
View File
@@ -0,0 +1,45 @@
# Caller stub — docs/12 §2.4.
#
# The reusable filters to `conclusion == 'failure'` on the default branch
# internally, so the `if:` below is redundant for behaviour — but not for this:
# the reusable declares `DISCORD_CI_WEBHOOK` as `required: true`, and GitHub
# validates that BEFORE any of the reusable's own logic runs. With the secret
# unset (docs/00 §10.6) this workflow therefore failed on *every* CI completion,
# success included, from the first push after it landed.
#
# The `vars.DISCORD_CI_NOTIFY` gate on top of that, for the same reason
# `release.yml`'s announce job has one: a notification must never be able to
# change the colour of the thing it is reporting on. A run that is red for a
# reason nobody acts on teaches everyone to stop reading the colour.
name: Notify CI failure
on:
workflow_run:
workflows: ['CI']
types: [completed]
permissions:
contents: read
actions: read
jobs:
notify:
# Both conditions matter. The conclusion check stops this running at all on
# a green CI, which is what made it red on every push; the variable gate
# keeps it off entirely until the owner has actually set DISCORD_CI_WEBHOOK,
# since the reusable declares that secret `required: true` and GitHub
# validates it before the reusable's own filter runs.
#
# `continue-on-error` is NOT usable here: GitHub rejects it on a job that
# calls a reusable workflow ("Property continue-on-error is not allowed"),
# which invalidates the entire file. A repo variable is allowed in `if:`;
# a secret is not.
if: github.event.workflow_run.conclusion == 'failure' && vars.DISCORD_CI_NOTIFY == 'true'
uses: poli0981/.github/.github/workflows/notify-ci-failure.yml@main
permissions:
contents: read
actions: read
# Named, not `inherit`: the reusable is pinned to a moving branch, so it gets
# the one secret it declares and nothing else.
secrets:
DISCORD_CI_WEBHOOK: ${{ secrets.DISCORD_CI_WEBHOOK }}
+172
View File
@@ -0,0 +1,172 @@
# 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.
#
# Three jobs, least privilege first. `build` installs, runs every gate and
# packages with a READ-ONLY token; only `publish`, which installs nothing and
# runs no repository code, ever holds `contents: write`. Before this split one
# job ran `npm ci` — every dependency's install script plus our own tests —
# while holding a write token that checkout had also left in .git/config.
name: Release
on:
push:
tags: ['v*']
permissions:
contents: read
jobs:
build:
name: Gate + package
runs-on: ubuntu-latest
timeout-minutes: 20
permissions:
contents: read
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version-file: .nvmrc
cache: npm
- run: npm ci --ignore-scripts
- run: npx --no-install wxt prepare
# 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 audit --omit=dev --audit-level=low
- 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
- uses: actions/upload-artifact@v7
with:
name: release-${{ github.ref_name }}
path: |
.output/*-chrome.zip
.output/SHA256SUMS.txt
if-no-files-found: error
retention-days: 90
publish:
name: GitHub Release
needs: build
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: write # create the GitHub Release — the only write in this file
steps:
- uses: actions/download-artifact@v8
with:
name: release-${{ github.ref_name }}
path: dist
# The bytes about to be published are the bytes the build job hashed.
- name: Re-verify checksums
working-directory: dist
run: sha256sum -c SHA256SUMS.txt
# Idempotent on purpose. `gh release create` fails outright if a Release
# for the tag already exists, so any failure AFTER this step — realistically
# the store job below, once CWS_AUTOPUBLISH is on — used to strand the tag:
# re-running could not get past this line (docs/13 §7).
- name: Create or update the Release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
run: |
set -euo pipefail
if gh release view "$GITHUB_REF_NAME" >/dev/null 2>&1; then
echo "Release $GITHUB_REF_NAME exists — re-uploading assets."
gh release upload "$GITHUB_REF_NAME" dist/*-chrome.zip dist/SHA256SUMS.txt --clobber
else
gh release create "$GITHUB_REF_NAME" dist/*-chrome.zip dist/SHA256SUMS.txt \
--verify-tag --generate-notes
fi
store:
# v1.0.x/v1.1.x are published by hand (docs/12 §3). Flipping the repo
# variable CWS_AUTOPUBLISH to 'true' turns this on once the four CHROME_*
# secrets exist. A variable, not a secret: only variables are allowed here.
name: Publish to Chrome Web Store
needs: publish
if: vars.CWS_AUTOPUBLISH == 'true'
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: read
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version-file: .nvmrc
cache: npm
- run: npm ci --ignore-scripts
- uses: actions/download-artifact@v8
with:
name: release-${{ github.ref_name }}
path: dist
- name: Submit the Release asset
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 }}
# The locally installed wxt, never `npx wxt`: npx may fetch and run an
# unpinned package with these four secrets in its environment.
run: ./node_modules/.bin/wxt submit --chrome-zip dist/*-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: publish
# A Discord notification is not part of the release, so it can never turn a
# good release red (docs/12 §2.3). Gated on a repo VARIABLE — GitHub REJECTS
# `continue-on-error` on a job that calls a reusable workflow, which makes
# the whole file a startup_failure with zero jobs and no log.
if: vars.DISCORD_ANNOUNCE == 'true'
uses: poli0981/.github/.github/workflows/announce-release.yml@main
permissions:
contents: read
with:
# REQUIRED here: the reusable resolves `TAG="${INPUT_TAG:-$EVENT_TAG}"`
# with EVENT_TAG = github.event.release.tag_name — empty under
# `on: push: tags` — so without this the job exits 1 and never announces.
tag_override: ${{ github.ref_name }}
# Named, not `inherit`: the reusable is pinned to a moving branch, so it gets
# only the two webhooks it reads — never the CHROME_* or SONAR secrets. The
# names also differ: this repo stores RELEASES_WEBHOOK / REPO_WEBHOOK, while
# the reusable reads DISCORD_* — with `inherit` it received neither and would
# have failed on "No webhooks configured" the day DISCORD_ANNOUNCE was set.
secrets:
DISCORD_RELEASES_WEBHOOK: ${{ secrets.RELEASES_WEBHOOK }}
DISCORD_REPO_WEBHOOK: ${{ secrets.REPO_WEBHOOK }}
+79
View File
@@ -0,0 +1,79 @@
# SonarCloud — docs/12 §2.5.
#
# A separate workflow on purpose, not a job in ci.yml: a SonarCloud outage or a
# quality-gate opinion must never change the colour of CI, which is what branch
# protection reads ("Quality gates", "Build + package / build"). The verdict
# reaches the PR through the SonarCloud GitHub App's own check.
#
# ⚠️ Prerequisite: Automatic Analysis is OFF in the SonarCloud project
# (Administration → Analysis Method). With it on, the scanner refuses to run.
name: SonarCloud
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
concurrency:
group: sonarcloud-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
analyze:
name: SonarCloud analysis
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: read
steps:
- uses: actions/checkout@v7
with:
# Full history: Sonar's new-code detection and blame need it.
fetch-depth: 0
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version-file: .nvmrc
cache: npm
# --ignore-scripts: no dependency gets to run code at install time. Our own
# postinstall (`wxt prepare`) is the one script we need, so it runs
# explicitly — from the local binary, never fetched on demand.
- run: npm ci --ignore-scripts
- run: npx --no-install wxt prepare
# lcov for Sonar; the docs/11 §1 thresholds still gate core here too.
- run: npm run coverage
- name: Read the package version
id: pkg
run: echo "version=$(node -p "require('./package.json').version")" >> "$GITHUB_OUTPUT"
# The token is scoped to the two steps that need it, so the install and
# the test run above never see it. Dependabot and fork PRs get no repo
# secrets at all: they skip the scan with a notice instead of failing.
- name: Check for SONAR_TOKEN
id: token
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
run: |
if [ -n "$SONAR_TOKEN" ]; then
echo "present=true" >> "$GITHUB_OUTPUT"
else
echo "present=false" >> "$GITHUB_OUTPUT"
echo "::notice::SonarCloud scan skipped — SONAR_TOKEN is not available to this run (Dependabot or fork PR)."
fi
- name: SonarCloud scan
if: steps.token.outputs.present == 'true'
# Pinned to a commit, not a moving tag: this step holds a token. Dependabot
# proposes updates (with the repo's 7-day cooldown).
uses: SonarSource/sonarqube-scan-action@d209202bc7d53ff1cc128f7f907dac145c9d6ae9 # v8.3.0
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
with:
args: >
-Dsonar.projectVersion=${{ steps.pkg.outputs.version }}
+8 -4
View File
@@ -7,10 +7,14 @@ node_modules/
stats.html
stats-*.json
# Test / coverage
# Test / coverage (Vitest 5 writes reporter output under .vitest/)
coverage/
.vitest/
*.tsbuildinfo
# WXT runner config — holds local browser paths, never shared
web-ext.config.ts
# Editors
.idea/
.vs/
@@ -33,8 +37,8 @@ npm-debug.log*
.env.local
.env.*.local
# Generated fixtures that are too big to commit (tests/fixtures/generate-huge.ts
# writes here on demand — docs/11 §2)
# Generated fixtures that are too big to commit (scripts/gen-fixture.mjs writes
# here on demand — docs/11 §2)
tests/fixtures/generated/
.claude/
.claude/
+6
View File
@@ -0,0 +1,6 @@
# Supply-chain cooldown (docs/01 §6): resolve every install to the newest
# release that has been public for at least 7 days. Malicious versions
# published to npm have historically been caught and pulled within hours to
# days; a week of age keeps this repo out of that window. Units are DAYS.
# Dependabot applies the same rule through `cooldown` in dependabot.yml.
min-release-age=7
+1 -1
View File
@@ -1 +1 @@
24
26
+95
View File
@@ -0,0 +1,95 @@
# 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.1] — 2026-08-03
Released and submitted 2026-08-03; live on the Chrome Web Store (confirmed on
the listing 2026-10-28).
Stabilization, from the first pass over the shipped extension. No new features,
no change to permissions, and nothing you have to do — Chrome updates itself.
### Fixed
- If the browser refuses part of an import, the report now says how many
bookmarks were actually created, and — after a "replace everything" — names
the safety backup so you can restore. It used to say only that something went
wrong, while the items it had already written sat in your tree uncounted.
- Cancelling a "replace everything" after the deletion had begun said only how
many items were created, on a browser that was nearly empty. It now says what
happened and points at your backup.
- The import screen no longer offers a backup filename in the cases where no
backup was written.
- Pressing the browser's Back button during an import used to leave the manager
permanently stuck — every tab disabled, and no way out but closing it.
Navigation is now refused while an import is running, with an explanation.
- Two manager tabs no longer overwrite each other's settings, and accepting the
terms in one tab now unlocks the other.
- Errors in the Edit and Export tabs appear in your own language again, with the
browser's own message kept separately for bug reports.
- Clearing the search box no longer leaves every folder it opened expanded, and
collapsing a folder while searching now stays collapsed.
- "Keep the first of each" no longer offers to delete bookmarks managed by your
organisation, which the browser always refused, and says how many copies it
removed if it stops early.
- A profile with no writable bookmark folder now says so, instead of reporting a
refused operation.
### Added
- The import screen states that imported bookmarks carry today's date — the
browser does not let an extension set the original one. Your exported files
still keep the real dates.
- A link to the Chrome Web Store listing in the About tab.
- Bug-report forms, a contributing guide, and `scripts/sanitize-bookmarks.mjs`,
which strips every address and title from a bookmark file while keeping the
structure a parsing bug depends on — so a sample can be attached to a public
issue without publishing your browsing history.
## [1.0.0] — 2026-07-26
First public release. Approved by the Chrome Web Store and available to install
from 2026-08-03.
### 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.1...HEAD
[1.0.1]: https://github.com/poli0981/bookmarkmagic/compare/v1.0.0...v1.0.1
[1.0.0]: https://github.com/poli0981/bookmarkmagic/releases/tag/v1.0.0
+63 -4
View File
@@ -1,9 +1,26 @@
# CLAUDE.md — Build Instructions (BookmarkMagic)
You are building a Chrome MV3 extension: offline bookmark import/export/edit.
A Chrome MV3 extension: offline bookmark import/export/edit.
This file is the entry point; the `docs/` suite is the specification.
**When code and docs disagree, docs win — or stop and ask.**
> ## ⚠️ This is shipped software
>
> **BookmarkMagic is published on the Chrome Web Store and has real users**
> (v1.0.0 live by 2026-08-03; v1.0.1 live, confirmed on the listing
> 2026-10-28). Phases 0–6 are complete; the project is in **maintenance**.
> That changes the rules of the game:
>
> - Every change now reaches installed users through a store review. It needs a
> semver bump, a `CHANGELOG.md` entry and an update submission — `13 §1b`.
> - Breaking something is no longer a local cost. The 1.0.0 → 1.0.x **upgrade
> over an existing profile** (`11 §5`) is the one test whose failure hits
> every user at once.
> - Bumping `LEGAL_VERSION` re-shows the first-run gate to **everybody**. It is
> a deliberate, documented act (`14 §2`), never a side effect.
> - Read `docs/15`'s build-progress table and decision log before planning
> anything; `docs/00 §10` is the live open-items list.
## Doc index (read 00–02 fully before writing any code)
| Doc | Contents |
@@ -37,7 +54,11 @@ This file is the entry point; the `docs/` suite is the specification.
`satisfies Dict`, where `Dict = typeof dict` is exported from
`locales/en.ts`). **Never `as const` on a locale file** — docs/07 §2.
7. TypeScript strict; no `any`; casts need `// SAFETY:` comments.
8. Conventional Commits; `npm run verify` green before every commit.
8. Conventional Commits; `npm run verify` green before every commit — and
**`npm run verify:full` before anything release-bearing**. `verify` omits
three gates the tag run enforces (`coverage`, `build`, `check:manifest`), so
a core change that drops branch coverage passes locally and fails only after
the tag is pushed, when `gh release create` may already have run.
## Build phases (each ends with `npm run verify` green + a commit)
@@ -87,13 +108,51 @@ 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.
**Exit:** ready for the docs/13 §1 runbook (human performs store submission).
clean-install test. Also carried in from the Phase 4 review:
- ✔ About's "Changelog" link now targets `CHANGELOG.md`, pinned by
`tests/unit/links.test.ts`;
- ✔ `EditTab.svelte` split (589 → 459, under the hard limit). It grew back
through the Phase 5 and 6 review commits — **476 lines with a 356-line script
block** as of 2026-10-28, against a 150-line soft limit for script blocks
(docs/10 §1). Anything added there has to come out first; `src/lib/edit/` is
where extracted logic goes;
- ✔ contrast tokens fixed, and `tests/unit/styles/contrast.test.ts` now fails
the build on any text pair under 4.5:1. Two blind spots to know about: it is
token-level, so it cannot see the `opacity`-on-text bypass it was written to
catch, and its pair list is hand-maintained.
**Exit:** ✔ v1.0.0 submitted and published.
### Phase 6 — Post-launch stabilization → v1.0.1
The first phase written for shipped software. In order, because the docs are
binding and three of the code changes need the spec to say the new thing first:
docs reconciliation (this suite had frozen at "in review") → user-intake
machinery (`.github/ISSUE_TEMPLATE`, `CONTRIBUTING.md`, the sanitizer — docs/15
§v1.0.x's "fixture + test per report" had no intake at all) → import failure
reporting and the routing deadlock → localized `#edit`/`#export` failures and
bounded search expansion → cross-tab settings/legal sync → dependency bumps and
CI hardening → the About store link → cut 1.0.1.
**Exit:** ✔ v1.0.1 tagged and released 2026-08-03, live on the store
(confirmed 2026-10-28).
## Working style
- Small commits per module; tests land with (or before) implementation.
- **A git worktree needs its own `npm ci` *and* `npx wxt prepare`.** With an
empty `node_modules/` packages resolve upward from the parent repo and most
things appear to work, but knip reports every devDependency unused and
`verify` fails; `tsconfig.json` extends `./.wxt/tsconfig.json`, which
`wxt prepare` generates.
**Type resolution walks up too, and it does so even after a correct `npm ci`.**
A worktree under `E:\bookmarkmagic\.claude\worktrees\` inherits
`E:\bookmarkmagic\node_modules\@types\*`, so `npm run check` can pass locally
on types the package does not declare and CI does not have. That is exactly
how a missing `@types/node` survived a green local `verify` and failed CI on
the first push. A green local type-check in a worktree is weaker evidence than
it looks.
- When a browser fixture contradicts the format spec: add the fixture, make
the parser tolerant, note the quirk in code + docs/04 §1.2, then continue.
- Do not invent features not in docs; park ideas as `docs/15` roadmap PRs.
- Anything marked ⚠️ is human-only — surface it in your summary, don't fake it.
- Every phase so far has been adversarially reviewed after implementation and
**every review found real defects**. A green test run has never once meant
"done" on this project. Budget the review.
+71
View File
@@ -0,0 +1,71 @@
# Code of Conduct
## Our pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, caste, color, religion, or sexual
identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our standards
Examples of behavior that contributes to a positive environment:
- Demonstrating empathy and kindness toward other people
- Being respectful of differing opinions, viewpoints, and experiences
- Giving and gracefully accepting constructive feedback
- Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
- Focusing on what is best not just for us as individuals, but for the overall
community
Examples of unacceptable behavior:
- The use of sexualized language or imagery, and sexual attention or advances of
any kind
- Trolling, insulting or derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or email address,
without their explicit permission
- Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement responsibilities
Project maintainers are responsible for clarifying and enforcing these standards
and will take appropriate and fair corrective action in response to any behavior
that they deem inappropriate, threatening, offensive, or harmful.
Maintainers have the right and responsibility to remove, edit, or reject
comments, commits, code, issues, and other contributions that are not aligned to
this Code of Conduct, and will communicate reasons for moderation decisions when
appropriate.
## Scope
This Code of Conduct applies within all community spaces — the issue tracker,
pull requests, discussions and any project communication channel — and also
applies when an individual is officially representing the project in public
spaces.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the maintainers at **contact@poli0981.dev**. All complaints will be
reviewed and investigated promptly and fairly.
Maintainers are obligated to respect the privacy and security of the reporter of
any incident.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.1, available at
<https://www.contributor-covenant.org/version/2/1/code_of_conduct.html>.
[homepage]: https://www.contributor-covenant.org
+153
View File
@@ -0,0 +1,153 @@
# Contributing to BookmarkMagic
Bug reports, parser samples and translation fixes are all genuinely useful, and
none of them requires you to write code. If you only want to report something,
[open an issue](https://github.com/poli0981/bookmarkmagic/issues/new/choose) and
stop reading here — the forms ask for what is needed.
Security problems go through [`SECURITY.md`](SECURITY.md), never a public issue.
## Reporting a bookmark file that will not import
This is the most valuable report this project gets, because a sample becomes a
permanent test and the bug can then never come back.
**Sanitize the file first.** From a clone of this repository:
```bash
node scripts/sanitize-bookmarks.mjs your-bookmarks.html
```
It needs nothing installed — plain Node. It writes
`your-bookmarks.sanitized.html` next to the original, and prints what it found.
It reads the usual `bookmarks.html` export, a BookmarkMagic JSON file, Chrome's
profile `Bookmarks` file (also Edge, Brave and Vivaldi), a Firefox
`bookmarks-YYYY-MM-DD.json` backup, and our CSV. It refuses anything else rather
than guess, and it refuses to write if its own output still looks personal.
What it **destroys**: every hostname, path, query value and fragment; every
bookmark and folder title and description; Firefox keywords and tags; favicon
data; local `file:` paths; in JSON, every string except structural fields
(types, ids, timestamps), including Chrome's `meta_info` and sync blob.
What it **keeps**, because this is where the bug lives: the byte order mark, the
doctype, the `<META>` line, comments, line endings, indentation, tag and
attribute **case**, quoting style, attribute order, the tree's shape and depth,
every timestamp exactly as written, whether a URL had a port, how deep its path
was, whether it ended in a slash, how many query parameters it had, whether
there was a fragment, any percent-escapes, and any HTML entities in a title.
Distinct hosts stay distinct, so duplicate-detection bugs survive too.
That combination is the point: the sanitized file still reproduces the problem,
without telling us where you browse. A test in `tests/unit/scripts/` asserts
exactly that against every fixture in the repo.
Please do not send a real bookmarks file — an export is a browsing history.
Anything you attach to a GitHub issue is public and permanent; see
[`legal/PRIVACY.md`](legal/PRIVACY.md) for what happens to anything you email.
## Suggesting a translation fix
You do not need to clone anything. Use the translation issue form: the language,
where the text appears, what it says now, and what it should say. Vietnamese is
reviewed by the maintainer; **Japanese is best-effort until a native pass**, so
JA corrections are especially welcome.
One constraint if you send the change yourself: placeholders like `{n}` or
`{name}` must appear in the translation exactly as in English — same names, same
count. A build gate enforces it.
## Setting up to write code
Node **24 or newer** (see `.nvmrc`).
```bash
npm ci
npx wxt prepare
npm run verify
```
`wxt prepare` is not optional: `tsconfig.json` extends `./.wxt/tsconfig.json`,
which does not exist until it has run.
> **Using a git worktree?** It needs its own `npm ci` *and* `npx wxt prepare`.
> With an empty `node_modules/` the packages resolve upward from the parent
> checkout and almost everything appears to work — but knip then reports every
> devDependency as unused and `verify` fails in a way that looks like your
> change broke something.
Then `npm run dev` and load `.output/chrome-mv3` at `chrome://extensions` with
Developer mode on.
`npm run verify` runs lint, type-check, knip, the grep gate and the tests. It
must be green before every commit. For anything release-bearing use
`npm run verify:full`, which additionally runs coverage, the build, and the gate
that inspects the *built* manifest — `verify` alone is weaker than what CI and a
release tag enforce.
## The rules that are not negotiable
These are what the extension promises in its store listing and privacy policy,
so they are not style preferences:
- **Zero runtime dependencies.** Not "few". A new one needs discussion first.
- **Exactly two permissions**, `bookmarks` and `storage`. Changing that list is
a minor-version event that also requires re-certifying the store's privacy
answers.
- **No network access of any kind** — no `fetch`, `XMLHttpRequest`, `WebSocket`,
`EventSource` or `sendBeacon`. `npm run guard` fails the build on any of them.
- **No `eval`, `{@html}` or `innerHTML`.** File content reaches the DOM as text.
- `src/lib/core/` is pure: it imports nothing from `browser/`, `stores/`, Svelte
or `chrome.*`.
- Files stay under 300 lines (hard limit 500), functions under 50 (hard 80).
- Every user-visible string is an i18n key present in **all three** locales.
[`CLAUDE.md`](CLAUDE.md) is the entry point and [`docs/`](docs/) is the binding
specification — **where code and docs disagree, the docs win.** A behaviour
change that skips its doc leaves the spec lying, which is why the PR checklist
asks about it.
## Turning a reported file into a regression test
The full ritual, in order, because it is easy to do four fifths of it:
1. **Commit the sanitized sample** to `tests/fixtures/` (or `weird/`, or
`malformed/`). Note that `.gitattributes` sets `tests/fixtures/** -text`, so
line-ending normalization cannot rewrite the CRLF or BOM bytes the bug may
depend on — do not "fix" that.
2. **Add the regression test** to `tests/unit/core/fixtures.test.ts`, the only
parser regression suite. A browser export goes in its `BROWSER_EXPORTS` array,
which drives a shared set of assertions; anything else gets its own case.
There is no shared fixture-loading helper — that file has its own loader.
3. **Fix the parser** in `src/lib/core/parse/`. The test and the fix land in the
**same** pull request; a fixture with no test is just a file.
4. **Write the quirk down** in the parser source *and* in `docs/04 §1.2`. The
format chapter is where the next person looks to understand why the code is
shaped oddly.
5. **Update** `docs/11 §2`'s inventory and `CHANGELOG.md`'s `[Unreleased]`.
If the fix changes what a format is able to preserve, that is a specification
change: update `docs/04` first, then `tests/helpers/tree.ts`'s `project()` — it
models each format's documented lossiness, and widening it without the doc turns
a real regression into a passing test.
## Translations, in code
`src/lib/i18n/locales/en.ts` is the schema; `vi.ts` and `ja.ts` are typed
`satisfies Dict` against it, so a missing key is a compile error.
**Never add `as const` to `en.ts`.** It would make `Dict` a tree of string
*literal* types, and every correct translation would become a type error — the
only way to make the build pass would be leaving VI and JA in English.
Four gates run on every change: identical key paths across the three locales,
identical interpolation tokens per string, no empty leaves, and plural keys
carrying exactly `{one, other}` everywhere. See `docs/07` for register and tone
(VI: neutral-friendly, "bạn"; JA: です/ます with katakana loanwords).
## Commits and pull requests
Conventional Commits (`fix(import): …`, `feat(edit): …`, `docs: …`,
`chore(deps): …`). Small commits, one concern each; tests land with or before
the implementation. The PR template lists the rest.
+135
View File
@@ -0,0 +1,135 @@
# 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. The browser enforces it: the extension's content security
policy sets `connect-src 'none'`, so Chrome itself refuses any request an
extension page tries to make. On top of that, `npm run check:manifest` scans
the shipped bundle for network APIs and `npm run guard` scans the source.
- **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: [here](https://chromewebstore.google.com/detail/bookmarkmagic/eghnciphhegekmnofffpgbdfefckdhmg)
Requires Chrome 136 or later (April 2025), or any Chromium browser of the same
vintage — Edge, Brave, Vivaldi, Opera. On an older browser the store keeps the
version you already have and simply stops updating it.
From source (Node.js 26):
```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 —
[the issue forms](https://github.com/poli0981/bookmarkmagic/issues/new/choose)
ask for what is needed, and none of them requires you to write code.
If a bookmark file will not import, that is the most useful report there is,
because the sample becomes a permanent test. Sanitize it first:
```bash
node scripts/sanitize-bookmarks.mjs your-bookmarks.html
```
That strips every address and title but keeps the structure, encoding and
timestamps a parser bug depends on — so the sanitized file still reproduces the
problem without handing over your browsing history.
[`CONTRIBUTING.md`](CONTRIBUTING.md) has the rest: the setup, the rules that are
not negotiable, and how a reported file becomes a regression test.
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.
+37 -3
View File
@@ -1,22 +1,56 @@
# Security Policy
## Supported versions
| Version | Supported |
|---|---|
| The latest version published on the Chrome Web Store | ✅ |
| Anything older | ❌ |
There is no back-porting, and there is nothing for you to do to stay current:
Chrome auto-updates extensions once a new version passes store review. You can
see which version you are running in the extension's **About** tab, or on
`chrome://extensions`.
## Reporting a vulnerability
Report privately via **GitHub Security Advisories**:
<https://github.com/poli0981/bookmarkmagic/security/advisories/new>
No GitHub account? Email **contact@poli0981.dev** instead. Please say up front
that it is a security report.
Please do not open a public issue for a security problem.
Include, where possible: the affected version, a description of the impact, and
a minimal reproduction. If a bookmark file triggers the issue, attach a
**sanitized** sample — replace real URLs and titles with placeholders.
a minimal reproduction. If a bookmark file triggers the issue, **sanitize it
first**:
```bash
node scripts/sanitize-bookmarks.mjs your-file.html
```
That replaces every hostname, path, query value and title while preserving the
structure, encoding and timestamp shape a parser bug actually depends on — so
the sanitized file still reproduces the problem. `CONTRIBUTING.md` explains what
it keeps and why. Please do not send us a real bookmarks file; we would rather
have a slow reproduction than your browsing history. Anything you do send by
email is kept only as long as it takes to reproduce and fix the issue, and is
then deleted.
## Response targets
| Stage | Target |
|---|---|
| Acknowledgement | 72 hours |
| Fix or mitigation for High/Critical | 14 days |
| Fix prepared for High/Critical | 14 days |
| Fix **reaching users** | the above, plus Chrome Web Store review |
That last row is the honest one: a shipped fix has to pass store review before
Chrome rolls it out, and that step is not ours to control. If a defect is severe
enough to warrant it, we will say so publicly in the advisory so users can
mitigate — for this extension, that generally means "do not import untrusted
files until the update lands".
This is a hobby project with no bounty programme. Credit is given in the
release notes unless you ask otherwise.
+13 -2
View File
@@ -1,9 +1,20 @@
{
"$schema": "https://biomejs.dev/schemas/2.5.5/schema.json",
"$schema": "https://biomejs.dev/schemas/2.6.2/schema.json",
"vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true },
"files": {
"ignoreUnknown": true,
"includes": ["**", "!**/*.svelte", "!**/*.css", "!.output", "!.wxt", "!tests/fixtures"]
"includes": [
"**",
"!**/*.svelte",
"!**/*.css",
"!**/*.md",
"!**/*.yml",
"!**/*.yaml",
"!.output",
"!.wxt",
"!coverage",
"!tests/fixtures"
]
},
"formatter": {
"enabled": true,
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

+80 -13
View File
@@ -5,11 +5,23 @@
> **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:** **v1.0.0 is PUBLISHED on the Chrome Web Store and has real users.**
> Submitted 2026-07-26, approved and live by 2026-08-03 (⚠️ exact approval date
> to be recorded by the owner). Listing:
> <https://chromewebstore.google.com/detail/bookmarkmagic/eghnciphhegekmnofffpgbdfefckdhmg>.
> Signed tag `v1.0.0`, GitHub Release with a checksum-verified zip. Verified
> working on real Chrome and Brave.
>
> **v1.0.1 is PUBLISHED.** Tagged, released and submitted 2026-08-03; the
> listing was observed showing **version 1.0.1** (`Updated: August 3, 2026`,
> 5 users) on 2026-10-28. ⚠️ The exact approval date was never recorded — the
> owner can read it from the dashboard. Installed users are on 1.0.1.
>
> The project is now in **maintenance**, not construction: every change from
> here reaches installed users through a store review, so it needs a version
> bump, a CHANGELOG entry and an update submission (`13 §1b`). Sequencing lives
> in `/CLAUDE.md`; what is still open is in §10 below.
> **Doc suite version:** 1.7 (2026-10-28 — v1.0.1 published; v1.1.0 in progress)
---
@@ -86,7 +98,11 @@ One extension page with three capabilities:
## 8. Success criteria
- Chrome Web Store approval on first or second review pass.
- ✔ Chrome Web Store approval on first or second review pass — **approved**
between 2026-07-26 and 2026-08-03, with no rejection recorded (⚠️ owner: note
which pass, since it is the only evidence that the `08 §5` privacy answers and
permission justifications landed correctly, and the baseline against which a
future *update* rejection would be judged).
- Round-trip fidelity **at the file level**: `parse(serialize(tree))` reproduces
the tree, per-format and minus each format's documented losses — verified by
the automated suite (`11 §3`). Note what the platform does *not* allow:
@@ -112,6 +128,8 @@ Derived identifiers (canonical across docs and code):
| Own JSON schema | "BM JSON v1", `"format": "bookmarkmagic"` |
| Code prefix | `Bm*` (`BmParseError`, `BmAborted`) |
| Safety-backup filename | `bookmarkmagic-backup-YYYYMMDD-HHmm.json` |
| Chrome Web Store item id | `eghnciphhegekmnofffpgbdfefckdhmg` (also the value `CHROME_EXTENSION_ID` needs — `12 §3`) |
| Store listing URL | `https://chromewebstore.google.com/detail/bookmarkmagic/eghnciphhegekmnofffpgbdfefckdhmg` |
## 10. Manual action items (human-only) ⚠️
@@ -119,14 +137,63 @@ 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.
⚠️ **Store assets are unreconciled.** The listing is live, so whatever
`13 §2` requires was supplied — but nothing in the repo records what, or
where the originals live. `capture/` holds five README screenshots at
2512×1440 / 2560×1440, which are *not* the five 1280×800 store screenshots
`13 §2` specifies, and there is no 440×280 promo tile of any size. Owner:
either record where the submitted assets live, or correct `13 §2`.
4. ✔ Donate URLs resolved from `.github/FUNDING.yml` (`14 §5`).
Still open: contact email in `legal/PRIVACY.md`.
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").
✔ Contact email filled in and confirmed live: `contact@poli0981.dev`
(`legal/PRIVACY.md`), alongside the GitHub Issues link.
5. ✔ Chrome Web Store: developer account paid, item created, submitted
2026-07-26 and **approved — the listing is public and has users**. Listing
copy and the Privacy tab answers came from `13 §3` and `08 §5`. The store URL
landed in the README on 2026-07-27 (`ea246aa`) and the item id is now in the
§9 identifiers table. `store/listing.{en,vi,ja}.md` now hold the listing copy
`13 §4` always asked for — ⚠️ reconstructed from `13 §3` *after* the listing
went live, so diff them against the dashboard and correct the files.
**Still open:** the asset reconciliation in item 3.
6. Repo secrets + settings per `12 §5`. ✔ CodeQL "Default setup" is already
disabled (the advanced workflow uploads SARIF cleanly). **Still open:**
- `DISCORD_CI_WEBHOOK` is **not** optional in practice. `notify-ci-failure.yml`
calls a reusable that declares it `required: true`, so with the secret
unset that workflow fails on *every* CI completion — success or failure.
Either set it or accept the caller-side tolerance in `12 §2.4`.
- `DISCORD_RELEASES_WEBHOOK` / `DISCORD_REPO_WEBHOOK` genuinely are optional;
the announce job is skipped unless the repo variable `DISCORD_ANNOUNCE` is
`true`. (It used to say `continue-on-error`, which GitHub **rejects** on a
reusable-workflow caller — see `12 §2.3`.)
- The four `CHROME_*` secrets are now a **concrete v1.1 prerequisite**, not a
maybe: `15` lists automated CWS publishing as the first v1.1 item. One of
the four is already known — `CHROME_EXTENSION_ID` is the item id in §9. The
other three come from `npx wxt submit init` (`12 §3`). Note there is no
dry-run: the first time that step executes it makes a real submission.
7. **Untested:** `npm run dev:firefox`. No gate exercises it (Firefox is a
non-goal, §7). The `overrides` block that used to threaten it is gone
(`09 §3.1`), but do not assume it works.
8. **Unmeasured:** the 2 s parse budget on a real browser (`11 §6`). The
recorded 2869 ms is a jsdom figure and settles nothing. `scripts/gen-fixture.mjs`
now produces the file needed to measure it.
### Post-launch (added 2026-08-03)
9. **JA native review pass.** `src/lib/i18n/locales/ja.ts` carries the repo's
only `TODO` — "owner reviews VI; JA is best-effort until a native pass". It
was acceptable pre-launch; it is now shipping to users. `15 §v1.0.x` tracks
it, and the `translation` issue form is the intake for it.
10. **The published build has never been installed from the store and smoke
tested.** `13 §1` step 8 became due at approval and no result is recorded.
It is the only check that the artifact users actually receive matches what
was tested. Now folded into `11 §5` as a standing pre/post-submission item.
11. ✔ **v1.0.1 cleared review** — the listing showed 1.0.1 when checked on
2026-10-28, and the "published" row is in `15`'s progress table. ⚠️ Still
open: the exact approval date, and `13 §1b` step 10 against the published
build (install on a clean profile, re-run the upgrade check) — no result is
recorded for either.
## 11. Reading order
+42 -23
View File
@@ -1,6 +1,7 @@
# 01 — Tech Stack
> Versions verified against npm/official sources on **2026-07-25**.
> Versions verified against npm/official sources on **2026-10-28** (first pass
> 2026-07-25).
> Rule: latest stable or LTS only, with any deliberate exception stated inline.
> Re-verify minor/patch at scaffold time (`npm outdated`), but do NOT jump
> majors without a doc update.
@@ -10,24 +11,27 @@
| Item | Choice | Rationale |
|---|---|---|
| Browser | Chrome / Chromium, **Manifest V3** | MV2 is fully retired. Edge/Brave/Vivaldi/Opera work from the same build. |
| Min Chrome | `minimum_chrome_version: "120"` | Margin over our highest hard-floor API, `runtime.getContexts()` (116+). `scheduler.yield()` (129+) is used only behind a nullish fallback, so it does not raise the floor — see `08 §7`. |
| Runtime deps | **0 (zero)** | `DOMParser`, `Blob`, `URL`, `crypto.randomUUID` cover all needs. |
| Min Chrome | `minimum_chrome_version: "136"` (was `"120"` through v1.0.1) | The ES2025 floor: 136 is the first Chrome with every ES2025 built-in (`RegExp.escape` 136, `Float16Array` 135, `Promise.try` 128, iterator helpers and Set methods 122). The manifest floor, Vite's `build.target` (`chrome136`) and tsconfig's `lib: ["ES2025", …]` are one number stated three times — `wxt.config.ts` derives two of them from `CHROME_FLOOR`, and `tests/unit/manifest.test.ts` pins all three. Users on Chrome 120–135 keep the version they have and stop receiving updates; nothing is uninstalled. `scheduler.yield()` (129+) is now always present, though the write queue keeps its fallback because the test environment has no `scheduler`. |
| Runtime deps | **0 (zero)** | `DOMParser`, `Blob`, `URL`, `showSaveFilePicker` and `navigator.clipboard` cover all needs. "Zero" means no npm `dependencies`: the compiled Svelte runtime still ships inside the bundle — see `legal/THIRD_PARTY_NOTICES.md`. |
## 2. Toolchain (dev dependencies)
| Tool | Version (2026-07) | Role |
|---|---|---|
| Node.js | **24.x (Active LTS)** | Build runtime. Active LTS until Oct 2026, maintained to 2028-04-30. Node 26 is *Current*, not LTS — do not use for production tooling yet. |
| npm | bundled with Node 24 (v11) | Package manager. Commit `package-lock.json`. |
| **WXT** | **^0.20.27** | Extension framework: entrypoints, manifest generation, HMR, `wxt zip`, `wxt submit`. |
| **TypeScript** | **~6.0.3** (strict) | Deliberate exception to "latest stable": TS **7.0 went GA 2026-07-08** (7.0.2 is `dist-tags.latest`), but the Go-native compiler exposes no stable programmatic API yet and Microsoft's own GA post says Svelte/Volar toolchains "can only currently rely on TypeScript 6.0" — full support is deferred to 7.1. Since `svelte-check` is our template type authority, we hold on 6.x. Pin with `~` (patch-only). Revisit when TS 7.1 ships **and** svelte-check declares support. |
| **Svelte** | **^5.56.4** | UI, runes mode only (`$state`, `$derived`, `$effect`, `$props`). |
| @wxt-dev/module-svelte | latest at scaffold | WXT ↔ Svelte integration. |
| **Biome** | **2.5.2 (pinned exact)** | Lint + format (replaces ESLint + Prettier). Install with `npm i -D -E @biomejs/biome` per Biome guidance. |
| svelte-check | ^4.7.1 | Type/template authority for `.svelte` files. |
| **Knip** | **^6** (6.29.0 latest as of 2026-07) | Dead code: unused files, exports, dependencies. Requires Node ≥ 20.19. v6 swapped the TypeScript backend for oxc-parser — confirm `compilers.svelte` is still the supported `.svelte` hook before scaffold (`10 §4`). |
| **Vitest** | latest stable at scaffold | Unit tests for `src/lib/core`. |
| @vitest/coverage-v8 | match Vitest | Coverage reporting. |
| Node.js | **26.x (Active LTS)** (was 24.x through v1.0.1) | Build runtime. Node 26 entered Active LTS on 2026-10-28 (maintenance from 2027-10-20, end of life 2029-04-30); Node 24 moved to maintenance on 2026-10-20. `.nvmrc`, `engines` and every CI job say 26 — CI reads `.nvmrc` where it can, and passes `'26'` to the ops reusable, which takes a string input. |
| npm | bundled with Node 26 (v11.20+) | Package manager. Commit `package-lock.json`. `.npmrc` sets `min-release-age=7` (§6). |
| **WXT** | **^0.21.4** (was ^0.20.27 through v1.0.0) | Extension framework: entrypoints, manifest generation, HMR, `wxt zip`, `wxt submit`. **0.x, so a minor is semver's breaking slot** — and 0.21 was: `wxt/testing` split into `wxt/testing/fake-browser` and `wxt/testing/vitest-plugin`, and `tabs.create` is now typed as returning `void`. Both are dev-only. Never take a WXT bump without diffing the **built** manifest before and after (`12 §2.3`); `tests/unit/manifest.test.ts` reads `wxt.config.ts` and is structurally incapable of noticing. |
| **TypeScript** | **7.0 for `tsc`, 6.0 for the API** (strict) | Two packages under two names, Microsoft's documented side-by-side setup for toolchains that embed the compiler: `"@typescript/native": "npm:typescript@~7.0.2"` provides the `tsc` binary (the Go-native 7.0 compiler that type-checks every `.ts` file in `npm run check`), and `"typescript": "npm:@typescript/typescript6@~6.0.2"` keeps the TS 6.0 programmatic API under the `typescript` module name (it re-exports the real `typescript@6.0.x` and adds a `tsc6` binary). svelte-check (peer `typescript ^5 || ^6`) and Volar need that API — TS 7 has none until 7.1 — so `.svelte` files are checked by 6.0 and `.ts` files by both. `tsc --version` must say 7.x and `tsc6 --version` 6.x. Drop the alias when svelte-check declares TS 7 support. Both pinned `~` (patch-only). |
| **Svelte** | **^5.57.2** | UI, runes mode only (`$state`, `$derived`, `$effect`, `$props`). The compiled runtime ships in the bundle (MIT — `legal/THIRD_PARTY_NOTICES.md`). |
| @sveltejs/vite-plugin-svelte | ^7.3.1 | Compiles `.svelte` and the runes in `.svelte.ts` stores for Vitest (`vitest.config.ts`). Its `deepmerge` dependency carries the one advisory with no fix (`09 §3.1`). |
| @wxt-dev/module-svelte | ^2.0.5 | WXT ↔ Svelte integration. |
| **Biome** | **2.6.2 (pinned exact)** | Lint + format (replaces ESLint + Prettier). Install with `npm i -D -E @biomejs/biome` per Biome guidance. 2.6 started formatting Markdown and YAML; both are excluded in `biome.json` so docs and workflows keep their hand layout (`10 §3`). |
| svelte-check | ^4.7.7 | Type/template authority for `.svelte` files. Runs on the TS 6 API (see TypeScript above). |
| **@types/node** | **^26** (matches the Node major) | Types for `node:fs`, `node:path`, `node:child_process` and `process`, which the test suite and `scripts/*.mjs` genuinely use. **Declared explicitly since 2026-08-03** — it used to arrive transitively, and WXT 0.21 stopped providing it. Types only: erased at build, so hard rule 2 (zero *runtime* dependencies) is untouched. |
| jsdom | **^30.1** (was ^29 through v1.0.0) | Test DOM. Not interchangeable — `02 §3` picks jsdom over happy-dom because the Netscape walk depends on parse5's implied-end-tag behaviour. A major bump runs `tests/unit/dom-environment.test.ts` first; if that canary fails, pin rather than loosen the test. |
| **Knip** | **^6** (6.42.1 as of 2026-10) | Dead code: unused files, exports, dependencies. Requires Node ≥ 20.19. v6 swapped the TypeScript backend for oxc-parser — confirm `compilers.svelte` is still the supported `.svelte` hook before scaffold (`10 §4`). |
| **Vitest** | **^5.0.5** (was ^4 through v1.0.1) | Unit tests. 5.0 changed `clearMocks` to default `true`, requires `vi.mock` at top level and fails unawaited async assertions; the suite needed no changes. Requires Node ≥ 22.12. |
| @vitest/coverage-v8 | match Vitest | Coverage reporting (`text` + `lcov` for SonarCloud, `12 §2.5`). |
## 3. Explicitly rejected
@@ -52,22 +56,26 @@
```jsonc
{
"license": "GPL-3.0-or-later",
"engines": { "node": ">=24" },
"engines": { "node": ">=26" },
"scripts": {
"postinstall": "wxt prepare", // generates .wxt/tsconfig.json — 10 §2 extends it
"dev": "wxt",
"dev:firefox": "wxt -b firefox", // build sanity only, no store release
"build": "wxt build",
"zip": "wxt zip",
"check": "svelte-check --tsconfig ./tsconfig.json && tsc --noEmit",
"check": "svelte-check --tsconfig ./tsconfig.json && tsc --noEmit && tsc -p tsconfig.scripts.json",
// TS 6 API, the TS 7 tsc, then scripts/*.mjs via checkJs
"lint": "biome check .",
"lint:fix": "biome check --write .",
"knip": "knip",
"guard": "node scripts/guard.mjs", // canonical grep gate, 08 §3
"guard": "node scripts/guard.mjs", // the source gate, 08 §3
"check:manifest": "node scripts/check-manifest.mjs", // the built-artifact gate, 08 §3
"icons": "node scripts/gen-icons.mjs", // regenerates the shipped icons (source of truth)
"test": "vitest run",
"test:watch": "vitest",
"coverage": "vitest run --coverage",
"verify": "npm run lint && npm run check && npm run knip && npm run guard && npm run test"
"verify": "npm run lint && npm run check && npm run knip && npm run guard && npm run test",
"verify:full": "npm run verify && npm run coverage && npm run build && npm run check:manifest"
}
}
```
@@ -77,16 +85,27 @@
`npm ci` would otherwise fail type-checking.
`npm run verify` is the local gate — it must pass before every commit that
touches `src/` (mirrors CI, see `12_CI_CD.md`). CI additionally runs
`npm run coverage` for the threshold gate (`11 §1`).
touches `src/`.
It is **not** the same gate CI and a release tag run, and the difference bites:
both additionally run `coverage` (the `11 §1` thresholds), `build` and
`check:manifest`. A change to `src/lib/core/**` that drops branch coverage below
85 therefore passes every local step and fails only *after* the tag is pushed —
by which point `release.yml` may already have created the GitHub Release, which
is not re-runnable. `verify:full` closes that gap and is what `CLAUDE.md` hard
rule 8 requires before anything release-bearing.
Also set `repository`, `homepage` and `bugs` to
`https://github.com/poli0981/bookmarkmagic` — `13`/`14` link to those URLs.
Commit `.nvmrc` containing `24`.
Commit `.nvmrc` containing `26`.
## 6. Version pinning policy
- `typescript` → `~` (patch only; TS minors can break svelte-check).
- `@typescript/native` (TS 7 `tsc`) and `typescript` (the TS 6 API alias) → `~` (patch only; TS minors can break svelte-check). Dependabot ignores majors of both — a 7→8 or 6→7 jump is a doc decision, not a weekly bump.
- `@biomejs/biome` → exact (`-E`), formatter output must be reproducible.
- Everything else → `^`, with `package-lock.json` committed as source of truth.
- Renovate/Dependabot: weekly, grouped, majors require manual review.
- **Cooldown:** `.npmrc` `min-release-age=7` — installs resolve to the newest
release that has been public for 7 days (npm counts days). Dependabot uses the
same `cooldown`. Lockfile installs (`npm ci`) are not affected (`09 §3.1`).
- Renovate/Dependabot: weekly, grouped, majors require manual review; WXT
bumps arrive in their own PR (built-manifest diff, `12 §2.3`).
+26 -6
View File
@@ -46,11 +46,16 @@ log gives no warning — verify the output tree, not just the exit code.
bookmarkmagic/
├── CLAUDE.md # AI build instructions (root)
├── wxt.config.ts # srcDir + manifest + svelte module
├── biome.json / knip.json / tsconfig.json / vitest.config.ts
├── .nvmrc # 24
├── scripts/
│ ├── guard.mjs # canonical grep gate (08 §3), run by npm run guard
│ └── gen-icons.mjs # zero-dep placeholder PNG writer (16/32/48/128)
├── biome.json / knip.json / tsconfig.json / tsconfig.scripts.json / vitest.config.ts
├── sonar-project.properties # SonarCloud CI analysis (12 §2.5)
├── .nvmrc / .npmrc # Node 26; min-release-age=7 (01 §2, §6)
├── scripts/ # all plain .mjs, type-checked via checkJs
│ ├── guard.mjs # the source gate (08 §3), run by npm run guard
│ ├── check-manifest.mjs # the built-artifact gate (08 §3), npm run check:manifest
│ ├── gen-icons.mjs # zero-dep PNG writer — the icons' source of truth
│ ├── gen-fixture.mjs # large Netscape files for 11 §5/§6, never committed
│ ├── sanitize-bookmarks.mjs # reporter-facing sanitizer (CLI entry, 09 §6)
│ └── sanitize/ # its format modules: detect, mappers, spans, html, json, csv, leaks
├── docs/ # this suite (00–15)
├── legal/ # EULA.md, DISCLAIMER.md, PRIVACY.md, THIRD_PARTY_NOTICES.md
├── src/
@@ -77,20 +82,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/
@@ -205,7 +225,7 @@ submission (`08 §8`).
`browser/open-manager.ts`:
1. `browser.runtime.getContexts({ contextTypes: ['TAB'] })` → find an existing
manager context (requires Chrome 116+; we target 120+).
manager context (requires Chrome 116+; the floor is 136 — `01 §1`).
2. Found → `browser.tabs.update(tabId, { active: true })` +
`browser.windows.update(windowId, { focused: true })` (no `tabs`
permission needed for these calls).
+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)
+97 -9
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,56 @@ 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 ↗;
links: **GitHub repo ↗** · Report an issue ↗ · Changelog ↗ · Chrome Web Store ↗;
**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 `CHANGELOG.md` on `main`. (It pointed at the repo's
releases page until Phase 5 wrote that file — an empty releases page beats a 404
opened from a legal surface. `tests/unit/links.test.ts` now pins both the URL
shape and the file's existence, so the fallback cannot silently return.)
"Chrome Web Store" points at the published listing (item id in `00 §9`), added
once the item went public. It is the only route a user has from inside the
product to rate or review it, which `13 §6` depends on.
**No support email appears anywhere in the UI.** `contact@poli0981.dev` lives in
`SECURITY.md`, `CONTRIBUTING.md` and `legal/PRIVACY.md` only. An address on an
in-product surface invites users to mail their real bookmark file, and receiving
unsanitized personal URLs is exactly what `09` and the privacy policy are
written to avoid (`15` decision log, 2026-08-03).
## 4. Component inventory (`src/lib/components/`)
@@ -132,6 +204,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
+72 -30
View File
@@ -11,7 +11,7 @@ export default defineConfig({
name: '__MSG_appName__',
description: '__MSG_appDesc__',
default_locale: 'en',
minimum_chrome_version: '120',
minimum_chrome_version: String(CHROME_FLOOR), // 136 — the ES2025 floor, 01 §1
permissions: ['bookmarks', 'storage'], // ← the complete list, forever (v1)
action: { default_popup: 'popup.html' }, // WXT wires this automatically
options_ui: { page: 'manager.html#settings', open_in_tab: true },
@@ -34,32 +34,65 @@ deliberately avoids each (see `01_TECH_STACK.md §3`, `02_ARCHITECTURE.md §6`).
## 3. Code integrity rules
- **No remotely hosted code.** All JS/CSS ships in the package. No CDN
`<script>`, no `import()` of URLs, no `eval`, no `new Function`,
no string `setTimeout`. MV3's default extension CSP —
`script-src 'self' 'wasm-unsafe-eval'; object-src 'self';` — enforces this,
and Chrome rejects any manifest that loosens it. Never add a custom
`content_security_policy`.
- **No runtime network requests at all** (stronger than required): no
`fetch`, no remote favicons, no update pings. ⚠️ The default CSP does **not**
help here — it has no `connect-src`/`img-src` at all and restricts code
execution only, not network egress. The *only* thing enforcing the
zero-network promise is the grep gate below.
`<script>`, no `import()` of URLs, no `eval`, no `new Function`, no string
`setTimeout`. The extension-page CSP (below) enforces this, and Chrome
rejects any manifest that loosens the MV3 minimum.
- **No runtime network requests at all** (stronger than required): no network
calls, no remote favicons, no update pings. Three layers enforce it since
v1.1.0 — the browser, a build gate and a source gate:
#### The canonical grep gate
#### Layer 1 — the extension-page CSP (browser-enforced)
One pattern, defined **here and nowhere else**. `09 §1`, `09 §3`, `12 §2.1`
and §8 below all reference this block rather than restating it — four
divergent copies is exactly how a gate ends up weaker than the promise it
guards.
MV3's default extension CSP (`script-src 'self' 'wasm-unsafe-eval';
object-src 'self';`) restricts code execution only; it has no `connect-src` or
`img-src` at all. Until v1.0.1 that left a grep gate as the *only* thing between
the product and its zero-network claim. The production manifest now declares:
```
fetch\(|XMLHttpRequest|WebSocket|EventSource|sendBeacon|\beval\(|new Function|\{@html\}|(inner|outer)HTML\s*=|insertAdjacentHTML|import\s*\(
script-src 'self'; object-src 'none'; connect-src 'none'; img-src 'self' data: blob:;
style-src 'self' 'unsafe-inline'; font-src 'self'; media-src 'none'; frame-src 'none';
worker-src 'self'; form-action 'none'; base-uri 'none'
```
must return nothing across `src/` (which contains `entrypoints/` — `02 §2`
sets `srcDir: 'src'`), excluding `*.test.ts`. Implemented as
`scripts/guard.mjs` and run by `npm run guard`, so the same gate runs locally
(in `npm run verify`) and in CI — it cannot drift between them.
`connect-src 'none'` makes Chrome refuse every fetch, XHR, WebSocket,
EventSource and beacon from an extension page; the rest closes remote images,
stylesheets, fonts, media, frames and form posts. `style-src` keeps
`'unsafe-inline'` because Svelte sets `style` attributes; there is **no
`default-src`**, on purpose, because it would govern every unlisted directive. User-initiated
navigation — an About link, or "Open" on a bookmark via `tabs.create` — is not
governed by a page CSP and is not a request the extension makes (`09 §1`).
- **The rule is: only ever tighten.** Adding `'unsafe-*'`, a remote source, or
removing a directive is a security regression, and `check:manifest` fails on
any string other than the exact one above.
- **Production builds only.** `wxt.config.ts` emits it when the command is
`build` (so `npm run build` and `npm run zip`), because the dev server reloads
the extension over a localhost websocket that `connect-src 'none'` blocks.
- Vite's modulepreload polyfill is disabled (`modulePreload.polyfill: false`):
it was the one network call in the shipped bundle, dead code for every Chrome
at the floor.
#### Layer 2 — the built-artifact gate
`npm run check:manifest` (`scripts/check-manifest.mjs`) scans every `.js` file
in `.output/chrome-mv3` for network APIs — including code that arrived through
a dependency, which no source gate can see — and pins the manifest: MV3, the
permission list, the exact key set, the Chrome floor, the exact CSP, and that
every file the manifest and pages reference exists.
#### Layer 3 — the source gate
`npm run guard` (`scripts/guard.mjs`). **The rule set lives in that file, not
here** — this section used to restate it, and the copy drifted (its `\{@html\}`
matched only the literal `{@html}`). The script header explains each rule and
`tests/unit/scripts/guard.test.ts` holds a passing and a failing case for every
one, including the bypasses an audit found against the old line-by-line regexes
(aliases, computed global access, multi-line calls, `+=`, `{ @html }`, remote
`url()` in CSS, resource hints). It scans `src/**` — `.ts`, `.svelte`, `.html`,
`.css` and friends — with no exemptions, matches across line breaks, and fails
if it scanned nothing. Because identifiers are banned outright, the bare API
names cannot appear in `src/` comments either; write "network call".
- **Minification: yes. Obfuscation: NO.** CWS has prohibited obfuscated code
since 2018; WXT/Vite default minify (whitespace/identifier shortening) is
allowed and sufficient. Never add an obfuscator plugin. Open-source repo +
@@ -88,7 +121,7 @@ data-usage checkboxes. That is *not* the same as being exempt from disclosure:
CWS requires extensions to describe how they handle user data **even when the
handling is entirely local**, which is why the privacy-policy URL above is
mandatory and why `legal/PRIVACY.md` spells out the local bookmark reads/writes
and the `chrome.storage.local` settings explicitly (`14 §3.1`).
and the `chrome.storage.local` settings explicitly (`14 §3`).
The single-purpose text (§4) and the per-permission justifications (§2) are
also submitted on this tab — keep all three in sync, and re-certify whenever
@@ -114,11 +147,19 @@ any of them changes (`09 §4`).
event-driven only.
- Extension pages (popup/manager) may use `DOMParser`, `Blob`, `<a download>`
freely — these need no permissions.
- `browser.runtime.getContexts()` (Chrome 116+) is our highest **hard**-floor
API → `minimum_chrome_version: 120` gives margin. `scheduler.yield()`
(Chrome 129+) is used only behind the nullish fallback in `05 §6`, so it does
not raise the floor — but that fallback only works if it is written with
explicit parentheses; see the warning there.
- **The floor is Chrome 136** (`minimum_chrome_version: "136"`, since v1.1.0;
120 before). It is set by the language, not by an extension API: 136 is the
first Chrome with every ES2025 built-in, and tsconfig's `lib` is ES2025
(`01 §1`). The highest extension-API floors are far below it —
`browser.runtime.getContexts()` needs 116 and `scheduler.yield()` 129 — so
`scheduler.yield()` is in fact always present. The write queue still keeps
its nullish fallback (`05 §6`) because the test environment has no
`scheduler`; it only works if written with explicit parentheses, see the
warning there.
- Raising the floor is a **user-visible** event even though it is not a
permission change: a user below it keeps the installed version and simply
stops receiving updates. Say so in the CHANGELOG, and never raise it in a
patch release.
## 8. Review-readiness checklist (before every submission)
@@ -126,9 +167,10 @@ any of them changes (`09 §4`).
"Load unpacked" on a fresh profile.
- [ ] Manifest diff reviewed — permission list unchanged (`bookmarks`,
`storage` only).
- [ ] `npm run guard` passes (the canonical grep gate, §3). Note `{@html}` is
**not** catchable by Biome — no such rule exists for Svelte — so this
gate plus review is the whole enforcement.
- [ ] `npm run guard` and `npm run check:manifest` pass (§3: the source gate,
and the built-artifact gate that pins the CSP and scans the bundle). Note
`{@html}` is **not** catchable by Biome — no such rule exists for Svelte —
so the source gate plus review is its whole enforcement.
- [ ] Right-click → Options lands on `#settings` both on a fresh profile and
with a Manager tab already open on another route (§1 uses an undocumented
URL fragment; `02 §5`).
+109 -14
View File
@@ -4,9 +4,13 @@
1. **Zero data collection.** No analytics, no telemetry, no crash reporting,
no update pings. There is no server.
2. **Zero network activity at runtime.** Enforced by the canonical grep gate
defined in `08_MV3 §3` — that block is the single source of truth for the
pattern; do not restate it here.
2. **Zero network activity at runtime.** Enforced in three layers, all in
`08 §3`: the production CSP (`connect-src 'none'` — the browser itself
refuses), `check:manifest`'s scan of the shipped bundle, and the source gate
`scripts/guard.mjs`. Do not restate their rules here. Links the user
chooses to open (About, the legal documents, "Open" on a bookmark) load in a
browser tab; that is navigation the user asked for, not a request the
extension makes.
3. **Everything on-device.** Bookmarks are read/written via `chrome.bookmarks`
locally; files are parsed in-page and downloaded via Blob URLs. `chrome.
storage.local` holds only settings + legal flag (no `storage.sync` — even
@@ -21,18 +25,52 @@
| 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 with a 7-day cooldown + `min-release-age=7`; `npm audit --omit=dev` in CI; Biome installed exact-pinned. See §3.1. |
| 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
review. Biome has no rule for this: `noDangerouslySetInnerHtml` is a React
- `{@html}` — **forbidden**. Enforced by the source gate (`scripts/guard.mjs`,
`08 §3`) and review. Biome has no rule for this: `noDangerouslySetInnerHtml` is a React
rule and does not see Svelte templates.
- `innerHTML`, `outerHTML`, `insertAdjacentHTML` assignment — forbidden (same
gate).
- `innerHTML`, `outerHTML`, `insertAdjacentHTML`, `setHTMLUnsafe`,
`createContextualFragment`, `srcdoc`, `document.write` — forbidden outright,
reads included (same gate).
- All user/file-derived strings cross into the DOM only via Svelte text
bindings or `textContent`.
- `URL` constructor for any URL handling; no string-splitting of URLs.
@@ -44,6 +82,33 @@
≤120-char excerpt of the offending line (avoids log-injection weirdness in
screenshots/issues).
### 3.1 Dev-dependency advisories
**There is no `overrides` block any more** (removed 2026-10-28). The six pins
added on 2026-07-26 (`shell-quote`, `adm-zip`, `tmp`, `uuid`, `esbuild`,
`brace-expansion`) had all become dead: WXT 0.21 dropped `web-ext-run`, which
four of them sat under, and Vite 8 bundles with rolldown rather than esbuild.
None of the six packages was in the lockfile — and a stale override is worse
than none, because the day the package returns it silently pins it.
State after the v1.1.0 toolchain pass (Node 26, Vitest 5, Vite 8.3, WXT 0.21.4):
| Check | Result |
|---|---|
| `npm audit --omit=dev` | **0** — nothing third-party is a runtime dependency (CI runs this, `12 §2.1`) |
| `npm audit` (dev included) | 3 low, one root cause: **`deepmerge`** (GHSA-gcqx-w48m-w2h4, prototype poisoning in `mergeObject`), reached through `@sveltejs/vite-plugin-svelte`. **No fixed version exists.** It merges the build's own plugin options at dev/build time — never user data, never in the shipped extension — so it is accepted and recorded rather than overridden. Re-check when the plugin drops or bumps it. |
How new advisories are kept out:
- `.npmrc` sets `min-release-age=7`, and Dependabot's `cooldown` is 7 days:
a release must have been public for a week before this repo installs it. The
2025 npm compromises were caught and pulled within hours to days, so that
window is the point (`01 §6`).
- `npm ci` installs exactly what the lockfile pins and is unaffected by the
age rule — verified, not assumed.
- Dependabot *security* PRs bypass `cooldown`; one for a version younger than
a week may fail to resolve until it ages. That is the intended trade-off.
## 4. Permissions posture
`bookmarks` + `storage`, nothing else (justifications in `08 §2`). Any PR
@@ -52,14 +117,44 @@ 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
`SECURITY.md` in repo root (⚠️ create at scaffold): report privately via
GitHub Security Advisories; acknowledgment target 72h; fix-or-mitigate target
14 days for High/Critical. No bounty (hobby project) — credit given in
release notes.
`SECURITY.md` in the repo root is the policy in force. Summary:
- **Supported: the latest version published on the Chrome Web Store, only.** No
back-porting — Chrome auto-updates every installed copy once a release passes
review, so there is no population left behind to back-port for.
- Report privately via GitHub Security Advisories, or `contact@poli0981.dev` for
reporters without a GitHub account. Never a public issue.
- Acknowledgement 72 h; fix **prepared** within 14 days for High/Critical. Time
to *users* is that plus store review, which is outside our control — the
policy says so rather than implying a delivery guarantee we cannot make.
- No bounty (hobby project); credit in the release notes.
**Sample files from reporters.** A bookmark file is a browsing history, so the
policy asks reporters to run `scripts/sanitize-bookmarks.mjs` first — it rewrites
every hostname, path, query value, title, note, keyword and tag while preserving
the structure, encoding, and timestamps a parser bug depends on, so the sanitized
file still reproduces. It reads Netscape HTML, BookmarkMagic JSON, Chrome's
profile `Bookmarks` file, Firefox `.json` backups and our CSV, and refuses
anything else. JSON is rewritten default-deny (every string value except a short
list of structural keys). Before writing, it checks its own output — no host but
its `*.example` aliases, and for HTML no text left that is not a placeholder —
and writes nothing if that check fails. Until 2026-10-28 it accepted any JSON
and rewrote only `url`/`title`, so Chrome's profile file (titles under `name`)
came out with every title intact. Anything received by email is kept only as long as needed to
reproduce and fix, then deleted; `legal/PRIVACY.md` states the same to users.
This is the receiving-side counterpart to §3's rule that error messages never
echo more than a 120-character excerpt of file content.
+14 -6
View File
@@ -4,7 +4,7 @@
| Unit | Soft limit | Hard limit |
|---|---|---|
| File (.ts / .svelte) | **300 lines** | **500 lines** — split before merging |
| File (.ts / .svelte / .mjs) | **300 lines** | **500 lines** — split before merging |
| Function / method | 50 lines | 80 lines |
| Svelte component script block | 150 lines | move logic to a `.svelte.ts` store or `core/` |
| Nesting depth | 3 | 4 |
@@ -46,14 +46,18 @@ rather than assign `undefined`. Build nodes with conditional spreads
- Discriminated unions over boolean flags for state
(`{ kind: 'parsed', … } | { kind: 'error', … }`).
## 3. Biome — `biome.json` (2.5.x)
## 3. Biome — `biome.json` (2.6.x)
```jsonc
{
"$schema": "https://biomejs.dev/schemas/2.5.2/schema.json",
"$schema": "https://biomejs.dev/schemas/2.6.2/schema.json",
"vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true },
// Svelte and CSS are excluded on purpose — see the note below.
"files": { "includes": ["src/**", "tests/**", "*.ts", "!**/*.svelte", "!**/*.css"] },
// Svelte, CSS, Markdown and YAML are excluded on purpose — see the notes below.
"files": {
"ignoreUnknown": true,
"includes": ["**", "!**/*.svelte", "!**/*.css", "!**/*.md", "!**/*.yml", "!**/*.yaml",
"!.output", "!.wxt", "!coverage", "!tests/fixtures"]
},
"formatter": { "enabled": true, "indentStyle": "space", "indentWidth": 2, "lineWidth": 100 },
"javascript": { "formatter": { "quoteStyle": "single", "semicolons": "always", "trailingCommas": "all" } },
"linter": {
@@ -74,9 +78,13 @@ rather than assign `undefined`. Build nodes with conditional spreads
(`switch-every-tab-hotkey`) excludes `.svelte` and `.css` instead, and we
follow it rather than putting the build on an experimental flag.
**`svelte-check` is the authority** for everything inside `.svelte`.
- **Markdown and YAML are excluded since Biome 2.6**, which started formatting
both. The docs and workflow files are laid out by hand (long explanatory
comments, deliberate wrapping); letting a formatter own them would turn every
doc edit into a reflow diff.
- There is **no Biome rule that catches `{@html}`.** `noDangerouslySetInnerHtml`
is a React rule and does not apply to Svelte. The ban in `09 §3` is enforced
by the canonical grep gate (`08 §3`, run as `npm run guard`) and by review —
by the source gate (`scripts/guard.mjs`, `08 §3`, run as `npm run guard`) and by review —
not by the linter.
- `overrides` block: `noDefaultExport` must be relaxed for **`**/*.svelte`**,
not just `entrypoints/**` — every Svelte component is a default export,
+106 -10
View File
@@ -9,10 +9,13 @@
| Components/UI | Manual QA checklist (§5) | No component-test framework in v1 (cost/benefit) |
| End-to-end | Out of scope v1 (Roadmap: Playwright + `--load-extension`) | — |
`vitest.config.ts`: `plugins: [WxtVitest()]` (WXT aliases/auto-imports resolve
in tests), `environment: 'jsdom'`, `coverage.provider: 'v8'`,
`coverage.thresholds: { lines: 90, functions: 90, branches: 85 }` scoped to
`src/lib/core/**`.
`vitest.config.ts`: `plugins: [svelte(), WxtVitest()]` (the svelte plugin
compiles runes in `.svelte.ts` stores; WXT's resolves aliases and auto-imports),
`environment: 'jsdom'`, `coverage.provider: 'v8'`. Coverage **measures** every
`src/**/*.ts` module and writes `text` + `lcov` (SonarCloud reads the lcov,
`12 §2.5`), but only core is **gated**: a glob threshold
`'src/lib/core/**': { lines: 90, functions: 90, branches: 85 }`, so widening
what is measured cannot change what is enforced.
**Environment canary.** Add one test asserting that a Chrome fixture parses to
a `<DL>` nested *inside* its `<DT>` (`dl.querySelector('dt').querySelector(':scope > dl') !== null`).
@@ -33,18 +36,31 @@ malformed/doctype-only.html # valid doctype, zero <DL> → NO_BOOKMARKS
malformed/script-injection.html # <script> + onerror payloads (T1)
malformed/js-url.html # javascript: bookmark (T3)
weird/deep-nesting.html # depth 150 (under the 200 cap — tolerance)
weird/over-depth.html # depth 201 → TOO_DEEP (the cap itself)
weird/folder-with-dd.html # <DT><H3>/<DD>/<DL> — subtree must survive (04 §1.2)
weird/explicit-close-dt.html # literal </DT> → sibling-DL branch (05 §1)
weird/hr-separator.html # Firefox <HR> between entries → skipped
weird/add-date-zero.html # ADD_DATE="0" → omitted, NO warning
weird/mixed-wrapper.html # some roots wrapped, some not → root-list selection rule (04 §1.2)
weird/safari-no-wrapper.html # no wrapper <DL> at all → same rule, other branch
weird/emoji-rtl-titles.html # 🌸, RTL, CJK titles; & < > " entities
weird/microsecond-dates.html # Firefox-style timestamps
generate-huge.ts # script: emits 100k+1 node file on demand (not committed output)
```
Generated on demand, never committed: `scripts/gen-fixture.mjs` writes
arbitrarily large Netscape files into `tests/fixtures/generated/` (git-ignored)
for the 10k responsiveness item in §5 and the 100k parse measurement in §6.
Three behaviours have **no dedicated fixture** because a real browser export
already covers them, and a second file would only be a second thing to maintain:
| Behaviour | Covered by |
|---|---|
| `<HR>` separators skipped | `firefox-html-export.html` (`fixtures.test.ts` "firefox: DD does not eat the subtree, HR is skipped") |
| `ADD_DATE="0"` → omitted, **no** warning | `chrome-131-export.html` (same suite, asserted explicitly) |
| Depth past the cap → `TOO_DEEP` | built synthetically in `parse/netscape-html.test.ts` — cheaper and clearer than committing a 201-level file |
**Rule:** every browser-specific parser quirk discovered later gets a fixture
+ regression test in the same PR.
+ regression test in the same PR. `CONTRIBUTING.md` documents the full ritual
end to end; note `.gitattributes` sets `tests/fixtures/** -text` so EOL
normalization cannot rewrite the CRLF/BOM bytes a bug may depend on.
## 3. Core test suites (one file per module, mirrored paths)
@@ -130,14 +146,94 @@ 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: changing a setting in one **is** reflected in the
other, and accepting the gate in one drops the gate in the other. Also:
clearing storage in one must **not** re-raise the gate in the other —
acceptance is adopted in one direction only, by design (`03 §4`).
- [ ] Browser **Back** during a write: stays on `#import`, progress and Cancel
remain reachable, and a "busy" toast explains the refusal.
- [ ] Browser **Back** while the backup attestation is on screen: same. This is
the path that used to deadlock the Manager until the tab was closed.
- [ ] Right-click → Options **while a write is running**, with a Manager tab
already open. The deep-link is refused by the same guard; confirm it
behaves as `02 §5` describes rather than appearing to do nothing.
- [ ] The import report states that imported bookmarks carry today's date — in
EN, VI **and** JA.
- [ ] chrome://extensions → no errors logged during the whole pass.
- [ ] Edge (or Brave): smoke test install + import/export.
**Upgrade + published-build pass (every submission after the first):**
These have no equivalent in a first submission, and the upgrade item is the only
failure mode that would hit every installed user at once.
- [ ] Install the **currently published** version from the store on a clean
profile. Accept the gate, change two settings, import a fixture. This is
the prior state the upgrade test needs.
- [ ] Update that profile to the new build (load unpacked over it, or wait for
the store rollout). Then: the legal gate does **not** reappear
(`legal.acceptedVersion` survived), both settings survived, bookmarks are
untouched, and chrome://extensions logs nothing.
⚠️ If `LEGAL_VERSION` was bumped the gate *will* reappear for everyone —
that is `14 §2` working as designed, and it must be a deliberate decision
recorded in `15`, never a surprise found here.
- [ ] After the update goes live: install from the store on a clean profile and
smoke it. This is the only check that the artifact users receive is the
artifact that was tested (`13 §1b` step 10).
## 6. Performance budgets (checked manually in v1)
- Parse 25 MB / 100k HTML file: < 2 s.
- 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 29**:
| 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. ⚠️ Still unmeasured
(`00 §10.8`) — but no longer unmeasurable: the generator the original entry
assumed now exists.
**Procedure (reproducible, ~5 minutes):**
```bash
node scripts/gen-fixture.mjs --nodes 100000 --out tests/fixtures/generated/huge.html
npm run build # load .output/chrome-mv3 unpacked, fresh profile
```
Then in the Manager: open DevTools → Performance, drop the file on `#import`,
and time **drop → preview rendered**. Record the number, the Chrome version and
the machine below; a figure without those three is not comparable to anything.
| Date | Chrome | Machine | Drop → preview |
|---|---|---|---|
| ⚠️ | | | |
Re-measure whenever the jsdom major changes, since the table above is jsdom's
parse5 and not Chrome's parser — a jsdom bump invalidates the 2 869 ms row
rather than updating it. Add a column; do not overwrite.
+204 -185
View File
@@ -27,206 +27,184 @@ workflows use the `reusable-*` naming family. There is **no
## 2. Workflows (caller stubs in this repo)
### 2.1 `.github/workflows/ci.yml` — every push/PR to `main`
**This chapter no longer copies the workflow YAML** (decided 2026-10-28). It
used to, and the copies drifted three times: a Dependabot bump moved
`actions/setup-node` v6 → v7 in `.github/workflows/` and never touched this doc,
the `check:manifest` step added to the release job in `674ac34` was missing
here, and a copy kept `continue-on-error` after the file had dropped it.
Because docs win over code in this project, a stale copy is a standing
invitation to "reconcile" a pinned action backwards or delete a security gate.
**The workflow files are the ground truth about themselves.** What follows is
what a YAML file cannot say: why each job exists, what it must keep doing, and
the traps already stepped in.
The local `quality` job exists because the ops reusable workflow performs none
of it (§1). The `build` job delegates packaging.
Common to every job since v1.1.0:
```yaml
name: CI
- `actions/checkout` with `persist-credentials: false` — no job pushes, so no
job leaves a token in `.git/config`.
- `actions/setup-node` with `node-version-file: .nvmrc` (Node 26, `01 §2`).
The ops reusable takes a string input and cannot read the file, so `ci.yml`
passes it `'26'` — keep the two equal by hand.
- `npm ci --ignore-scripts`, then `npx --no-install wxt prepare`. No dependency
gets to run code at install time (SonarCloud S6505); our own `postinstall` is
the one script we need, so it runs explicitly, from the local binary, never
fetched. A local `npm ci` still runs `postinstall` normally.
- Reusable workflows get **named** secrets, never `secrets: inherit`: they are
pinned to the ops repo's moving `main`, so each one receives only what it
declares.
on:
push: { branches: [main] }
pull_request:
### 2.1 `ci.yml` — every push/PR to `main`
permissions:
contents: read
Three jobs. The two whose names branch protection requires (§5) are
`Quality gates` and `Build + package / build`.
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
- **`quality` — "Quality gates".** Local, because the ops reusable runs no
quality gates at all (§1). In order: `lint`, `check` (svelte-check on the
TS 6 API, then the TS 7 `tsc`), `knip`, `coverage` (`11 §1` thresholds),
`guard` (`08 §3`), `npm audit --omit=dev --audit-level=low` (the
zero-runtime-dependencies claim, `09 T5`), `build`, `check:manifest`. The last
two exist because the unit test over `wxt.config.ts` proves what we *asked*
for and only the built manifest proves what WXT *emitted* — a dev build of
the same config carries `tabs`/`scripting`/`host_permissions`.
- **`windows` — "Windows smoke (guard + unit tests)".** Not required. The owner
develops on Windows, and the failures that only happen there — drive letters
and percent-encoding in script paths, CRLF checkouts — had no CI coverage.
- **`build` — "Build + package".** Delegates packaging to
`reusable-chrome-extension.yml` with `package-manager: 'npm'`,
`node-version: '26'`, `build-command: 'npm run build'`,
`source-dir: '.output/chrome-mv3'`, `release: false`. 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.
jobs:
quality:
name: Quality gates
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: read
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v6
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 11 §1
- run: npm run guard # canonical grep gate, 08_MV3 §3
build:
name: Build + package
needs: quality
uses: poli0981/.github/.github/workflows/reusable-chrome-extension.yml@main
permissions:
contents: read
with:
package-manager: 'npm' # 01 §6 commits package-lock.json
node-version: '24'
build-command: 'npm run build'
source-dir: '.output/chrome-mv3' # WXT emits the manifest here
release: false
```
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.
drift between the two (`10 §3`).
### 2.2 `.github/workflows/codeql.yml`
### 2.2 `codeql.yml`
Use the current reusable (`reusable-codeql.yml`, CodeQL Action v4). Its input is
`languages` — a **JSON array encoded as a string**, not the singular `language`
of the older `codeql.yml`.
```yaml
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:
uses: poli0981/.github/.github/workflows/reusable-codeql.yml@main
permissions:
security-events: write
actions: read
contents: read
packages: read
with:
languages: '["javascript-typescript"]'
```
Calls the current reusable, `reusable-codeql.yml` (CodeQL Action v4). Its input
is `languages` — a **JSON array encoded as a string**
(`'["javascript-typescript"]'`), not the singular `language` of the older
`codeql.yml`. Weekly schedule plus push/PR to `main`; the permission block
(`security-events: write`, `actions: read`, `contents: read`, `packages: read`)
is repeated on the job because reusable workflows do not inherit it.
⚠️ **Prerequisite:** repo Settings → Advanced Security → CodeQL **"Default
setup" must be DISABLED**, or this advanced-setup workflow is rejected at SARIF
upload time.
### 2.3 `.github/workflows/release.yml` — on tag `v*`
### 2.3 `release.yml` — on tag `v*`
Standalone, **not** the ops reusable: the reusable's `release` job only does
`gh release create --generate-notes`. It produces no `SHA256SUMS.txt`
(required by `09 §5`), performs no store submission, and exposes no `outputs:`,
so a caller cannot reference the zip it built.
`gh release create --generate-notes`. It produces no `SHA256SUMS.txt` (required
by `09 §5`), performs no store submission, and exposes no `outputs:`, so a
caller cannot reference the zip it built.
```yaml
name: Release
Four jobs, least privilege first (split 2026-10-28):
on:
push:
tags: ['v*']
| Job | Token | Does |
|---|---|---|
| `build` "Gate + package" | `contents: read` | install, **every CI gate again** (a tag skips the branch triggers, and must never ship what a PR would have blocked), `zip`, `check:manifest`, the tag ↔ manifest version check, `SHA256SUMS.txt`; uploads both files as the artifact `release-<tag>` |
| `publish` "GitHub Release" | `contents: write` | downloads the artifact, `sha256sum -c` it, creates the Release with `--verify-tag` (or re-uploads to an existing one). Installs nothing and runs no repository code — the only job that ever holds a write token |
| `store` "Publish to Chrome Web Store" | `contents: read` | only when the repo variable `CWS_AUTOPUBLISH` is `'true'`: `./node_modules/.bin/wxt submit` with the Release asset — the local binary, never `npx wxt`, which may fetch an unpinned package into an environment holding the four `CHROME_*` secrets (SonarCloud S6505/S8543) |
| `announce` | `contents: read` | Discord, only when `DISCORD_ANNOUNCE` is `'true'` |
permissions:
contents: read
Before the split, one job ran `npm ci` — every dependency's install script plus
our own tests — while holding `contents: write`, with the token also left in
`.git/config` by checkout.
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@v6
with: { node-version: '24', cache: npm }
- run: npm ci
**The Release step is idempotent deliberately.** `gh release create` fails
outright when a Release for the tag already exists, so any failure *after* it —
realistically the store job, once `CWS_AUTOPUBLISH` is on — stranded the tag: a
re-run could not get past that line, and recovery meant deleting the Release
and the tag by hand. `docs/13 §7` documents the manual escape; this removes the
need for it in the common case.
# Same gates as CI — a tag must never ship what a PR would have blocked.
- run: npm run lint
- run: npm run check
- run: npm run knip
- run: npm run coverage
- run: npm run guard
The announcement is gated because the reusable exits 1 on "No webhooks
configured". On the real v1.0.0 run the Release, the zip and `SHA256SUMS.txt`
all published correctly and the run still showed red. A red run on a good
release trains you to ignore the colour, so the notification must not be able
to fail the release.
- run: npm run zip # wxt zip → .output/<name>-<version>-chrome.zip
⚠️ **It is gated with `if:` on a repo VARIABLE, not with `continue-on-error`.**
GitHub **rejects** `continue-on-error` on a job that calls a reusable workflow
(`Property continue-on-error is not allowed`), and a rejected file does not
fail one job — the whole run is a `startup_failure` with zero jobs and no log.
That sat undetected from `5f4c6e7` until 2026-08-03 because the commit landed
after the `v1.0.0` tag and no tag was pushed in between. A variable and not a
secret: secrets cannot be referenced in a job-level `if:`.
- 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; }
⚠️ **The webhook secrets are mapped by name.** This repo stores
`RELEASES_WEBHOOK` and `REPO_WEBHOOK`; the reusable reads
`DISCORD_RELEASES_WEBHOOK` and `DISCORD_REPO_WEBHOOK`. Under the old
`secrets: inherit` the reusable received neither, so the day `DISCORD_ANNOUNCE`
was set the job would have failed on "No webhooks configured". It now passes
each one explicitly under the name the reusable reads — found 2026-10-28 by
comparing the repo's secret list with the reusable's `workflow_call` block.
- name: SHA256SUMS
working-directory: .output
run: sha256sum *-chrome.zip > SHA256SUMS.txt
`tag_override` is **required**: 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 it the job exits 1 on "No
release tag available". The announcement is a **job inside this workflow**, not
a separate `on: release: [published]` caller, because a Release created by
`gh release create` under the default `GITHUB_TOKEN` emits no event that starts
new workflow runs.
- name: GitHub Release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
gh release create "$GITHUB_REF_NAME" \
.output/*-chrome.zip .output/SHA256SUMS.txt --generate-notes
### 2.4 `notify-ci-failure.yml`
- 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
Runs on `workflow_run` of CI, gated on
`conclusion == 'failure' && vars.DISCORD_CI_NOTIFY == 'true'`, and passes the
one secret the reusable declares (`DISCORD_CI_WEBHOOK`) by name. The reusable
declares that secret `required: true` and GitHub validates it before any of the
reusable's own logic, so without the gate this caller failed on **every** CI
completion, success included. `DISCORD_CI_WEBHOOK` exists (set 2026-07-26); the
variable is still unset, so notifications stay off until the owner opts in. A
notification must never be able to change the colour of the thing it reports
on.
announce:
needs: release
uses: poli0981/.github/.github/workflows/announce-release.yml@main
permissions:
contents: read
secrets: inherit
```
### 2.5 `sonarcloud.yml` — SonarCloud CI analysis
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
workflow runs, so an event-driven caller would silently never fire.
Added 2026-10-28, replacing SonarCloud's Automatic Analysis so the project gets
**coverage** and a scan of exactly what CI builds. Project
`poli0981_bookmarkmagic`, organisation `poli0981`; settings live in
`sonar-project.properties`.
### 2.4 `.github/workflows/notify-ci-failure.yml`
- **A separate workflow, not a job in `ci.yml`:** a Sonar outage or a
quality-gate opinion must never turn CI red. The verdict reaches PRs as the
SonarCloud GitHub App's own check. It is not a required check.
- Steps: full-history checkout (`fetch-depth: 0`, for new-code detection), the
common install, `npm run coverage` (which writes `coverage/lcov.info`), then the
scan with `-Dsonar.projectVersion=<package.json version>`, so "new code" means
"since the last release".
- The scan action is **pinned to a commit** (`v8.3.0`): it is the step that
holds `SONAR_TOKEN`, and the token is scoped to the two steps that need it.
Dependabot and fork PRs get no repository secrets, so the scan is skipped with
a notice instead of failing.
- Coverage: `vitest.config.ts` measures every `src/**/*.ts` module and reports
`text` + `lcov`; the CI *gate* is still the core-only glob threshold of
`11 §1`. `sonar.coverage.exclusions` drops components, entrypoints and
scripts — the same split as `11 §1`, where those are covered by the manual
pass and the script tests. The three locale files are excluded from
duplication detection: they are parallel by design.
- No `sonar.qualitygate.wait`: an unreviewed Security Hotspot can only be
cleared by a person in the Sonar UI, and a CI step that waits on a human is a
step that is red for a reason nobody can fix from the repo.
```yaml
name: Notify CI failure
⚠️ **Prerequisite:** Automatic Analysis must be **off** in the SonarCloud project
(Administration → Analysis Method). With it on, the scanner refuses to run.
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
```
The reusable already filters to `conclusion == 'failure'` on the default
branch, so the caller needs no `if:`.
Snyk is connected only as a GitHub App (the `security/snyk (poli0981)` PR
check); there is no `SNYK_TOKEN` and no Snyk step in any workflow.
## 3. Chrome Web Store publishing automation
@@ -239,7 +217,7 @@ produces the four values above → store as **repo Actions secrets**.
| Version | Method |
|---|---|
| v1.0.x (first listing + first reviews) | **Manual**: download the zip from the GitHub Release (not the CI artifact — the Release asset is the one `SHA256SUMS.txt` covers) → Dashboard upload → fill listing/privacy → submit. First reviews often ask questions; keep a human in the loop. |
| v1.0.x | **Manual**, per the `13 §1b` runbook: download the zip from the GitHub Release (not the CI artifact — the Release asset is the one `SHA256SUMS.txt` covers) → Dashboard → Package → upload new package → submit. The original rationale was "first reviews often ask questions"; in the event the first review asked nothing. It stays manual because none of the four `CHROME_*` secrets exists yet and `CWS_AUTOPUBLISH` is unset. |
| v1.1+ | **Automated**: the `Publish to Chrome Web Store` step in §2.3 runs after the Release succeeds, gated on the repo variable `CWS_AUTOPUBLISH=true` so it can be flipped off instantly if a review dispute is ongoing. |
Notes: uploaded builds still go through CWS review before rollout (automation
@@ -260,19 +238,60 @@ release: bump package.json (semver) → CHANGELOG.md (Keep a Changelog) →
## 5. Repo settings checklist (one-time ⚠️)
- [ ] Branch protection on `main`: require CI, require review, linear history.
Required checks are the **job** names — `Quality gates` and
`Build + package` — not the workflow name.
- [ ] CodeQL **Default setup DISABLED** (Settings → Advanced Security),
otherwise `codeql.yml` fails at SARIF upload (§2.2).
- [ ] Actions secrets: the four `CHROME_*` values (after `wxt submit init`).
- [ ] Actions secrets for Discord notifications (all optional — the reusables
skip cleanly when unset, except `DISCORD_CI_WEBHOOK` which
`notify-ci-failure.yml` declares `required: true`):
`DISCORD_CI_WEBHOOK`, `DISCORD_RELEASES_WEBHOOK`, `DISCORD_REPO_WEBHOOK`,
`DISCORD_PING_ROLE_ID`.
- [ ] Repo variable `CWS_AUTOPUBLISH=false` initially.
- [ ] Dependabot: npm weekly, grouped minors; `github-actions` ecosystem too.
- [ ] Issue templates: bug (asks for browser + a sanitized sample file),
feature, translation.
- [ ] GPG signing required for tags (matches tracker-repo practice).
Only the repo-visible items can be verified from a checkout; the rest live in
GitHub settings and stay ⚠️ until the owner confirms them. An unticked box here
means "unknown", not "not done".
- [x] Branch protection on `main` — configured 2026-08-03. Two corrections to
what this line used to say, both learned by applying it:
- **Required checks are `Quality gates` and `Build + package / build`.**
The old text said `Build + package`, the job name in `ci.yml`. That is
not what gets reported: a job that *calls a reusable workflow* publishes
its check as `<caller job> / <reusable job>`. Requiring the caller's
name alone matches nothing, so every PR waits forever on a check that
can never arrive — `main` becomes permanently unmergeable.
- **`required_approving_review_count: 0`, not 1.** "Require review" is
right for a team and a lockout for one maintainer, who cannot approve
their own pull request. Zero still forces every change through a PR and
through the checks above; it only drops the second pair of eyes that
does not exist. Raise it the day a second maintainer does.
Also set: linear history (matches the rebase-merge practice), no force
pushes, no branch deletion, conversation resolution required. **Admins are
deliberately NOT enforced** — with a single maintainer, an escape hatch
from your own protection rules is the difference between a safety net and
a locked door.
- [x] CodeQL **Default setup DISABLED** (Settings → Advanced Security) —
confirmed 2026-07-26; `codeql.yml` uploads SARIF cleanly, which is only
possible with it off (§2.2).
- [ ] ⚠️ Actions secrets: the four `CHROME_*` values (after `wxt submit init`).
`CHROME_EXTENSION_ID` is already known — it is the published item id in
`00 §9`. Required before `CWS_AUTOPUBLISH` can be flipped for v1.1.
- [x] Actions secrets for Discord notifications — **present as of 2026-10-28:**
`DISCORD_CI_WEBHOOK`, `RELEASES_WEBHOOK`, `REPO_WEBHOOK` (the last two under
names the reusable does not read; `release.yml` maps them, §2.3).
`DISCORD_PING_ROLE_ID` is optional and unset.
- [x] `SONAR_TOKEN` — set 2026-10-28, used only by `sonarcloud.yml` (§2.5).
- [ ] ⚠️ SonarCloud **Automatic Analysis OFF** (SonarCloud → bookmarkmagic →
Administration → Analysis Method). Required for §2.5; with it on, the CI
scan errors out. The owner agreed to switch it off on 2026-10-28.
- [x] Private vulnerability reporting **enabled** (verified 2026-10-28 via the
API) — `SECURITY.md` and the issue chooser send reporters there first.
- [ ] ⚠️ Repo variable `CWS_AUTOPUBLISH=false` initially. Note that when the
variable does not exist the expression is simply false, so "not configured"
and "configured off" are indistinguishable from a run's output.
- [ ] ⚠️ Repo variables `DISCORD_ANNOUNCE` and `DISCORD_CI_NOTIFY` — both still
unset (2026-10-28), so no notification fires. The webhook secrets now
exist, so either can be flipped to `true` whenever the owner wants the
posts. Unset means skipped; a reusable-workflow caller cannot use
`continue-on-error` to absorb a failure (§2.3).
- [x] Dependabot: npm weekly, grouped dev minor+patch, `github-actions` too —
`.github/dependabot.yml`. Both ecosystems have a 7-day `cooldown`
(matching `.npmrc` `min-release-age=7`, `09 §3.1`); WXT is excluded from
the group so every WXT bump arrives alone and gets its built-manifest
diff; majors of the TypeScript pair and `@types/node` are ignored.
- [x] Issue templates: `.github/ISSUE_TEMPLATE/` — bug, parser report (requires
a sanitized sample), translation, feature, plus a `config.yml` chooser.
Landed 2026-08-03; `13 §6` had asserted they existed since before launch.
- [ ] ⚠️ GPG signing required for tags (matches tracker-repo practice). The
`v1.0.0` tag object is in fact PGP-signed, so the practice held once.
+147 -9
View File
@@ -2,7 +2,13 @@
Developer account: registered & fee paid ✔.
## 1. First-submission runbook (v1.0.0)
## 1. First-submission runbook (v1.0.0) — ✔ completed 2026-07-26
**Historical.** Kept because it is the record of how the listing was created and
what was answered where. For every release after v1.0.0 use §1b instead — the
steps below are all first-listing shaped ("New item", filling the listing and
privacy tabs, setting distribution) and none of them is what a second submission
does.
1. `npm run verify` + full manual QA pass (`11 §5`) on a fresh profile.
2. Tag `v1.0.0` → CI produces the zip artifact (or `npm run zip` locally from
@@ -22,15 +28,78 @@ Developer account: registered & fee paid ✔.
community channels — posted automatically by the `announce` job in
`release.yml`, which calls the ops repo's `announce-release.yml`
(script: `.github/scripts/discord_notify.py`), see `12 §2.3`).
⚠️ **Never recorded as performed.** The approval landed and no result was
written down, so the one check that the *published* artifact matches what was
tested has not demonstrably happened. It is now a standing item in `11 §5`
rather than a one-off step here.
## 2. Asset checklist ⚠️ (create before submission)
## 1b. Update-submission runbook (v1.0.1 and every release after)
This is the procedure for shipping to an **existing** listing. The listing,
privacy and distribution tabs are already filled; you are replacing the package.
1. `npm run verify:full` + the full manual QA pass (`11 §5`) on a fresh profile,
**including the upgrade test over an existing profile** — that is the item
that has no equivalent in a first submission and the one whose failure hits
every installed user simultaneously.
2. Bump the version. Exactly **two** files change:
- `package.json` `version` (semver per `12 §4`);
- `CHANGELOG.md` — a new dated section **and** the link references at the
bottom of the file (`[Unreleased]` must compare against the new tag, and a
new `[X.Y.Z]` line must be added). Forgetting the link refs is the easy
half to miss.
`wxt.config.ts` declares no `version` key — WXT derives it from
`package.json` (`08 §5`). If it appears in your diff, something is wrong.
3. PR → CI green → merge to `main`. **The bump must be on `main` before the
tag**: `release.yml` reads the built `manifest.json` at the tagged commit and
fails the run when it does not equal the tag minus `v`.
4. ⚠️ Human: `git tag -s vX.Y.Z && git push origin vX.Y.Z`. Signed, per `09 §5`.
`release.yml` re-runs every gate, builds, zips, verifies tag↔manifest, writes
`SHA256SUMS.txt`, and creates the GitHub Release.
5. Download the **Release asset**, not the CI artifact — `SHA256SUMS.txt` covers
the Release asset only (`12 §3`). Verify with `sha256sum -c`.
6. Dashboard → the existing item → **Package → Upload new package** → the zip.
Do *not* create a new item.
7. Fill the "why this update" / what-changed note. Listing text and the privacy
answers stay as they are unless something actually changed — and if the
permission list or the data-handling answers did change, that is a
minor-version event which requires re-certifying the Privacy tab first
(`09 §4`, `08 §5`).
8. Consider a staged (percentage) rollout for anything touching the write paths.
There is no undo once a version is live, only a higher version (§7).
9. Submit. Review for a `bookmarks`+`storage`-only item is typically hours–days.
10. After it goes live: confirm the dashboard shows the new version, then
install/update on a clean profile and re-run the upgrade check from step 1
against the *published* build. Record the result in `15`'s progress table.
Chrome auto-updates installed extensions once the new version passes review;
users do nothing and, notably, get no prompt. That is why the upgrade test
matters more than any other single check here.
## 2. Asset checklist ⚠️
### Store assets (submitted — source of truth is the CWS dashboard)
| Asset | Spec |
|---|---|
| Icon | 128×128 PNG (also 16/32/48 in-package). Flat glyph: bookmark + swap arrows, violet `#6d4aff` on transparent. |
| Icon | 128×128 PNG (also 16/32/48 in-package). Flat glyph: bookmark + swap arrows, violet `#6d4aff` on transparent. Generated by `scripts/gen-icons.mjs`, which is the source of truth (`00 §10.3`). |
| Screenshots ×5 | 1280×800 PNG, real UI, EN locale, light theme: 1) Import preview+stats 2) Merge options+progress 3) Export format cards 4) Edit tree + duplicate panel 5) Dark theme overview |
| Small promo tile | 440×280 (required) |
| Marquee (optional) | 1400×560 — skip for v1.0 |
| Small promo tile | 440×280 (required by the dashboard) |
| Marquee (optional) | 1400×560 — skipped |
⚠️ **Unreconciled.** The listing is live, so the dashboard has whatever was
actually uploaded — but the repo does not, and nothing records where the
originals live. Anything here beyond the icon is currently unverifiable from the
repo. Owner: record the location, or correct this table to match what the
dashboard really required. Regenerating screenshots is required whenever the UI
changes (`08 §8`), which is impossible to do reliably from assets nobody can find.
### README screenshots (not store assets — do not confuse them)
`capture/` holds five PNGs at 2512×1440 / 2560×1440 used by `README.md`. They
are the wrong dimensions for the store and cover only four of the five required
subjects. `capture/Edit.png` is committed but unreferenced.
## 3. Store listing — EN (canonical)
@@ -85,8 +154,14 @@ https://github.com/poli0981/bookmarkmagic
**VI summary:** `Nhập, xuất & chỉnh sửa bookmark giữa các trình duyệt — offline, không tài khoản, không cloud. Dữ liệu không rời khỏi máy bạn.`
**JA summary:** `ブラウザ間でブックマークをインポート・エクスポート・編集。オフライン、アカウント不要、クラウド不要。データは端末から出ません。`
(Full VI/JA descriptions: translate §3 keeping structure; store in
`store/listing.{vi,ja}.md` in-repo so listing text is version-controlled ⚠️.)
Full VI/JA descriptions: translate §3 keeping structure. The canonical copy
lives in `store/listing.{en,vi,ja}.md` so listing text is version-controlled and
reviewable — a listing edit made straight into the dashboard has no diff and no
history.
⚠️ Those files were written from §3 **after** the listing went live, so they are
a reconstruction, not a transcript. Owner: diff them against what the dashboard
actually shows and correct the files, not the dashboard.
## 5. Update cadence & versioning
@@ -103,7 +178,70 @@ https://github.com/poli0981/bookmarkmagic
## 6. Post-launch monitoring (no telemetry ⇒ these channels only)
- CWS dashboard: user counts, ratings, review replies (reply within a week;
link issues to GitHub).
- GitHub issues — templates route bug reports with sample files.
link issues to GitHub). A store review is not a bug report — if it describes a
reproducible defect, open the GitHub issue yourself and reply with the link.
- GitHub issues — `.github/ISSUE_TEMPLATE/` routes them. `parser_report.yml`
requires a sanitized sample (`scripts/sanitize-bookmarks.mjs`) plus explicit
consent to commit it as a GPL-3.0 fixture, because that is what turns a report
into a regression test (`11 §2`, `15 §v1.0.x`).
- Discord servers (`#support` in the OSS server) — pin an FAQ post.
⚠️ The invite URL is not recorded anywhere in the repo.
- Review flow for feature requests: label → roadmap doc PR → milestone.
The three recurring questions are already answered in prose and make the FAQ
seed: favicons cannot be imported; imported bookmarks carry today's date (the
import report now says so itself); CSV is a flattened view. See §3's honesty
corner and README's "Honest limitations".
## 7. When something goes wrong after launch
None of this existed before v1.0.0 was live, and all of it is now reachable.
### An update is rejected
**The published version stays live.** An update rejection is not a takedown —
users keep running the previous version, so nothing is on fire and there is time
to read carefully.
1. Read the exact policy citation. Never argue past it (same rule as §1 step 7).
2. Fix, and bump the patch **again**. The store refuses a version string it has
already seen, so a rejected 1.0.1 comes back as 1.0.2 — not as a re-upload.
3. Never delete or move the tag of a rejected version. It is a real, published
GitHub Release and moving it invalidates its checksum. Leave it and move on.
4. Note the rejection and its resolution in `15`'s decision log — it is the only
memory the project has of what the reviewers actually object to.
### Rollback
There is no "revert to the previous version" in the Chrome Web Store. The only
rollback is **forward**: ship a higher version containing the revert. Plan
accordingly — a bad release cannot be recalled, only superseded, and the
superseding version has to pass review too.
### Takedown / unpublish / appeal
- **Unpublished** (by you or by Google): the listing disappears from search and
no one can install it. **Existing users keep the version they have** and it
keeps working; it simply stops receiving updates. GitHub Releases become the
only distribution channel, and the README install section should say so.
- Appeal through the developer support form, citing the specific policy. Attach
the permission justifications from `08 §5` — a `bookmarks`+`storage`-only,
zero-network extension has an unusually short defence to make, and `09`'s
threat model exists partly to make it.
- If a takedown is about data handling, `legal/PRIVACY.md` and the privacy-tab
answers must agree with the code exactly. `npm run guard` and
`npm run check:manifest` are the evidence that they do.
### A tag was pushed and the release run failed
`release.yml` runs `gh release create` with no existence check, so a failure
*after* that step (realistically the CWS publish step, once `CWS_AUTOPUBLISH` is
on) leaves a published Release that a re-run cannot recreate.
- If the Release and its two assets published correctly, the failure is
downstream — fix it and do the affected step by hand. Do **not** re-run the
workflow.
- If the Release is broken or incomplete: `gh release delete vX.Y.Z`, then
`git push --delete origin vX.Y.Z`, then re-tag. Only safe while nothing has
consumed the assets.
- Never move a tag that has already been announced or submitted.
+27 -73
View File
@@ -38,89 +38,43 @@ Storage keys are namespaced `legal.*` / `settings.*` (single
## 3. Repo `legal/` files (English canonical)
Linked from the gate, About tab, README, and the CWS privacy-policy URL.
Drafts below are ready to commit ⚠️ — fill placeholders, have a final human
read-through (docs are provided as-is, not legal advice).
Filenames follow the portfolio precedent: `legal/PRIVACY.md`,
`legal/DISCLAIMER.md`, `legal/EULA.md`, `legal/THIRD_PARTY_NOTICES.md` (the
notices file lives in `legal/`, not the repo root).
### 3.1 `legal/PRIVACY.md` (draft)
**The committed files are the canonical text — read them, not a copy here.**
This section used to embed drafts carrying `Last updated: 2026-⚠️` and
`⚠️ contact email` placeholders. Those were filled in Phase 0 and Phase 4, and
real users have now accepted the published wording in-product; a spec still
showing the unfilled draft was describing a document nobody has ever agreed to.
```markdown
# Privacy Policy — BookmarkMagic
Last updated: 2026-⚠️
### 3.1 Changing a legal document after launch
BookmarkMagic ("the Extension") is designed to work entirely on your
device.
The gate reappears for **every installed user** when `LEGAL_VERSION`
(`src/lib/core/limits.ts`) increases. That is the mechanism working correctly,
and it is also the most disruptive thing this project can do to its users
without shipping a bug. So the bump is a decision, never a side effect:
## What we collect
Nothing. The Extension has no servers, performs no network requests, and
contains no analytics, telemetry, or crash reporting.
| Change | Bump? |
|---|---|
| A new obligation, permission, or data flow — anything a user could reasonably object to | **Yes.** Bump, and say so in the CHANGELOG, so the reappearing gate is explicable rather than alarming. |
| Wording that narrows or clarifies something already true | No. Record the reasoning in the `15` decision log so the judgement stays auditable. |
| Typos, formatting, dead links | No. |
## What the Extension accesses, and why
- Bookmarks (permission: "bookmarks"): read to display/export your bookmark
tree; written when you import or edit. This data never leaves your device.
- Local settings (permission: "storage"): your language, theme, preferences,
and the date you accepted these terms are stored locally via
chrome.storage.local. They are not transmitted anywhere and are removed by
Chrome when you uninstall the Extension.
Procedure for a bump: edit `legal/*.md` → bump `LEGAL_VERSION` → update the CWS
Privacy tab if the privacy text changed at all (`08 §5`, `09 §4`; a privacy-tab
change is a **minor**-version event per `12 §4`) → add a `15` decision-log row →
confirm with the `11 §5` upgrade item that the gate does reappear and that
settings and bookmarks survive it.
## Files you import or export
Files are read and generated locally in your browser. They are never
uploaded. Exported files are saved through your browser's normal download
mechanism to a location you control.
**Precedent (2026-08-03):** `legal/PRIVACY.md` gained an "If you contact us"
paragraph — do not send your real bookmarks file, sanitize it first, GitHub
attachments are public, emailed material is deleted once the issue is fixed.
Deliberately **not** a bump: it describes what happens to data a user chooses to
send us, which was never inside "what the Extension collects", and re-gating
every installed user over a clarification is the worse of the two outcomes.
## Third parties
No data is shared with anyone, because no data is collected.
## Changes
Material changes will be published here and re-acceptance will be requested
inside the Extension.
## Contact
⚠️ contact email / GitHub issues link
```
### 3.2 `legal/DISCLAIMER.md` (draft)
```markdown
# Disclaimer — BookmarkMagic
- Provided "AS IS", without warranty of any kind (see LICENSE §15–16).
- Bookmark operations modify your browser's bookmark data. The "Replace
everything" mode DELETES all existing bookmarks after downloading an
automatic safety backup. You are responsible for keeping backups of data
you care about.
- Import files come from outside this Extension; verify you trust their
source. Bookmarked URLs are stored as-is and are not vetted by the
Extension.
- This project is not affiliated with or endorsed by Google, Chrome, or any
browser vendor. Browser names are trademarks of their respective owners.
```
### 3.3 `legal/EULA.md` (draft)
```markdown
# End User License Agreement — BookmarkMagic
1. License. The software is free software licensed under the GNU General
Public License v3.0 (see LICENSE). You may use, study, share, and modify
it under those terms. This EULA adds no restrictions beyond the GPL; if
anything here conflicts with the GPL, the GPL prevails.
2. No warranty; limitation of liability. As stated in GPL-3.0 §15 and §16,
the software is provided without warranty, and authors are not liable for
damages, including loss of bookmark data.
3. Acceptable use. You agree not to use the software to violate applicable
law or third-party rights.
4. Your data. The software processes bookmark data locally on your device
only (see PRIVACY.md).
5. Updates. Updates are delivered via the Chrome Web Store and may change
functionality. Material legal changes trigger re-acceptance in-app.
```
### 3.4 `LICENSE`
### 3.2 `LICENSE`
Full GPL-3.0 text at **repo root** (already committed). Variant resolved:
**`GPL-3.0-or-later`**, matching `poli0981/switch-every-tab-hotkey`. Set the
+148 -13
View File
@@ -1,10 +1,11 @@
# 15 — Roadmap
## v1.0 — MVP (store launch) — target: ~1–2 week build
## v1.0 — MVP (store launch) — ✔ SHIPPED
Everything in `00_PROJECT_OVERVIEW.md §6`. Definition of done =
Everything in `00_PROJECT_OVERVIEW.md §6`. Definition of done was
`CLAUDE.md` Phase 5 exit criteria + manual QA checklist green + store
approval.
approval — **all three met; published by 2026-08-03.** This section is now a
record rather than a plan.
Build-phase breakdown lives in `CLAUDE.md` (single source for sequencing).
@@ -16,24 +17,104 @@ 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 | ✔ 2026-07-26 | contrast tokens + a test that enforces them, `EditTab` split under the hard limit, CHANGELOG + README, four CI callers, T1–T8 pass, clean-room `wxt zip` |
| **v1.0.0 released** | ✔ 2026-07-26 | signed tag, GitHub Release with a `sha256sum -c`-verified zip, submitted to the Chrome Web Store |
| **v1.0.0 published** | ✔ by 2026-08-03 | approved by CWS review with no rejection recorded; listing public, item id `eghnciphhegekmnofffpgbdfefckdhmg`, **real users installed** |
| 6 — Post-launch stabilization | ✔ 2026-08-03 | doc reconciliation, user-intake machinery, the defects below, dependency bumps → v1.0.1 |
| **v1.0.1 released** | ✔ 2026-08-03 | signed tag on `4654086`, GitHub Release with a `sha256sum -c`-verified zip; shipped manifest `1.0.1`, permissions unchanged. `announce` skipped (no `DISCORD_ANNOUNCE`), store publish skipped (no `CWS_AUTOPUBLISH`) |
| **v1.0.1 submitted** | ✔ 2026-08-03 | uploaded to the CWS dashboard by hand (`13 §1b` step 6) |
| **v1.0.1 published** | ✔ observed 2026-10-28 | listing shows version 1.0.1 (`Updated: August 3, 2026`), 5 users. ⚠️ Exact approval date not recorded; `13 §1b` step 10 (clean-profile install of the published build + upgrade re-check) has no recorded result |
**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
that delete bookmarks. Budget that review into the remaining phases; a green
test run has not once meant "done" on this project.
**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.
## v1.0.x — stabilization
Every phase was adversarially reviewed after implementation and **every review
found real defects** — 7, 13 and 14 in phases 1–3, 19-of-33-filed in phase 4,
8-of-20 in phase 5 — several in the paths that delete bookmarks. Budget that
review into any future work; a green test run has not once meant "done" on this
project.
- Parser-tolerance fixes from real user files (fixture + test per report).
- Translation polish (JA review pass).
- Listing copy tweaks from early reviews.
Phase 5's own lesson is worth keeping: its three worst findings were defects in
work added **earlier in the same branch** — a release workflow that would have
failed on the first tag, a contrast test blind to its own bypass (`opacity` on
text, which a token-level check cannot see), and a README claiming a test
asserted the *built* manifest when it only read the config source. Review new
work as hard as old work.
And three defects reached `main` that no automated gate could ever have caught,
all found by a human looking at the running extension or at a real CI run: the
footer's missing space, a moon glyph that renders as a capital "C", and a
reusable-workflow permission grant that produced a `startup_failure` with no
jobs and no log.
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 (**the live workstream since 2026-08-03**)
This was speculative when written. It is now the actual next work, because real
users and a public listing exist.
### Intake — how a report becomes a fix
There is exactly one path, and every step has an owner in the repo:
1. A user files `.github/ISSUE_TEMPLATE/parser_report.yml`, which **requires** a
sanitized sample (`scripts/sanitize-bookmarks.mjs`) and an explicit consent
checkbox that the sample may be committed as a GPL-3.0 test fixture.
2. The sample lands in `tests/fixtures/`. Note `.gitattributes` sets
`tests/fixtures/** -text`, so EOL normalization cannot destroy the CRLF/BOM
bytes the bug may depend on.
3. A regression test lands in `tests/unit/core/fixtures.test.ts` — the only
parser regression suite — **in the same PR** as the parser fix (`11 §2`). The
sanitizer suite (`tests/unit/scripts/sanitize-bookmarks.test.ts`) also walks
every fixture automatically, so the new file is covered there too.
4. The quirk is noted in the parser source and in `04 §1.2` (`CLAUDE.md`
working style makes this mandatory, not optional).
5. `11 §2`'s inventory and `CHANGELOG.md [Unreleased]` are updated.
Translation fixes use `.github/ISSUE_TEMPLATE/translation.yml` and follow
`07 §4`; the JA native review pass (`ja.ts`'s `TODO(review-ja)`) is the
outstanding one, and it is user-facing now.
### Release trigger
Cut a patch when **any** of these is true, rather than on a schedule:
- a parser-tolerance fix exists (a user is currently unable to import a file);
- a data-integrity or dead-end defect is fixed;
- a batch of translation fixes has accumulated;
- a dependency fix is needed for a real advisory.
Listing copy tweaks alone do **not** need a patch — the store listing is edited
independently of the package (`13 §5`), though the copy should still go through
`store/listing.{en,vi,ja}.md` first so it is reviewable.
## v1.1 — quality of life
@@ -93,3 +174,57 @@ 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~~ — **resolved in Phase 5**: `links.ts` targets `CHANGELOG.md` and `tests/unit/links.test.ts` asserts both the URL shape and that the file exists | 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~~ — **superseded 2026-08-03**, see the Phase 6 rows below | 03 §4 |
| 2026-07-26 | Transitive dev-dep CVEs fixed with a `package.json` `overrides` block rather than by waiting on parents — every parent pinned a vulnerable range, which is why Dependabot's own PRs all failed | 09 §3.1 |
| 2026-07-26 | The release announcement is `continue-on-error`. A missing Discord webhook made the real v1.0.0 run red on a release whose zip and checksums had published correctly; a red run on a good release trains you to ignore the colour | 12 §2.3 |
| 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 |
| 2026-08-03 | **Every destructive step reports what already landed.** `writeTree` and `clearRoots` wrap their failing `chrome.*` call in `BmPartialWrite{phase, done}`, matching the contract `BmAborted` already had. A failure that says only "the browser refused" tells a user whose tree was half-replaced nothing they can act on | 02 §7, 03 §1 |
| 2026-08-03 | **`BmAborted` is re-thrown before the partial-write wrap.** Wrapping it would relabel every user cancellation as a failure and make `import.cancelledSummary` dead code — the same defect class as `detail ?? t(key)` | 03 §1 |
| 2026-08-03 | **The import report states that imported bookmarks carry today's date.** `05 §6` and `00 §8` both required this and no string ever said it. Shown in the `parsed` state too — telling someone before they commit beats telling them after | 03 §1, 05 §6 |
| 2026-08-03 | **Routing is guarded while a write or attestation is in flight**, via an injected predicate rather than a store import, so `route` stays uncoupled. Browser Back during `attesting` previously deadlocked the Manager permanently: the same hole Phase 4 closed for the footer and TabBar, left open on `hashchange` | 02 §5 |
| 2026-08-03 | **The attestation resolver lives in the import store, not in `ImportTab`.** A component-local resolver dies with the component; a remounted tab then renders inert buttons. A stale or reset resolver settles **`false`** — an unanswered backup attestation must never read as consent | 03 §1 6b |
| 2026-08-03 | **Two Manager tabs now converge.** Settings adopt external changes under two rules: ignore anything arriving while this context has an unflushed write (last-write-wins, as before), else adopt only when a field actually differs. Field equality makes self-echo suppression fall out for free — no snapshot to go stale | 03 §4 |
| 2026-08-03 | **Legal acceptance is adopted in one direction only — toward accepted.** The gate replaces the tab body, so an externally-raised gate would unmount `ImportTab` mid-write and recreate the attestation deadlock through a third door. One-way makes that unreachable by construction | 03 §4, 14 §2 |
| 2026-08-03 | **One `ErrorCallout` owns the localized-sentence-plus-detail-block contract.** Three sites still rendered a raw English Chrome string as the whole message after `LegalGate` had already been fixed for exactly that | 02 §7 |
| 2026-08-03 | **`NO_WRITABLE_ROOTS` is its own error, not `BROWSER`.** A profile with no writable root is an absence, not a refusal; reporting "the browser refused" sends the user looking for the wrong thing | 02 §7 |
| 2026-08-03 | **Search-driven expansion is undone when the search clears**, tracked separately from folders the user opened by hand. Merging into `expanded` was deliberate (a render-time union broke the disclosure button) — the missing half was the un-merge | 03 §3, 06 §3.3 |
| 2026-08-03 | **The "if you contact us" paragraph in `legal/PRIVACY.md` is a clarification, not a material change** — it describes what happens to data a user chooses to send, which was never inside "what the extension collects". `LEGAL_VERSION` deliberately **not** bumped: re-showing the gate to every installed user over a patch is a worse outcome than the ambiguity it fixes | 14 §2, 14 §3 |
| 2026-08-03 | **A WXT bump is accepted only after diffing the BUILT manifest**, not on a green test run. `tests/unit/manifest.test.ts` reads `wxt.config.ts`, which a WXT upgrade cannot change, so it stays green no matter what WXT emits. 0.21.3 was verified byte-identical in manifest, file inventory and bundle size; it did break `wxt/testing` into two subpaths and retype `tabs.create` as `void`, both dev-only. `check-manifest.mjs` now asserts the exact top-level key set so the next one is caught by CI rather than by hand | 01 §2, 12 §2.3 |
| 2026-08-03 | **jsdom 30 accepted after running `dom-environment.test.ts` first.** The canary exists because the Netscape walk depends on parse5's implied-end-tag behaviour; the rule is that a failing canary pins the dependency, never loosens the test. The 2 869 ms figure in `11 §6` is a jsdom **29** number and a major bump adds a column rather than overwriting it | 01 §2, 11 §6 |
| 2026-08-03 | **`continue-on-error` is invalid on a job that calls a reusable workflow** — GitHub rejects the file with "Property continue-on-error is not allowed", and a rejected file is a `startup_failure` with zero jobs and no log, not a failed job. `release.yml`'s announce job had carried it since `5f4c6e7`; that commit landed *after* the `v1.0.0` tag and no tag was pushed since, so **the first v1.0.1 tag would have been its first execution**. Both notification jobs are now gated with `if:` on a repo variable — allowed there, unlike a secret — defaulting to skipped | 12 §2.3, 12 §2.4 |
| 2026-08-03 | **A notification must never change the colour of the thing it reports on.** `notify-ci-failure.yml` had been failing on *every* CI completion, success included, because the reusable declares a secret that does not exist and GitHub validates that before the reusable's own success filter runs. Same lesson as `5f4c6e7`, learned twice | 12 §2.4 |
| 2026-08-03 | **No support email on any in-product surface.** About links to the store listing, the repo, issues and the changelog. Publishing an address inside the extension invites unsanitized bookmark files by mail, which is the exact receipt-of-personal-data problem the privacy clause exists to bound. The address stays in `SECURITY.md`, `CONTRIBUTING.md` and the privacy policy | 06 §3.5, 09 §6 |
| 2026-10-28 | **Node 26 LTS for the whole toolchain.** Node 26 entered Active LTS that day and Node 24 had gone to maintenance on 2026-10-20 — the "latest stable or LTS" rule of `01` moves with it | 01 §2 |
| 2026-10-28 | **TypeScript 7 runs beside the TS 6 API instead of replacing it.** `@typescript/native` (`npm:typescript@~7.0.2`) owns `tsc`; `typescript` is aliased to `@typescript/typescript6`, which re-exports TS 6.0.3 for svelte-check and Volar. TS 7 has no programmatic API until 7.1, and svelte-check peers `^5 \|\| ^6`, so this is the only way to adopt 7 without losing template type-checking | 01 §2 |
| 2026-10-28 | **ES2025, and the Chrome floor that makes it honest: 120 → 136.** A lib newer than the floor lets the compiler accept APIs the oldest allowed Chrome lacks (`RegExp.escape` is 136). `CHROME_FLOOR` in `wxt.config.ts` drives both `minimum_chrome_version` and Vite's `build.target`; `manifest.test.ts` pins those and tsconfig's `lib` together. A floor raise strands nobody — users below it keep their version and stop updating — but it is user-visible, so never in a patch | 01 §1, 08 §7 |
| 2026-10-28 | **7-day supply-chain cooldown:** `.npmrc` `min-release-age=7` + Dependabot `cooldown: 7`. Verified that `npm ci` still installs whatever the lockfile pins, so the rule only shapes *what gets locked* | 01 §6, 09 §3.1 |
| 2026-10-28 | **The `overrides` block is deleted.** All six pinned packages had left the tree (WXT 0.21 dropped `web-ext-run`; Vite 8 uses rolldown, not esbuild). `npm audit` 13 → 3 low, all one unfixable `deepmerge` advisory inside vite-plugin-svelte, accepted and documented; `--omit=dev` stays 0 | 09 §3.1 |
| 2026-10-28 | **WXT 0.21.3 → 0.21.4 accepted after the built-manifest diff** the 2026-08-03 rule requires: identical key set and values (only the deliberate `minimum_chrome_version`), identical file inventory, chunk sizes within ±1.1 kB from the Svelte 5.57 runtime. Vitest 4 → 5 and jsdom 30.0 → 30.1 passed the whole suite unchanged, the `dom-environment` canary first | 01 §2 |
| 2026-10-28 | **Biome ignores Markdown and YAML.** 2.6 began formatting both and flagged 35 hand-laid docs and workflows; formatting prose is not what the gate is for | 10 §3 |
| 2026-10-28 | **SonarCloud moves from Automatic Analysis to a CI scan** (`sonarcloud.yml`, `sonar-project.properties`): coverage at last, and a scan of what CI actually builds. Its own workflow so it never colours CI; the scan action pinned to a commit because it holds `SONAR_TOKEN`; skipped, not failed, where secrets are absent | 12 §2.5 |
| 2026-10-28 | **Coverage measures all of `src/**/*.ts`, but the gate stays core-only** via a glob threshold — verified to still fail a run below `src/lib/core/**`'s numbers, so widening what is measured cannot loosen what is enforced | 11 §1, 12 §2.5 |
| 2026-10-28 | **CI installs with `--ignore-scripts` and runs `wxt prepare` explicitly; reusables get named secrets; checkouts drop credentials; the release's write token moves to a job that installs nothing.** The old release job ran every dependency's install script and our tests while holding `contents: write`. The announce job's `secrets: inherit` also passed nothing it could use — this repo's webhook secrets have different names than the reusable reads | 12 §2 |
| 2026-10-28 | **docs/12 stops copying workflow YAML.** The copies drifted three times; with docs-win, a stale copy invites reverting a pinned action or deleting a gate. The chapter now records why each job exists and the traps already hit; the files are the ground truth about themselves | 12 §2 |
| 2026-10-28 | **The zero-network promise becomes browser-enforced.** The production manifest gains an extension-page CSP that keeps the MV3 minimum and adds `connect-src 'none'` plus closed image/font/media/frame/form sources — no `default-src`, so styles are untouched; dev builds omit it so HMR works. Reverses `08 §3`'s old "never add a custom CSP", whose reason was that MV3 forbids *loosening*; tightening was always allowed. The rule now: only ever tighten, and `check:manifest` pins the exact string | 08 §3 |
| 2026-10-28 | **Three gates instead of one grep:** the CSP (runtime), `check:manifest` scanning the shipped JS for network APIs (catches dependency code), and a rewritten `guard.mjs` — whole-file matching, identifiers banned outright, computed global access banned, `.html/.css` scanned, no test exemption, fails on zero files. The old one let all 28 audited bypasses through and printed "clean" for a checkout path with a space or diacritic. Vite's modulepreload polyfill (the one network call in the bundle) is off | 08 §3 |
| 2026-10-28 | **The guard's rule list lives in `scripts/guard.mjs` only.** `08 §3` restating it was the "single source" that had already diverged (`\{@html\}` matched only the literal text) | 08 §3 |
| 2026-10-28 | **The sanitizer reads the browser JSON formats and is default-deny for JSON.** It accepted any JSON and rewrote only `url`/`title`, so Chrome's profile `Bookmarks` file — titles under `name`, plus `meta_info` and a base64 sync blob — came out with every title intact and passed its own host check. JSON dialects are now recognised by shape (anything else refused), every string value is rewritten except structural keys, Firefox root GUIDs and the timestamps survive | 09 §6 |
| 2026-10-28 | **The sanitizer's backstop reads the output's text, not just its hosts.** For HTML it strips markup and refuses on any word that is not a placeholder — independent of the rewriting rules, unlike the old check (and its test), which shared their blind spots. It also stopped overwriting the input when the output path equalled it, checks size before reading, decodes attributes once (CodeQL double-escaping) and finds `<DD>` notes in linear time (Sonar S8786), attributes included | 09 §6 |
| 2026-10-28 | **`scripts/` obeys the size rule and is type-checked.** `docs/10 §1` now names `.mjs`; the 627-line sanitizer is split into `scripts/sanitize/` modules; every script carries `// @ts-check` and `tsconfig.scripts.json` runs them through the TS 7 `tsc` in `npm run check`. The sanitizer stays plain `.mjs` on purpose — reporters run it on whatever Node they have | 10 §1 |
+25 -2
View File
@@ -1,6 +1,6 @@
# Privacy Policy — BookmarkMagic
Last updated: 2026-07-25
Last updated: 2026-08-03
BookmarkMagic ("the Extension") is designed to work entirely on your device.
@@ -34,12 +34,35 @@ location you control.
No data is shared with anyone, because no data is collected. The Extension
ships with zero runtime dependencies.
## If you contact us
Everything above describes the Extension, which sends us nothing. This section
describes what happens if *you* choose to send us something — reporting a bug,
for example.
- **Please do not send us your real bookmarks file.** A bookmarks export is a
browsing history. Run `scripts/sanitize-bookmarks.mjs` from the repository
first: it replaces every address and title while keeping the file structure
that a bug depends on, so the sanitized version still reproduces the problem.
- **Anything you attach to a GitHub issue is public** and stays in the issue
history. Attach only a sanitized sample. If you agree, a sample may be
committed to the repository as a permanent test fixture under GPL-3.0 — the
bug report form asks you explicitly, and never assumes it.
- **Anything you email us is kept only as long as it takes to reproduce and fix
the issue, and is then deleted.** It is not shared with anyone, and it is
never added to the repository unless you agreed to that.
## Changes
Material changes will be published here and re-acceptance will be requested
inside the Extension.
*The section above was added on 2026-08-03. It is a clarification, not a change
of practice: it describes handling of material you choose to send us, which was
never part of what the Extension itself collects — which remains nothing. No
re-acceptance was requested.*
## Contact
⚠️ contact email — or open an issue at
Email: contact@poli0981.dev — or open an issue at
<https://github.com/poli0981/bookmarkmagic/issues>
+1274 -4312
View File
File diff suppressed because it is too large. Load diff
+18 -14
View File
@@ -1,7 +1,7 @@
{
"name": "bookmarkmagic",
"private": true,
"version": "0.1.0",
"version": "1.0.1",
"type": "module",
"description": "Import, export & edit bookmarks between browsers — offline, no account, no cloud.",
"license": "GPL-3.0-or-later",
@@ -15,7 +15,7 @@
"url": "https://github.com/poli0981/bookmarkmagic/issues"
},
"engines": {
"node": ">=24"
"node": ">=26"
},
"scripts": {
"postinstall": "wxt prepare",
@@ -23,28 +23,32 @@
"dev:firefox": "wxt -b firefox",
"build": "wxt build",
"zip": "wxt zip",
"check": "svelte-check --tsconfig ./tsconfig.json && tsc --noEmit",
"check": "svelte-check --tsconfig ./tsconfig.json && tsc --noEmit && tsc -p tsconfig.scripts.json",
"lint": "biome check .",
"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",
"coverage": "vitest run --coverage",
"verify": "npm run lint && npm run check && npm run knip && npm run guard && npm run test"
"verify": "npm run lint && npm run check && npm run knip && npm run guard && npm run test",
"verify:full": "npm run verify && npm run coverage && npm run build && npm run check:manifest"
},
"devDependencies": {
"@biomejs/biome": "2.5.5",
"@sveltejs/vite-plugin-svelte": "^7.2.0",
"@vitest/coverage-v8": "^4.1.10",
"@biomejs/biome": "2.6.2",
"@sveltejs/vite-plugin-svelte": "^7.3.1",
"@types/node": "^26.6.5",
"@typescript/native": "npm:typescript@~7.0.2",
"@vitest/coverage-v8": "^5.0.5",
"@wxt-dev/module-svelte": "^2.0.5",
"jsdom": "^29.1.1",
"knip": "^6.29.0",
"svelte": "^5.56.8",
"svelte-check": "^4.7.3",
"typescript": "~6.0.3",
"vitest": "^4.1.10",
"wxt": "^0.20.27"
"jsdom": "^30.1.3",
"knip": "^6.42.1",
"svelte": "^5.57.2",
"svelte-check": "^4.7.7",
"typescript": "npm:@typescript/typescript6@~6.0.2",
"vitest": "^5.0.5",
"wxt": "^0.21.4"
}
}
+5
View File
@@ -0,0 +1,5 @@
/**
* Types for scripts/check-manifest.mjs, so its tests can call it directly.
* The script itself is plain JavaScript checked with `// @ts-check`.
*/
export function checkExtension(outDir: string): { problems: string[]; readError?: string };
+246
View File
@@ -0,0 +1,246 @@
// @ts-check
/**
* Assert the BUILT extension — CLAUDE.md hard rule 1, docs/08 §2–§3.
*
* `tests/unit/manifest.test.ts` reads `wxt.config.ts`, which proves what we
* ASKED for. It cannot prove what WXT emitted, and 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. So the shipped artifact gets its
* own gate, run after `npm run build` (or `npm run zip`):
*
* 1. the manifest: MV3, the exact permission list, the exact top-level key
* set, the Chrome floor, and the exact extension-page CSP;
* 2. the file inventory: every file the manifest or the pages point at exists
* (WXT drops `_locales/` and `icon/` silently when publicDir is wrong);
* 3. the bundle: no network API anywhere in the shipped JavaScript.
*
* Usage: node scripts/check-manifest.mjs — checks <repo>/.output/chrome-mv3,
* resolved from this file, not the cwd. It takes no arguments on purpose: a
* path from the command line flowed straight into file reads (SonarCloud
* S8707). Its tests call `checkExtension(dir)` directly instead.
*/
import { existsSync, readdirSync, readFileSync } from 'node:fs';
import { join, relative, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
/** Exactly this, in any order. Adding one is a minor-version event (docs/09 §4). */
const ALLOWED_PERMISSIONS = ['bookmarks', 'storage'];
/** The ES2025 floor (docs/01 §1). Must equal CHROME_FLOOR in wxt.config.ts. */
const CHROME_FLOOR = '136';
/**
* The production extension-page CSP (docs/08 §3), character for character.
* It may only ever get stricter. Never add 'unsafe-eval' or a remote source.
*/
const EXPECTED_CSP =
"script-src 'self'; object-src 'none'; connect-src 'none'; img-src 'self' data: blob:; " +
"style-src 'self' 'unsafe-inline'; font-src 'self'; media-src 'none'; frame-src 'none'; " +
"worker-src 'self'; form-action 'none'; base-uri 'none'";
/**
* The exact top-level key set the build is expected to emit.
*
* The forbidden list below can only catch reach-widening keys someone thought
* to enumerate. This catches the other direction — a build tool that starts
* emitting a key nobody asked for, or stops emitting one the store requires.
* WXT is a 0.x dependency, so a routine minor bump is exactly when that
* happens. `version_name` would appear if package.json ever carried a
* prerelease version (WXT splits it out); release versions never do.
*
* Adding a key here is a deliberate act. Check docs/08 §1 first.
*/
const EXPECTED_KEYS = [
'action',
'content_security_policy',
'default_locale',
'description',
'homepage_url',
'icons',
'manifest_version',
'minimum_chrome_version',
'name',
'options_ui',
'permissions',
'version',
];
/** 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',
];
/** Files every build must contain besides what the manifest references. */
const REQUIRED_FILES = [
'manager.html',
'popup.html',
'_locales/en/messages.json',
'_locales/vi/messages.json',
'_locales/ja/messages.json',
];
/**
* Network APIs that must not appear in the shipped JavaScript — including code
* that arrived through a dependency, which `npm run guard` (source only) never
* sees. The CSP would refuse these at runtime; this refuses to ship them.
*/
const NETWORK_IN_BUNDLE =
/\bfetch\s*\(|\bXMLHttpRequest\b|\bWebSocket\b|\bEventSource\b|\bsendBeacon\b|\bWebTransport\b/;
/** @param {string} a @param {string} b */
const byName = (a, b) => a.localeCompare(b, 'en');
/** @param {string} dir @returns {string[]} */
function listFiles(dir) {
return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
const full = join(dir, entry.name);
return entry.isDirectory() ? listFiles(full) : [full];
});
}
/**
* @param {string} outDir
* @returns {Record<string, unknown> | string} the manifest, or why it could not be read
*/
function readManifest(outDir) {
try {
return JSON.parse(readFileSync(join(outDir, 'manifest.json'), 'utf8'));
} catch (cause) {
return `cannot read manifest.json (${cause instanceof Error ? cause.message : cause})`;
}
}
/** @param {Record<string, unknown>} manifest @param {string[]} problems */
function checkManifest(manifest, problems) {
if (manifest.manifest_version !== 3) {
problems.push(`manifest_version is ${manifest.manifest_version}, expected 3`);
}
const permissions = Array.isArray(manifest.permissions) ? manifest.permissions : [];
const actualPermissions = [...permissions].sort(byName).join(',');
if (actualPermissions !== [...ALLOWED_PERMISSIONS].sort(byName).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])}`);
}
const actualKeys = Object.keys(manifest);
const unexpected = actualKeys.filter((key) => !EXPECTED_KEYS.includes(key)).sort(byName);
const missing = EXPECTED_KEYS.filter((key) => !actualKeys.includes(key));
if (unexpected.length > 0) {
problems.push(`unexpected top-level key(s): ${unexpected.join(', ')} — see docs/08 §1`);
}
if (missing.length > 0) problems.push(`missing expected top-level key(s): ${missing.join(', ')}`);
if (manifest.minimum_chrome_version !== CHROME_FLOOR) {
problems.push(
`minimum_chrome_version is ${JSON.stringify(manifest.minimum_chrome_version)}, expected "${CHROME_FLOOR}" (docs/01 §1)`,
);
}
const csp = /** @type {{ extension_pages?: unknown } | undefined} */ (
manifest.content_security_policy
);
if (csp?.extension_pages !== EXPECTED_CSP || Object.keys(csp).length !== 1) {
problems.push(
`content_security_policy is ${JSON.stringify(csp)}, expected exactly { extension_pages: "${EXPECTED_CSP}" } (docs/08 §3)`,
);
}
}
/** @param {Record<string, unknown>} manifest @returns {string[]} */
function referencedFiles(manifest) {
const icons = /** @type {Record<string, string>} */ (manifest.icons ?? {});
const action = /** @type {{ default_popup?: string }} */ (manifest.action ?? {});
const options = /** @type {{ page?: string }} */ (manifest.options_ui ?? {});
return [...Object.values(icons), action.default_popup, options.page?.split('#')[0]].filter(
(p) => typeof p === 'string',
);
}
/** @param {string} outDir @param {Record<string, unknown>} manifest @param {string[]} problems */
function checkInventory(outDir, manifest, problems) {
for (const file of [...REQUIRED_FILES, ...referencedFiles(manifest)]) {
const path = join(outDir, file.replace(/^\//, ''));
if (!existsSync(path)) problems.push(`missing file in the build: ${file}`);
}
}
/** @param {string} outDir @param {string[]} problems */
function checkBundle(outDir, problems) {
for (const file of listFiles(outDir).filter((f) => f.endsWith('.js'))) {
const match = readFileSync(file, 'utf8').match(NETWORK_IN_BUNDLE);
if (match) {
const rel = relative(outDir, file).replace(/\\/g, '/');
problems.push(`network API "${match[0]}" in the shipped bundle: ${rel} (docs/08 §3)`);
}
}
}
/**
* Check one built extension directory.
*
* @param {string} outDir
* @returns {{ problems: string[], readError?: string }} no problems and no read
* error means the build is clean
*/
export function checkExtension(outDir) {
const manifest = readManifest(outDir);
if (typeof manifest === 'string') return { problems: [], readError: manifest };
/** @type {string[]} */
const problems = [];
checkManifest(manifest, problems);
checkInventory(outDir, manifest, problems);
checkBundle(outDir, problems);
return { problems };
}
/** @returns {number} the exit code */
function main() {
const repo = resolve(fileURLToPath(new URL('..', import.meta.url)));
const { problems, readError } = checkExtension(join(repo, '.output', 'chrome-mv3'));
if (readError !== undefined) {
console.error(`check-manifest: ${readError} — run \`npm run build\` first.`);
return 1;
}
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.');
return 1;
}
// Constants only: the manifest has just passed every check, so its values ARE
// these — and nothing read from a file is echoed into the log.
console.warn(
`check-manifest: clean — MV3, permissions exactly ${ALLOWED_PERMISSIONS.join(' + ')}, Chrome ≥${CHROME_FLOOR}, CSP pinned, inventory complete, no network API in the bundle.`,
);
return 0;
}
// Run only as the entry point. Under a test runner `import.meta.url` may not
// even be a file: URL, so it is not resolved until it is known to be one.
const isEntry =
import.meta.url.startsWith('file:') &&
process.argv[1] !== undefined &&
resolve(process.argv[1]) === fileURLToPath(import.meta.url);
if (isEntry) {
// exitCode, not exit(): exit() can cut off piped stderr before CI reads it.
process.exitCode = main();
}
+165
View File
@@ -0,0 +1,165 @@
#!/usr/bin/env node
// @ts-check
/**
* Generate a large Netscape bookmark file on demand.
*
* Purpose: make the two measurements docs/11 asks for actually runnable — the
* 10 000-node responsiveness item in §5, and the 100 000-node parse budget in
* §6 that has only ever been measured under jsdom.
* Inputs: a node count and an output path.
* Guarantees: exactly `--nodes` nodes (folders + bookmarks), valid Netscape
* HTML, deterministic for a given seed — so two runs are comparable.
*
* docs/11 §2 named a `generate-huge.ts` for this and `.gitignore` has always
* reserved `tests/fixtures/generated/` for its output, but the script itself was
* never written, which is why the 2 s budget stayed unmeasured (docs/00 §10.8).
*
* Usage:
* node scripts/gen-fixture.mjs --nodes 10000 --out tests/fixtures/generated/big.html
* node scripts/gen-fixture.mjs --nodes 100000 --per-folder 100 --seed 7 --out …
*/
import { mkdirSync, writeFileSync } from 'node:fs';
import { dirname } from 'node:path';
/**
* Mulberry32 — small, seeded, and good enough for shaping test data.
* @param {number} seed
*/
function rng(seed) {
let a = seed >>> 0;
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const USAGE =
'usage: node scripts/gen-fixture.mjs --nodes <n> --out <path> [--per-folder <n>] [--seed <n>]';
/**
* Strict flags: whole numbers >= 1, every flag needs a value, no unknown flags.
* The old reader took arguments in blind pairs, so `--nodes 1.5` wrote 2 nodes,
* `--per-folder abc` silently wrote no bookmarks, and one missing value shifted
* every flag after it.
*
* @param {string[]} argv
* @returns {{ nodes: number, perFolder: number, seed: number, out: string } | string}
* the options, or an error message
*/
function parseArgs(argv) {
const out = { nodes: 10_000, perFolder: 50, seed: 1, out: '' };
/** @type {Record<string, 'nodes' | 'perFolder' | 'seed'>} */
const numeric = { '--nodes': 'nodes', '--per-folder': 'perFolder', '--seed': 'seed' };
for (let i = 0; i < argv.length; i += 2) {
const flag = argv[i] ?? '';
const value = argv[i + 1];
if (value === undefined || value.startsWith('--')) return `${flag} needs a value`;
if (flag === '--out') {
out.out = value;
continue;
}
const key = numeric[flag];
if (key === undefined) return `unknown flag ${flag}`;
const n = Number(value);
if (!Number.isInteger(n) || n < 1) return `${flag} must be a whole number >= 1, got "${value}"`;
out[key] = n;
}
return out.out === '' ? '--out is required' : out;
}
/**
* Titles that exercise the escaping path, not just ASCII.
*
* A 100k file of `Bookmark 1..n` would measure string concatenation and nothing
* else; entities, CJK and emoji are what the parser actually spends time on.
*/
const TITLE_POOL = [
'Example bookmark',
'Quotes &quot;here&quot;',
'Ampersand &amp; more',
'Angle &lt;brackets&gt;',
'ブックマーク',
'Thư mục quan trọng',
'🌸 emoji title',
'A rather long bookmark title that wraps in most reasonable window widths',
];
/**
* @param {{ nodes: number, perFolder: number, seed: number }} options
* @returns {string}
*/
function build({ nodes, perFolder, seed }) {
const rand = rng(seed);
const lines = [
'<!DOCTYPE NETSCAPE-Bookmark-file-1>',
'<!-- Generated by scripts/gen-fixture.mjs — not a real export. -->',
'<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">',
'<TITLE>Bookmarks</TITLE>',
'<H1>Bookmarks</H1>',
'<DL><p>',
];
let folderIndex = 0;
/** @param {number} depth */
const indent = (depth) => ' '.repeat(depth);
/**
* Write one folder (and, below depth 3, one nested folder chain) using at
* most `budget` nodes. Returns how many it wrote — always at least 1, so the
* caller's loop provably makes progress.
*
* @param {number} depth
* @param {number} written nodes written before this call
* @param {number} budget nodes this call may write
* @returns {number}
*/
const emitFolder = (depth, written, budget) => {
folderIndex++;
const stamp = 1700000000 + folderIndex;
lines.push(
`${indent(depth)}<DT><H3 ADD_DATE="${stamp}" LAST_MODIFIED="${stamp + 1}"${
folderIndex === 1 ? ' PERSONAL_TOOLBAR_FOLDER="true"' : ''
}>Folder ${folderIndex}</H3>`,
`${indent(depth)}<DL><p>`,
);
let used = 1;
const count = Math.min(perFolder, budget - used);
for (let i = 0; i < count; i++) {
const n = written + used;
const title = TITLE_POOL[Math.floor(rand() * TITLE_POOL.length)];
lines.push(
`${indent(depth + 1)}<DT><A HREF="https://host${n % 997}.example/p${n}?q=${n}" ` +
`ADD_DATE="${1700000000 + n}">${title}</A>`,
);
used++;
}
// Depth 3 so the walk is exercised, but nowhere near the 200 cap — this
// file is for measuring the common case, not the limit.
if (depth < 3 && used < budget) used += emitFolder(depth + 1, written + used, budget - used);
lines.push(`${indent(depth)}</DL><p>`);
return used;
};
let written = 0;
while (written < nodes) written += emitFolder(1, written, nodes - written);
lines.push('</DL><p>', '');
return lines.join('\n');
}
const options = parseArgs(process.argv.slice(2));
if (typeof options === 'string') {
console.error(`gen-fixture: ${options}
${USAGE}`);
process.exitCode = 1;
} else {
const html = build(options);
mkdirSync(dirname(options.out), { recursive: true });
writeFileSync(options.out, html);
const mb = (Buffer.byteLength(html) / 1024 / 1024).toFixed(1);
console.error(`wrote ${options.out} — ${options.nodes} nodes, ${mb} MB`);
}
+26 -9
View File
@@ -1,20 +1,26 @@
// @ts-check
/**
* Generate placeholder extension icons — a rounded violet square with a white
* bookmark ribbon — at the four sizes Chrome needs. Zero dependencies: PNG is
* written by hand (zlib deflate + a CRC32 table), so no image library enters
* the tree.
* Generate the extension icons — a rounded violet square with a white bookmark
* ribbon — at the four sizes Chrome needs. Zero dependencies: PNG is written by
* hand (zlib deflate + a CRC32 table), so no image library enters the tree.
*
* These are functional placeholders so the manifest loads from Phase 0.
* Replace with the designed icon before a store release (docs/00 §10 item 3,
* docs/13 §2). Run: `npm run icons`.
* THIS SCRIPT IS THE SOURCE OF TRUTH for the shipped icons: the owner adopted
* its output as final on 2026-07-26 (docs/00 §10 item 3). There is no other
* master file. `npm run icons` overwrites src/public/icon/*.png — review the
* diff before committing, because those PNGs are what the store listing shows.
*/
import { mkdirSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { deflateSync } from 'node:zlib';
/** @typedef {readonly [number, number, number, number]} Rgba */
/** @type {Rgba} */
const ACCENT = [0x6d, 0x4a, 0xff, 255]; // --accent, docs/06 §1
/** @type {Rgba} */
const WHITE = [255, 255, 255, 255];
/** @type {Rgba} */
const TRANSPARENT = [0, 0, 0, 0];
const CRC_TABLE = (() => {
@@ -27,12 +33,14 @@ const CRC_TABLE = (() => {
return table;
})();
/** @param {Uint8Array} buf */
function crc32(buf) {
let c = 0xffffffff;
for (const byte of buf) c = CRC_TABLE[(c ^ byte) & 0xff] ^ (c >>> 8);
for (const byte of buf) c = (CRC_TABLE[(c ^ byte) & 0xff] ?? 0) ^ (c >>> 8);
return (c ^ 0xffffffff) >>> 0;
}
/** @param {string} type @param {Buffer} data */
function chunk(type, data) {
const body = Buffer.concat([Buffer.from(type, 'ascii'), data]);
const len = Buffer.alloc(4);
@@ -42,6 +50,7 @@ function chunk(type, data) {
return Buffer.concat([len, body, crc]);
}
/** @param {number} x @param {number} y @param {number} size @param {number} radius */
function insideRounded(x, y, size, radius) {
const px = x + 0.5;
const py = y + 0.5;
@@ -50,7 +59,10 @@ function insideRounded(x, y, size, radius) {
return dx * dx + dy * dy <= radius * radius;
}
/** Bookmark ribbon: a tall rectangle with a triangular notch cut from the bottom. */
/**
* Bookmark ribbon: a tall rectangle with a triangular notch cut from the bottom.
* @param {number} x @param {number} y @param {number} size
*/
function insideBookmark(x, y, size) {
const u = (x + 0.5) / size;
const v = (y + 0.5) / size;
@@ -64,12 +76,17 @@ function insideBookmark(x, y, size) {
return true;
}
/**
* @param {number} x @param {number} y @param {number} size
* @returns {Rgba}
*/
function colorAt(x, y, size) {
if (!insideRounded(x, y, size, size * 0.2)) return TRANSPARENT;
if (insideBookmark(x, y, size)) return WHITE;
return ACCENT;
}
/** @param {number} size */
function makePng(size) {
const stride = size * 4;
const raw = Buffer.alloc((stride + 1) * size);
+199 -51
View File
@@ -1,51 +1,144 @@
// @ts-check
/**
* The canonical grep gate — docs/08_MV3_COMPLIANCE.md §3.
* The zero-network / no-raw-HTML gate — docs/08 §3.
*
* This file is the single implementation of that pattern. It runs both locally
* (`npm run verify`) and in CI (`npm run guard`), so the gate cannot drift
* between the two. Zero dependencies, Node stdlib only.
* This file IS the rule set; docs/08 §3 points here instead of restating it,
* because two copies of a security pattern drift (they did: the doc's
* `\{@html\}` matched only the literal `{@html}`, never `{@html x}`).
*
* Why a grep and not a lint rule: MV3's default CSP blocks remote code, but it
* has no connect-src at all and does not restrict network egress. And no Biome
* rule sees Svelte's {@html} — noDangerouslySetInnerHtml is a React rule. This
* script plus review is the entire enforcement of the zero-network and
* no-raw-HTML promises.
* It runs locally (`npm run verify`) and in CI (`npm run guard`), so the gate
* cannot differ between the two. Zero dependencies, Node stdlib only.
*
* It is no longer the ONLY enforcement: since v1.1.0 the production manifest
* declares a CSP with `connect-src 'none'` (docs/08 §3), so the browser itself
* refuses fetch/XHR/WebSocket/EventSource/beacons. This gate catches the rest —
* raw HTML sinks, code execution, remote resources in markup and CSS — and
* keeps network code out of review in the first place.
*
* Matching runs over the WHOLE file, not line by line, so `\s*` spans newlines
* and splitting a call across two lines no longer gets past a rule. Identifiers
* are banned outright where an alias would otherwise slip through
* (`const go = fetch; go(u)`), which means the bare words are banned in
* comments too — write "network call", not the API name, in prose.
*
* Usage: node scripts/guard.mjs [--root <dir>] (--root is for its own tests)
*/
import { readFileSync } from 'node:fs';
import { readdir } from 'node:fs/promises';
import { extname, join, relative } from 'node:path';
import { extname, join, relative, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
/**
* fileURLToPath, never `new URL(...).pathname`: the pathname stays
* percent-encoded, so a checkout under `C:\Users\Nguyễn\…` or `my dir` became a
* path that does not exist — and the walker reported "clean" after scanning
* nothing.
*/
const DEFAULT_ROOT = fileURLToPath(new URL('..', import.meta.url));
const ROOT = new URL('..', import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1');
const SCAN_DIRS = ['src'];
const SCAN_EXTS = new Set(['.ts', '.js', '.mjs', '.svelte']);
const SCAN_EXTS = new Set([
'.ts',
'.mts',
'.cts',
'.js',
'.mjs',
'.cjs',
'.svelte',
'.html',
'.css',
]);
const SKIP_DIRS = new Set(['node_modules', '.output', '.wxt', '.git']);
/** Each entry: [human-readable name, pattern]. Keep in sync with docs/08 §3. */
const BANNED = [
['network: fetch', /\bfetch\s*\(/],
['network: XMLHttpRequest', /\bXMLHttpRequest\b/],
['network: WebSocket', /\bWebSocket\b/],
['network: EventSource', /\bEventSource\b/],
['network: sendBeacon', /\bsendBeacon\b/],
['remote code: eval', /\beval\s*\(/],
['remote code: new Function', /\bnew\s+Function\s*\(/],
['remote code: dynamic import', /(^|[^.\w])import\s*\(/],
['raw HTML: {@html}', /\{@html\b/],
['raw HTML: innerHTML assignment', /\b(?:inner|outer)HTML\s*=/],
['raw HTML: insertAdjacentHTML', /\binsertAdjacentHTML\b/],
/** A URL that leaves the extension: `https://`, `http://` or protocol-relative `//`. */
const REMOTE = String.raw`(?:https?:)?\/\/`;
/**
* [category, name, pattern, refine?]. Every pattern carries the `g` flag and is
* run over the whole file; when `refine` is present, a match only counts if
* `refine` also matches the matched text. Each rule has a positive and a
* negative case in tests/unit/scripts/guard.test.ts — add both when adding one.
*
* No pattern may let two quantifiers compete for the same characters (a
* `\s*` beside an optional quote beside another `\s*`): that backtracks
* polynomially (SonarCloud S8786), and this script scans whatever lands in src/.
*/
const RULES = [
// Network. Identifiers, not call shapes: aliasing, tagged templates and
// `.call()` all start with the bare name.
['network', 'fetch', /\bfetch\b/g],
['network', 'XMLHttpRequest', /\bXMLHttpRequest\b/g],
['network', 'WebSocket', /\bWebSocket\b/g],
['network', 'WebTransport', /\bWebTransport\b/g],
['network', 'EventSource', /\bEventSource\b/g],
['network', 'sendBeacon', /\bsendBeacon\b/g],
['network', 'RTCPeerConnection', /\bRTCPeerConnection\b/g],
['network', 'importScripts', /\bimportScripts\b/g],
// `globalThis['fe' + 'tch']` — computed access on a global is how every
// identifier rule above is evaded, so it is banned as a shape.
['network', 'computed global access', /\b(?:globalThis|window|self|navigator|document)\s*\[/g],
// Resource hints fetch ahead of time. These words have no use in this
// extension, so they are banned outright; `preload` is ordinary English, so
// only as a rel value.
[
'network',
'resource hint',
/\b(?:prefetch|preconnect|prerender|dns-prefetch|modulepreload)\b|\brel\s*=\s*["'`]?preload\b/gi,
],
// Two linear steps: find a resource-loading tag, then look inside it.
[
'network',
'remote resource in markup',
/<(?:img|script|iframe|frame|link|source|video|audio|embed|object|track|image)\b[^>]*>/gi,
new RegExp(String.raw`\b(?:src|href|srcset|data|poster)\s*=\s*(?:["'{]\s*)?` + REMOTE, 'i'),
],
['network', 'remote url() in CSS', new RegExp(String.raw`url\(\s*(?:["']\s*)?` + REMOTE, 'gi')],
[
'network',
'remote @import',
new RegExp(String.raw`@import\s+(?:url\(\s*)?(?:["']\s*)?` + REMOTE, 'gi'),
],
// Remote code.
['remote code', 'eval', /\beval\b/g],
['remote code', 'Function constructor', /\bFunction\s*\(/g],
['remote code', 'string timer', /\bset(?:Timeout|Interval)\s*\(\s*["'`]/g],
// `[ \t]*`, not `\s*`: prose that ends a line with "import" and opens the
// next with "(" is common in comments, and the MV3 CSP already refuses any
// remote script, so this rule is a second line of defence, not the only one.
['remote code', 'dynamic import', /(?:^|[^.\w$])import[ \t]*\(/g],
[
'remote code',
'import from URL',
new RegExp(String.raw`\b(?:from|import)\s+["']` + REMOTE, 'g'),
],
// Raw HTML sinks.
['raw HTML', '{@html}', /\{\s*@html\b/g],
['raw HTML', 'innerHTML / outerHTML', /\b(?:inner|outer)HTML\b/g],
['raw HTML', 'insertAdjacentHTML', /\binsertAdjacentHTML\b/g],
['raw HTML', 'setHTMLUnsafe / parseHTMLUnsafe', /\b(?:set|parse)HTMLUnsafe\b/g],
['raw HTML', 'createContextualFragment', /\bcreateContextualFragment\b/g],
['raw HTML', 'srcdoc', /\bsrcdoc\b/gi],
['raw HTML', 'document.write', /\bdocument\s*\.\s*write(?:ln)?\b/g],
];
/** Test files may reference banned identifiers when asserting they are absent. */
const isExempt = (path) => /\.(test|spec)\.ts$/.test(path);
async function* walk(dir) {
let entries;
try {
entries = await readdir(dir, { withFileTypes: true });
} catch {
return; // directory not created yet — nothing to scan
/** @param {string[]} argv */
function rootFrom(argv) {
const at = argv.indexOf('--root');
if (at === -1) return DEFAULT_ROOT;
const value = argv[at + 1];
if (value === undefined || value.startsWith('--')) {
console.error('guard: --root needs a directory');
process.exit(2);
}
for (const entry of entries) {
return resolve(value);
}
/**
* @param {string} dir
* @returns {AsyncGenerator<string>}
*/
async function* walk(dir) {
for (const entry of await readdir(dir, { withFileTypes: true })) {
const full = join(dir, entry.name);
if (entry.isDirectory()) {
if (!SKIP_DIRS.has(entry.name)) yield* walk(full);
@@ -55,30 +148,85 @@ async function* walk(dir) {
}
}
/**
* Every rule over one file's text.
* @param {string} text
* @returns {{ line: number, name: string, category: string, excerpt: string }[]}
*/
function scan(text) {
const lines = text.split('\n');
const lineStarts = [0];
for (let i = 0; i < text.length; i++) if (text.charCodeAt(i) === 0x0a) lineStarts.push(i + 1);
/** @param {number} index */
const lineOf = (index) => {
let lo = 0;
let hi = lineStarts.length - 1;
while (lo < hi) {
const mid = (lo + hi + 1) >> 1;
if ((lineStarts[mid] ?? 0) <= index) lo = mid;
else hi = mid - 1;
}
return lo + 1;
};
const found = [];
const seen = new Set();
for (const [category, name, pattern, refine] of RULES) {
for (const match of text.matchAll(/** @type {RegExp} */ (pattern))) {
if (refine instanceof RegExp && !refine.test(match[0])) continue;
const line = lineOf(match.index ?? 0);
const key = `${line}\u0000${name}`;
if (seen.has(key)) continue;
seen.add(key);
const excerpt = (lines[line - 1] ?? '').trim().slice(0, 120);
found.push({
line,
name: /** @type {string} */ (name),
category: /** @type {string} */ (category),
excerpt,
});
}
}
return found;
}
const root = rootFrom(process.argv.slice(2));
const violations = [];
let scanned = 0;
for (const dir of SCAN_DIRS) {
for await (const file of walk(join(ROOT, dir))) {
const rel = relative(ROOT, file).replace(/\\/g, '/');
if (isExempt(rel)) continue;
const lines = readFileSync(file, 'utf8').split(/\r?\n/);
lines.forEach((line, i) => {
for (const [name, pattern] of BANNED) {
if (pattern.test(line)) violations.push({ rel, line: i + 1, name, text: line.trim() });
}
});
const base = join(root, dir);
try {
for await (const file of walk(base)) {
scanned++;
const rel = relative(root, file).replace(/\\/g, '/');
const text = readFileSync(file, 'utf8').replace(/\r\n?/g, '\n');
for (const hit of scan(text)) violations.push({ rel, ...hit });
}
} catch (cause) {
// A missing src/ used to be "nothing to scan" and printed clean. A gate
// that cannot see the code has not passed it.
console.error(`guard: cannot scan ${base} — ${cause instanceof Error ? cause.message : cause}`);
process.exitCode = 1;
}
}
if (process.exitCode !== 1 && scanned === 0) {
console.error(`guard: scanned 0 files under ${root} — refusing to report clean.`);
process.exitCode = 1;
}
if (violations.length > 0) {
for (const v of violations) {
console.error(`::error file=${v.rel},line=${v.line}::[${v.name}] ${v.text}`);
console.error(` ${v.rel}:${v.line} ${v.name}\n ${v.text}`);
console.error(`::error file=${v.rel},line=${v.line}::[${v.category}: ${v.name}] ${v.excerpt}`);
console.error(` ${v.rel}:${v.line} ${v.category}: ${v.name}\n ${v.excerpt}`);
}
console.error(
`\nguard: ${violations.length} banned pattern(s) found. See docs/08_MV3_COMPLIANCE.md §3.`,
);
process.exit(1);
console.error(`\nguard: ${violations.length} banned pattern(s). See docs/08 §3.`);
process.exitCode = 1;
}
console.warn(`guard: clean — no banned patterns in ${SCAN_DIRS.join(', ')}`);
if (process.exitCode !== 1) {
console.warn(
`guard: clean — ${scanned} files under ${SCAN_DIRS.join(', ')}, ${RULES.length} rules`,
);
}
+151
View File
@@ -0,0 +1,151 @@
#!/usr/bin/env node
// @ts-check
/**
* Strip personal data from a bookmark file, keeping the bug.
*
* Purpose: make "attach a sanitized sample" (SECURITY.md, the parser issue
* form) something a reporter can actually do, instead of an instruction they
* have to interpret.
* Inputs: a Netscape HTML export, BookmarkMagic JSON, Chrome's profile
* `Bookmarks` file (also Edge/Brave/Vivaldi), a Firefox `.json` backup, or a
* docs/04 §3 CSV.
* Guarantees: every byte outside a replaced address, title or note is untouched
* — the BOM, the doctype, line endings, tag and attribute case, quoting style,
* indentation, JSON key order and escapes, and every timestamp. Replacements
* are stable per distinct input value, so "how many distinct hosts" and
* "which two bookmarks are duplicates" survive. When the output still looks
* personal, nothing is written at all.
*
* Zero dependencies, Node stdlib only, no network, plain JavaScript: it has to
* run from a fresh clone with nothing installed, on whatever Node the reporter
* has. The format modules live in scripts/sanitize/.
*
* Usage:
* node scripts/sanitize-bookmarks.mjs <input> [output]
* node scripts/sanitize-bookmarks.mjs <input> --stdout
* node scripts/sanitize-bookmarks.mjs <input> --check # report, write nothing
*/
import { readFileSync, statSync, writeFileSync } from 'node:fs';
import { basename, extname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { sanitizeCsv } from './sanitize/csv.mjs';
import { detectKind } from './sanitize/detect.mjs';
import { sanitizeHtml } from './sanitize/html.mjs';
import { sanitizeJson } from './sanitize/json.mjs';
import { findLeakedHosts, findLeakedWords } from './sanitize/leaks.mjs';
import { makeTitleMapper, makeUrlMapper } from './sanitize/mappers.mjs';
export { detectKind } from './sanitize/detect.mjs';
export { findLeakedHosts, findLeakedWords } from './sanitize/leaks.mjs';
/** Matches docs/09's parse cap. A 25 MB attachment helps nobody anyway. */
const MAX_BYTES = 25 * 1024 * 1024;
/**
* Sanitize a bookmark file's text.
*
* @param {string} text
* @returns {{ text: string | null, kind: import('./sanitize/detect.mjs').Kind | null, leaked: string[] }}
* `text` is null when the format was not recognised, or when the output
* failed its own leak check. Both mean: write nothing.
*/
export function sanitize(text) {
const kind = detectKind(text);
if (kind === null) return { text: null, kind: null, leaked: [] };
const mapUrl = makeUrlMapper();
const mapTitle = makeTitleMapper();
let out;
if (kind === 'html') out = sanitizeHtml(text, mapUrl, mapTitle);
else if (kind === 'csv') out = sanitizeCsv(text, mapUrl, mapTitle);
else out = sanitizeJson(text, mapUrl, mapTitle);
const leaked = [
...findLeakedHosts(out),
...(kind === 'html' ? findLeakedWords(out).map((word) => `text "${word}"`) : []),
];
return { text: leaked.length > 0 ? null : out, kind, leaked };
}
/** @param {string} input */
function refuseUnknown(input) {
console.error(
`${basename(input)} is not a bookmark file this tool recognises, so NOTHING WAS WRITTEN.\n` +
' Expected one of: a Netscape HTML export (the usual bookmarks.html), a BookmarkMagic\n' +
' JSON export, Chrome\'s profile "Bookmarks" file, a Firefox bookmarks-*.json backup,\n' +
' or a CSV whose header is exactly "folder_path,title,url,add_date".\n' +
' Refusing to hand you a file it cannot promise is clean. Please attach the export\n' +
' exactly as your browser wrote it, or describe the problem in the issue instead.',
);
return 1;
}
/** @param {string} input @param {string[]} leaked */
function refuseLeak(input, leaked) {
console.error(
`${basename(input)}: NOTHING WAS WRITTEN — the result still contained ${leaked.length} item(s) ` +
`that look personal, so this file is not safe to attach.\n Found: ${leaked.slice(0, 5).join(', ')}` +
`${leaked.length > 5 ? `, and ${leaked.length - 5} more` : ''}\n` +
' This is a bug in the sanitizer, not in your file. Please report it (without the file)\n' +
' at https://github.com/poli0981/bookmarkmagic/issues — the list above is enough.',
);
return 1;
}
/** @param {string[]} argv */
function main(argv) {
const flags = argv.filter((a) => a.startsWith('--'));
const [input, maybeOutput] = argv.filter((a) => !a.startsWith('--'));
if (input === undefined) {
console.error('usage: node scripts/sanitize-bookmarks.mjs <input> [output] [--stdout|--check]');
return 1;
}
// Size first, from the file system: reading a 2 GB file to learn it is too
// big is how the old version ran out of memory before its own check.
const size = statSync(input).size;
if (size > MAX_BYTES) {
console.error(
`${input} is ${(size / 1024 / 1024).toFixed(1)} MB. The extension itself refuses ` +
'anything over 25 MB, and a smaller file that still reproduces the bug is more useful. ' +
'Please trim it first.',
);
return 1;
}
const text = readFileSync(input).toString('utf8');
const { text: out, kind, leaked } = sanitize(text);
if (kind === null) return refuseUnknown(input);
if (out === null) return refuseLeak(input, leaked);
const eol = text.includes('\r\n') ? 'CRLF' : 'LF';
const bom = text.charCodeAt(0) === 0xfeff ? ', BOM' : '';
console.error(
`${basename(input)}: ${kind}, ${eol}${bom} — ${Buffer.byteLength(out)} bytes out, no leaks`,
);
if (flags.includes('--check')) return 0;
if (flags.includes('--stdout')) {
process.stdout.write(out);
return 0;
}
const ext = extname(input);
const target = maybeOutput ?? `${input.slice(0, input.length - ext.length)}.sanitized${ext}`;
// Never over the original: an output path equal to the input used to replace
// the user's only copy of their real bookmarks with the placeholder version.
if (resolve(target) === resolve(input)) {
console.error(
`refusing to overwrite ${input} with its sanitized copy — pick another output path.`,
);
return 1;
}
writeFileSync(target, out);
console.error(`wrote ${target}`);
return 0;
}
if (process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
process.exitCode = main(process.argv.slice(2));
}
+118
View File
@@ -0,0 +1,118 @@
// @ts-check
/**
* CSV (docs/04 §3): a minimal RFC 4180 reader that records the span of each
* field's *content* (inside the quotes, when quoted). Replacements never
* contain a delimiter, quote or newline, so the original quoting survives —
* which matters, because CSV quoting is itself a common bug.
*/
import { replaceSpans } from './spans.mjs';
/** @typedef {import('./spans.mjs').Span} Span */
/** @typedef {import('./mappers.mjs').Mapper} Mapper */
/** @typedef {{ row: number, col: number, start: number, end: number }} Field */
/**
* @param {string} text
* @param {string} delimiter
* @returns {Field[]}
*/
function readFields(text, delimiter) {
/** @type {Field[]} */
const fields = [];
let row = 0;
let col = 0;
let i = 0;
while (i < text.length) {
const quoted = text[i] === '"';
if (quoted) i++;
const start = i;
while (i < text.length) {
const ch = text[i];
if (quoted) {
if (ch === '"' && text[i + 1] === '"') i += 2;
else if (ch === '"') break;
else i++;
} else if (ch === delimiter || ch === '\n' || ch === '\r') {
break;
} else {
i++;
}
}
fields.push({ row, col, start, end: i });
if (quoted && text[i] === '"') i++;
if (text[i] === delimiter) {
col++;
i++;
} else {
if (text[i] === '\r') i++;
if (text[i] === '\n') i++;
row++;
col = 0;
}
}
return fields;
}
/**
* Map each path segment separately so `\/` and `\\` escapes keep their meaning.
* A segment that contained a literal slash or backslash keeps one, so the
* escape branch of the CSV path parser — a real reason someone files a report —
* is still exercised by the sample.
*
* @param {string} path
* @param {Mapper} mapTitle
*/
function mapFolderPath(path, mapTitle) {
const segments = [];
let current = '';
for (let i = 0; i < path.length; i++) {
const ch = path[i];
if (ch === '\\' && (path[i + 1] === '/' || path[i + 1] === '\\')) {
current += path[i + 1];
i++;
} else if (ch === '/') {
segments.push(current);
current = '';
} else {
current += ch;
}
}
segments.push(current);
return segments
.map((s) => {
if (s === '') return '';
const kept = `${s.includes('/') ? '/' : ''}${s.includes('\\') ? '\\' : ''}`;
return `${mapTitle(s)}${kept}`.replace(/\\/g, '\\\\').replace(/\//g, '\\/');
})
.join('/');
}
/**
* @param {string} text
* @param {Mapper} mapUrl
* @param {Mapper} mapTitle
*/
export function sanitizeCsv(text, mapUrl, mapTitle) {
const delimiter = (text.split('\n', 1)[0] ?? '').includes(';') ? ';' : ',';
const fields = readFields(text, delimiter);
// Column names per docs/04 §3 — `folder_path`, not `folder`.
const header = fields.filter((f) => f.row === 0).map((f) => text.slice(f.start, f.end).trim());
/** @param {string} name */
const at = (name) => header.findIndex((h) => h.toLowerCase().replace(/^/, '') === name);
const [folderCol, titleCol, urlCol] = [at('folder_path'), at('title'), at('url')];
/** @type {Span[]} */
const spans = [];
for (const f of fields) {
if (f.row === 0 || f.start === f.end) continue;
const value = text.slice(f.start, f.end).replace(/""/g, '"');
let mapped;
if (f.col === urlCol) mapped = mapUrl(value);
else if (f.col === titleCol) mapped = mapTitle(value);
else if (f.col === folderCol) mapped = mapFolderPath(value, mapTitle);
else continue;
spans.push({ start: f.start, end: f.end, value: mapped.replace(/"/g, '""') });
}
return replaceSpans(text, spans);
}
+80
View File
@@ -0,0 +1,80 @@
// @ts-check
/**
* Format sniffing for the sanitizer — refuse anything not positively known.
*
* Returning `null` rather than guessing is load-bearing. Every sanitizer finds
* what it must destroy *by format*, so a wrong guess destroys nothing and emits
* the input verbatim — and the file would still be handed over as "sanitized".
* The old `return 'csv'` fallback did exactly that for a truncated JSON export.
*
* The same goes for JSON: the old check accepted ANY object, and the JSON
* rewriter only knew BookmarkMagic's `title`/`url` keys — so Chrome's profile
* `Bookmarks` file, which keeps titles under `name`, "sanitized" with every
* title intact and passed the host check. Each JSON dialect is now recognised
* by shape, and anything else is refused.
*
* Re-implemented rather than imported from `src/lib/core/detect-format.ts`:
* this script must run from a fresh clone with nothing installed.
*/
/** The docs/04 §3 CSV header, in order. A file is CSV only if it says so. */
const CSV_HEADER = ['folder_path', 'title', 'url', 'add_date'];
/** @typedef {'html' | 'json' | 'chrome-json' | 'firefox-json' | 'csv'} Kind */
/**
* @param {unknown} doc
* @returns {'json' | 'chrome-json' | 'firefox-json' | null}
*/
export function jsonDialect(doc) {
if (typeof doc !== 'object' || doc === null || Array.isArray(doc)) return null;
const record = /** @type {Record<string, unknown>} */ (doc);
if (record.format === 'bookmarkmagic') return 'json';
const roots = record.roots;
if (
typeof roots === 'object' &&
roots !== null &&
!Array.isArray(roots) &&
['bookmark_bar', 'other', 'synced'].some((key) => key in roots)
) {
return 'chrome-json';
}
const isPlacesRoot = record.type === 'text/x-moz-place-container' || record.root === 'placesRoot';
if (isPlacesRoot && Array.isArray(record.children)) return 'firefox-json';
return null;
}
/**
* Identify the format, or refuse with `null`.
*
* The people who run this tool are, by definition, the ones whose file did not
* import — so a malformed or hand-trimmed file is the typical input here.
*
* @param {string} text
* @returns {Kind | null}
*/
export function detectKind(text) {
const body = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
const trimmed = body.trimStart();
// JSON first: a JSON title may legitimately contain the Netscape doctype
// string, and nothing that starts with `{` is HTML or CSV.
if (trimmed.startsWith('{')) {
try {
return jsonDialect(JSON.parse(trimmed));
} catch {
return null;
}
}
if (/NETSCAPE-Bookmark-file-1/i.test(body.slice(0, 512))) return 'html';
const firstLine = body.split(/\r?\n/, 1)[0] ?? '';
for (const delimiter of [',', ';']) {
const columns = firstLine
.split(delimiter)
.map((h) => h.trim().replace(/^"|"$/g, '').toLowerCase());
if (columns.length === CSV_HEADER.length && CSV_HEADER.every((c, i) => columns[i] === c)) {
return 'csv';
}
}
if (/<\s*dl[\s>]/i.test(body)) return 'html';
return null;
}
+121
View File
@@ -0,0 +1,121 @@
// @ts-check
/**
* Netscape HTML: rewrite addresses, titles, descriptions and user-authored
* attributes by span, leaving every other byte exactly as the browser wrote it.
*/
import { isAddressLike } from './mappers.mjs';
import {
ANY_ATTR,
attrRewriter,
attrSpans,
replaceSpans,
spansFrom,
TAG_INNARDS,
} from './spans.mjs';
/** @typedef {import('./spans.mjs').Span} Span */
/** @typedef {import('./mappers.mjs').Mapper} Mapper */
/** 1×1 transparent PNG. Keeps ICON= present, which is what the parser reacts to. */
const BLANK_ICON =
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=';
/** Attributes handled explicitly; the generic URL sweep must not touch them. */
const HANDLED_ATTRS = new Set(['href', 'icon']);
/**
* Scrub any *other* attribute whose value is an address. Firefox alone writes
* `ICON_URI`, and `FEEDURL` and friends exist in the wild; enumerating them was
* already wrong once, so this sweeps by value shape. `file:` counts: an
* `ICON_URI="file:///C:/Users/<name>/…"` has no host, and used to pass.
*
* @param {string} text
* @param {Mapper} mapUrl
* @returns {Span[]}
*/
function urlAttrSpans(text, mapUrl) {
/** @type {Span[]} */
const spans = [];
const rewrite = attrRewriter(mapUrl);
for (const m of text.matchAll(ANY_ATTR)) {
const name = (m[1] ?? '').toLowerCase();
const value = m[2] ?? m[3] ?? m[4] ?? '';
if (HANDLED_ATTRS.has(name) || value === '' || !isAddressLike(value)) continue;
const at = m.indices?.[2] ?? m.indices?.[3] ?? m.indices?.[4];
if (at !== undefined) spans.push({ start: at[0], end: at[1], value: rewrite(value) });
}
return spans;
}
/** The next element that ends a description: `<DT>`, `<DD>`, `<DL>` or a close. */
const DESCRIPTION_END = /<\s*(?:\/\s*)?(?:dt|dd|dl)\b/gi;
/**
* `<DD>` descriptions, found in one linear pass.
*
* The description runs to the next `<DT>/<DD>/<DL>` (or a closing one), not to
* the end of the line — a wrapped description used to leak its second line —
* and trailing whitespace stays outside the span, because the newline and
* indentation before the next tag are byte-level shape this tool keeps.
*
* Replaces `/<dd>([\s\S]*?)(?=\s*<…>|\s*$)/`, which backtracked polynomially
* (SonarCloud S8786) and matched only a bare `<dd>` — `<DD class=n>Private
* note` passed through untouched.
*
* @param {string} text
* @param {() => string} next
* @returns {Span[]}
*/
function descriptionSpans(text, next) {
/** @type {Span[]} */
const spans = [];
for (const open of text.matchAll(/<dd\b[^>]*>/gi)) {
const start = (open.index ?? 0) + open[0].length;
DESCRIPTION_END.lastIndex = start;
const close = DESCRIPTION_END.exec(text);
let end = close === null ? text.length : close.index;
while (end > start && /\s/.test(text.charAt(end - 1))) end--;
if (end > start) spans.push({ start, end, value: next() });
}
return spans;
}
/** A document heading that says nothing about its owner stays as it is. */
const GENERIC_HEADING = /^\s*bookmarks(?:\s+menu)?\s*$/i;
/**
* @param {string} text
* @param {Mapper} mapUrl
* @param {Mapper} mapTitle
*/
export function sanitizeHtml(text, mapUrl, mapTitle) {
let descriptions = 0;
let keywords = 0;
/** @param {string} heading */
const mapHeading = (heading) => (GENERIC_HEADING.test(heading) ? heading : mapTitle(heading));
const spans = [
// HREF and ICON, at any quoting — attribute name case is left as found.
...attrSpans(text, /^href$/, attrRewriter(mapUrl)),
...attrSpans(text, /^icon$/, () => BLANK_ICON),
...urlAttrSpans(text, mapUrl),
// Firefox keywords and tags are user-authored text, so they are personal
// too. Tag count is preserved because it is the only part a parser sees.
...attrSpans(text, /^shortcuturl$/, () => `kw${++keywords}`),
...attrSpans(text, /^tags$/, (v) =>
v
.split(',')
.map((_, i) => `tag${i + 1}`)
.join(','),
),
// Bookmark and folder titles. `[\s\S]*?`, not `[^<]*`: a title holding a
// raw `<` made the whole match fail and stay in the output.
...spansFrom(text, new RegExp(`<a\\b${TAG_INNARDS}>([\\s\\S]*?)</a>`, 'gi'), mapTitle),
...spansFrom(text, new RegExp(`<h3\\b${TAG_INNARDS}>([\\s\\S]*?)</h3>`, 'gi'), mapTitle),
// `<TITLE>` / `<H1>` — usually "Bookmarks", but an exporter can write the
// owner's name there ("Jane Doe's bookmarks").
...spansFrom(text, /<title\b[^>]*>([^<]*)<\/title>/gi, mapHeading),
...spansFrom(text, /<h1\b[^>]*>([^<]*)<\/h1>/gi, mapHeading),
...descriptionSpans(text, () => `Description ${++descriptions}`),
];
return replaceSpans(text, spans);
}
+159
View File
@@ -0,0 +1,159 @@
// @ts-check
/**
* JSON bookmark files — BookmarkMagic JSON, Chrome's profile `Bookmarks` file,
* and Firefox's `bookmarks-YYYY-MM-DD.json` backup.
*
* Default-deny: every string VALUE is replaced unless its key is on the short
* structural list below. The old rewriter was default-allow — it rewrote only
* `"url"` and `"title"`, so Chrome's titles (under `"name"`), Firefox's `uri`,
* `iconUri` and keywords, Chrome's `meta_info` and the base64 `sync_metadata`
* blob all went through untouched, and the host check could not see a title.
*
* Values are rewritten by span over the raw text (a small tokenizer tracks
* which key each string belongs to), so indentation, key order, escapes and
* line endings stay byte-for-byte as the browser wrote them.
*/
import { isAddressLike, makeGuidMapper } from './mappers.mjs';
import { replaceSpans } from './spans.mjs';
/** @typedef {import('./spans.mjs').Span} Span */
/** @typedef {import('./mappers.mjs').Mapper} Mapper */
/**
* Keys whose string values are structure, not content, and are kept verbatim:
* format markers, type tags, root identifiers, numeric ids and every timestamp
* (Chrome stores dates as decimal strings). Nothing a person typed lives here.
*/
const STRUCTURAL = new Set([
'format',
'generator',
'exportedAt',
'version',
'type',
'root',
'id',
'date_added',
'date_modified',
'date_last_used',
'charset',
'source',
]);
/** Keys whose value is an address, mapped even when it does not parse. */
const ADDRESS = new Set(['url', 'uri', 'iconuri']);
/**
* @typedef {{ kind: 'object' | 'array', key: string | null, expectKey: boolean, current: string | null }} Frame
* @typedef {{ start: number, end: number, raw: string, key: string | null, parentKey: string | null }} StringToken
*/
/**
* Every string VALUE in a JSON text, with the key it sits under and the key of
* the object that holds it (`annos[].value` → key "value", parentKey "annos").
* The input has already passed `JSON.parse`, so it is well-formed.
*
* @param {string} text
* @returns {StringToken[]}
*/
export function stringValues(text) {
/** @type {Frame[]} */
const stack = [];
/** @type {StringToken[]} */
const out = [];
// The key a new child sits under. Array elements inherit the array's key, so
// every object inside `"annos": [...]` reports "annos" as its parent.
const keyFor = () => {
const top = stack.at(-1);
return (top?.kind === 'object' ? top.current : top?.key) ?? null;
};
let i = 0;
while (i < text.length) {
const ch = text[i];
if (ch === '"') {
i = readString(text, i, stack, out, keyFor);
continue;
}
if (ch === '{' || ch === '[') {
stack.push({
kind: ch === '{' ? 'object' : 'array',
key: keyFor(),
expectKey: ch === '{',
current: null,
});
} else if (ch === '}' || ch === ']') {
stack.pop();
} else if (ch === ',') {
const top = stack.at(-1);
if (top?.kind === 'object') top.expectKey = true;
} else if (ch === ':') {
const top = stack.at(-1);
if (top !== undefined) top.expectKey = false;
}
i++;
}
return out;
}
/**
* One string token starting at the quote at `start`: a key updates its object
* frame, a value is recorded. Returns the index just past the closing quote.
*
* @param {string} text
* @param {number} start
* @param {Frame[]} stack
* @param {StringToken[]} out
* @param {() => string | null} keyFor
*/
function readString(text, start, stack, out, keyFor) {
let end = start + 1;
while (end < text.length && text[end] !== '"') end += text[end] === '\\' ? 2 : 1;
const raw = text.slice(start + 1, end);
const top = stack.at(-1);
if (top?.kind === 'object' && top.expectKey) {
top.current = JSON.parse(`"${raw}"`);
} else {
const holder = top?.kind === 'object' ? top : stack.at(-2);
out.push({ start: start + 1, end, raw, key: keyFor(), parentKey: holder?.key ?? null });
}
return end + 1;
}
/**
* @param {string} text
* @param {Mapper} mapUrl
* @param {Mapper} mapTitle
*/
export function sanitizeJson(text, mapUrl, mapTitle) {
const mapGuid = makeGuidMapper();
let keywords = 0;
/** @type {Span[]} */
const spans = [];
for (const token of stringValues(text)) {
const key = token.key ?? '';
const lower = key.toLowerCase();
if (STRUCTURAL.has(key)) continue;
// An anno's `name` is a schema id (bookmarkProperties/description); its
// `value` is what the person wrote.
if (token.parentKey === 'annos' && key === 'name') continue;
const value = /** @type {string} */ (JSON.parse(`"${token.raw}"`));
let mapped;
if (lower === 'guid') mapped = mapGuid(value);
else if (lower === 'checksum' || lower === 'checksum_sha256') mapped = '0'.repeat(value.length);
else if (lower === 'sync_metadata') mapped = '';
else if (lower === 'keyword') mapped = value === '' ? '' : `kw${++keywords}`;
else if (lower === 'tags')
mapped =
value === ''
? ''
: value
.split(',')
.map((_, i) => `tag${i + 1}`)
.join(',');
else if (ADDRESS.has(lower) || isAddressLike(value)) mapped = mapUrl(value);
else mapped = mapTitle(value);
spans.push({ start: token.start, end: token.end, value: JSON.stringify(mapped).slice(1, -1) });
}
return replaceSpans(text, spans);
}
+66
View File
@@ -0,0 +1,66 @@
// @ts-check
/**
* The backstop: check the OUTPUT, not the rules that produced it.
*
* The rewriting rules are patterns over untrusted markup, so each one has a
* shape it does not match — a single-quoted attribute, a title containing `<`,
* a JSON key nobody enumerated, a `<DD class=…>`. Every one of those is a silent
* leak, and nobody can honestly claim to have thought of every shape. So the
* output is inspected independently, and anything that still looks personal
* makes the tool refuse instead of handing the file over. A rule this misses
* degrades into a refusal — annoying — instead of a published browsing history.
*/
import { TAG_INNARDS } from './spans.mjs';
/**
* Hosts in the output that are not one of our own `*.example` aliases.
*
* @param {string} text sanitized output
* @returns {string[]} distinct suspicious hosts, empty when clean
*/
export function findLeakedHosts(text) {
const leaked = new Set();
for (const m of text.matchAll(/\b[a-z][a-z0-9+.-]*:\/\/([^\s"'<>)\]}\\]+)/gi)) {
const authority = (m[1] ?? '').split(/[/?#]/, 1)[0] ?? '';
// Strip credentials and port; what remains is the host.
const host = authority.split('@').pop()?.replace(/:\d+$/, '').toLowerCase() ?? '';
if (host === '' || /^[a-z]\d*\.example$/.test(host)) continue;
leaked.add(host);
}
return [...leaked];
}
/**
* Words the sanitized TEXT of a Netscape file may legitimately contain: our
* placeholders, the default heading, and the script samples the title mapper
* adds so an encoding bug still reproduces.
*/
const ALLOWED_WORDS = new Set(['title', 'description', 'bookmarks', 'bookmark', 'menu', 'شيء']);
/**
* Words in the document's text content — everything outside tags and comments —
* that are not placeholders.
*
* Independent of the rewriting rules on purpose: it does not look for `<A>` or
* `<H3>` at all, it strips markup and reads whatever text is left. The old
* backstop matched only `scheme://host`, so an unsanitized title, a `<DD>` note
* or an `<H1>Jane Doe's bookmarks</H1>` passed it, and the test that guarded it
* reused the same pattern and could never notice.
*
* @param {string} html sanitized Netscape output
* @returns {string[]} distinct offending words, empty when clean
*/
export function findLeakedWords(html) {
const text = html
.replace(/<!--[\s\S]*?-->/g, ' ')
// Script and style bodies are code. A browser export never contains them;
// the T1 injection fixtures do, and their payload is the point of the file.
.replace(/<(script|style)\b[^>]*>[\s\S]*?<\/\1\s*>/gi, ' ')
.replace(new RegExp(`<${TAG_INNARDS}>`, 'g'), ' ')
.replace(/&(?:#\d+|#x[0-9a-f]+|[a-z]+);/gi, ' ');
const leaked = new Set();
for (const [word] of text.matchAll(/\p{L}{3,}/gu)) {
if (!ALLOWED_WORDS.has(word.toLowerCase())) leaked.add(word);
}
return [...leaked];
}
+167
View File
@@ -0,0 +1,167 @@
// @ts-check
/**
* Value mappers: deterministic placeholders that keep what parsers branch on.
*
* Replacements are stable per distinct input value, so "how many distinct
* hosts" and "which two bookmarks are duplicates" survive sanitizing.
*/
/** @typedef {(raw: string) => string} Mapper */
/**
* Replace addresses while preserving everything a parser branches on: the
* scheme, whether there is a port, how deep the path is, whether it ends in a
* slash, how many query parameters there are and in what order, and whether
* there is a fragment. Percent-escapes are carried across literally, so a
* decoding bug still reproduces.
*
* @returns {Mapper}
*/
export function makeUrlMapper() {
/** @type {Map<string, string>} */
const seen = new Map();
/** @type {Map<string, string>} */
const hosts = new Map();
/** @param {string} host */
const hostAlias = (host) => {
let alias = hosts.get(host);
if (alias === undefined) {
const n = hosts.size;
// a.example … z.example, then a1.example, a2.example …
const letter = String.fromCharCode(97 + (n % 26));
const round = Math.floor(n / 26);
alias = round === 0 ? `${letter}.example` : `${letter}${round}.example`;
hosts.set(host, alias);
}
return alias;
};
/** @param {string} segment */
const escapesIn = (segment) => (segment.match(/%[0-9a-fA-F]{2}/g) ?? []).join('');
/** @param {string} pathname */
const mapPath = (pathname) => {
if (pathname === '' || pathname === '/') return pathname;
const trailing = pathname.endsWith('/');
const parts = pathname.replace(/^\//, '').replace(/\/$/, '').split('/');
const mapped = parts.map((p, i) => (p === '' ? '' : `p${i + 1}${escapesIn(p)}`));
return `/${mapped.join('/')}${trailing ? '/' : ''}`;
};
/** @param {string} search */
const mapQuery = (search) => {
if (search === '') return '';
return `?${search
.slice(1)
.split('&')
.map((pair, i) => (pair.includes('=') ? `q${i + 1}=v${i + 1}` : `q${i + 1}`))
.join('&')}`;
};
return (raw) => {
if (raw === '') return raw;
const cached = seen.get(raw);
if (cached !== undefined) return cached;
let out;
let url;
try {
url = new URL(raw);
} catch {
url = undefined;
}
if (url === undefined) {
// Keep it unparseable, and keep distinct values distinct — the dedupe
// path treats an unparseable URL as its own trimmed self.
out = `not-a-url-${seen.size + 1}`;
} else if (url.host === '') {
// Opaque or hostless scheme (javascript:, data:, mailto:, file:, place:).
// The scheme is the whole point for the T1/T3 threat cases; the payload —
// which for file: is a local path with a user name in it — is not ours.
out = `${url.protocol}sanitized-${seen.size + 1}`;
} else {
// Credentials are never round-tripped, not even as placeholders.
const port = url.port === '' ? '' : `:${url.port}`;
const hash = url.hash === '' ? '' : '#frag';
out = `${url.protocol}//${hostAlias(url.host.replace(/:\d+$/, ''))}${port}${mapPath(url.pathname)}${mapQuery(url.search)}${hash}`;
}
seen.set(raw, out);
return out;
};
}
/**
* Replace titles while preserving what encoding bugs live in: emptiness, the
* scripts present (so a CJK or RTL or emoji bug still reproduces), and any HTML
* entity references, which are carried across verbatim.
*
* @returns {Mapper}
*/
export function makeTitleMapper() {
/** @type {Map<string, string>} */
const seen = new Map();
/** @type {[RegExp, string][]} */
const SCRIPTS = [
[/[一-鿿぀-ヿ]/, '文字'],
[/[֐-ࣿ]/, 'شيء'],
[/[\p{Extended_Pictographic}]/u, '🌸'],
];
return (raw) => {
if (raw.trim() === '') return raw;
const cached = seen.get(raw);
if (cached !== undefined) return cached;
const entities = (raw.match(/&(?:#\d+|#x[0-9a-fA-F]+|[a-zA-Z]+);/g) ?? []).join('');
const extras = SCRIPTS.filter(([re]) => re.test(raw))
.map(([, sample]) => sample)
.join('');
const out = `Title ${seen.size + 1}${extras === '' ? '' : ` ${extras}`}${entities}`;
seen.set(raw, out);
return out;
};
}
/** Firefox's fixed root GUIDs — structural, and the parser keys off them. */
const RESERVED_GUID = /^(?:root|menu|toolbar|unfiled|mobile|tags)_+$/;
/**
* Replace bookmark GUIDs with stable fakes of the same shape. They are random,
* but they are also the identifier sync uses, so they could tie a public sample
* to an account; the root GUIDs are kept because they carry meaning.
*
* @returns {Mapper}
*/
export function makeGuidMapper() {
/** @type {Map<string, string>} */
const seen = new Map();
return (raw) => {
if (raw === '' || RESERVED_GUID.test(raw)) return raw;
const cached = seen.get(raw);
if (cached !== undefined) return cached;
const n = String(seen.size + 1);
const out = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(raw)
? `00000000-0000-4000-8000-${n.padStart(12, '0')}`
: `g${n.padStart(Math.max(raw.length - 1, n.length), '0')}`;
seen.set(raw, out);
return out;
};
}
/**
* True when a value is a URL whose payload could identify someone: it has a
* host, or it is a `file:` path (`file:///C:/Users/<name>/…` has no host).
*
* @param {string} value
*/
export function isAddressLike(value) {
try {
const url = new URL(value);
return url.host !== '' || url.protocol === 'file:';
} catch {
return false;
}
}
+125
View File
@@ -0,0 +1,125 @@
// @ts-check
/**
* Span rewriting: every change is a [start, end) → value replacement, so the
* bytes between spans are provably untouched. Rebuilding the file from a parsed
* model would quietly normalize them, and the byte-level shape is often the bug.
*/
/** @typedef {{ start: number, end: number, value: string }} Span */
/**
* Apply replacements right to left by character span.
*
* Overlaps are dropped, outermost first. Two patterns can legitimately claim
* the same bytes — an <A> title containing `x="http://…"` matches both the
* title rule and the generic attribute sweep — and applying both would splice
* already-rewritten text using an `end` measured against the original. The
* widest span sanitizes the most.
*
* @param {string} text
* @param {Span[]} spans
*/
export function replaceSpans(text, spans) {
const ordered = [...spans].sort((a, b) => a.start - b.start || b.end - a.end);
const out = [];
let cursor = 0;
for (const span of ordered) {
if (span.start < cursor) continue;
out.push(text.slice(cursor, span.start), span.value);
cursor = span.end;
}
out.push(text.slice(cursor));
// Joined once rather than spliced per span: splicing is O(spans × file),
// which took minutes on a large export.
return out.join('');
}
/**
* Spans for one capture group of a global regex; `map` receives the captured
* text. The `d` flag gives exact per-group offsets — searching the match for
* the captured substring lands on the wrong copy whenever the capture also
* appears earlier in the match (a title equal to part of its own URL).
*
* @param {string} text
* @param {RegExp} re
* @param {(captured: string) => string} map
* @param {number} [group]
* @returns {Span[]}
*/
export function spansFrom(text, re, map, group = 1) {
const indexed = new RegExp(re.source, re.flags.includes('d') ? re.flags : `${re.flags}d`);
/** @type {Span[]} */
const spans = [];
for (const m of text.matchAll(indexed)) {
const captured = m[group] ?? '';
const at = m.indices?.[group];
if (captured === '' || at === undefined) continue;
spans.push({ start: at[0], end: at[1], value: map(captured) });
}
return spans;
}
/**
* The inside of an opening tag, tolerating `>` within quoted attribute values.
* `data:text/html,<h1>hi</h1>` is a legal HREF in the T1/T3 fixtures, and a
* naive `[^>]*` stopped inside it, leaving that bookmark's title unsanitized.
*/
export const TAG_INNARDS = '(?:"[^"]*"|\'[^\']*\'|[^>"\'])*';
/** The four entities Netscape exporters write inside attribute values. */
const ATTR_ENTITY = /&(amp|lt|gt|quot);/gi;
/** @type {Record<string, string>} */
const ATTR_DECODE = { amp: '&', lt: '<', gt: '>', quot: '"' };
/**
* Decode an HTML attribute value, map it, then re-encode it the way the source
* file encoded it.
*
* Decoding is ONE pass. Chained `.replace()` calls (`&amp;` first, then `&lt;`)
* turned `&amp;lt;` into `<` — a double unescape (CodeQL js/double-escaping).
* Netscape exports write `&amp;` inside HREF but not all of them do, and
* emitting a bare `&` where the source had `&amp;` would silently repair the
* file being reported.
*
* @param {(value: string) => string} map
* @returns {(captured: string) => string}
*/
export function attrRewriter(map) {
return (captured) => {
const decoded = captured.replace(
ATTR_ENTITY,
(_m, name) => ATTR_DECODE[name.toLowerCase()] ?? _m,
);
const mapped = map(decoded);
const escapesAmp = /&amp;/i.test(captured) || !captured.includes('&');
return escapesAmp ? mapped.replace(/&/g, '&amp;') : mapped;
};
}
/**
* `name = value`, where the value is double-quoted, single-quoted or bare.
* Group 2/3/4 is the value, whichever quoting was used — matching only `"…"`
* left `HREF='https://…'` completely untouched.
*/
export const ANY_ATTR = /\b([a-z_][a-z0-9_-]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'<>=`]+))/dgi;
/**
* Spans for every attribute whose (lower-cased) name matches, at any quoting.
*
* @param {string} text
* @param {RegExp} nameRe
* @param {(value: string) => string} map
* @returns {Span[]}
*/
export function attrSpans(text, nameRe, map) {
/** @type {Span[]} */
const spans = [];
for (const m of text.matchAll(ANY_ATTR)) {
if (!nameRe.test((m[1] ?? '').toLowerCase())) continue;
const at = m.indices?.[2] ?? m.indices?.[3] ?? m.indices?.[4];
const value = m[2] ?? m[3] ?? m[4] ?? '';
if (at === undefined || value === '') continue;
spans.push({ start: at[0], end: at[1], value: map(value) });
}
return spans;
}
+28
View File
@@ -0,0 +1,28 @@
# SonarCloud — CI-based analysis (docs/12 §2.5). Read by
# .github/workflows/sonarcloud.yml; Automatic Analysis must stay OFF in the
# SonarCloud project (Administration → Analysis Method), or the scan errors out.
sonar.projectKey=poli0981_bookmarkmagic
sonar.organization=poli0981
sonar.projectName=BookmarkMagic
sonar.sourceEncoding=UTF-8
# What ships, plus the repo tooling that guards it.
sonar.sources=src,scripts
# Icons and the _locales message catalogues are data, not code.
sonar.exclusions=src/public/**
sonar.tests=tests
sonar.test.inclusions=tests/**/*.ts
# Fixtures are byte-exact samples of what browsers emit — malformed on purpose
# (a no-doctype HTML file is a test case, not a bug), never something to "fix".
sonar.test.exclusions=tests/fixtures/**
# Coverage scope mirrors docs/11 §1: components, entrypoints and repo scripts
# are verified by the manual QA pass and their own script tests, not by line
# coverage. Everything else in src/ is unit-tested and counted.
sonar.javascript.lcov.reportPaths=coverage/lcov.info
sonar.coverage.exclusions=src/entrypoints/**,src/lib/components/**,**/*.svelte,scripts/**
# The three locale dictionaries are parallel by design (en is the schema, vi/ja
# `satisfies Dict`); their "duplication" is the i18n contract working.
sonar.cpd.exclusions=src/lib/i18n/locales/**
+135 -16
View File
@@ -1,30 +1,101 @@
<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 { subscribeStorage } from '@/lib/browser/storage';
import { adoptExternalLegal } from '@/lib/stores/legal.svelte';
import {
adoptExternalSettings,
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();
// The tab bar and the footer already refuse to navigate mid-write. This
// closes the third door: browser Back, which fires `hashchange` directly
// and — during the backup attestation — used to unmount ImportTab and leave
// the Manager permanently locked.
const stopRouting = startRouting({
isBlocked: isWriting,
onBlocked: () => pushToast(t('common.busy'), 'info'),
});
// Leaving mid-write would kill the queue with the tab (docs/03 §5).
const onBeforeUnload = (event: BeforeUnloadEvent): void => {
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();
};
// Two Manager tabs used to overwrite each other silently: `save()` writes
// the whole settings object, so a tab holding a stale locale reverted the
// other tab's language change the moment its own theme toggle fired.
// Registered here rather than in main.ts because this is the only place
// with a teardown path.
const stopStorage = subscribeStorage((change) => {
if (change.settings !== undefined) adoptExternalSettings(change.settings);
if ('legal' in change) adoptExternalLegal(change.legal ?? null);
});
globalThis.addEventListener('beforeunload', onBeforeUnload);
globalThis.document?.addEventListener('visibilitychange', onVisibilityChange);
return () => {
stopRouting();
stopStorage();
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 +103,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 +196,12 @@
gap: var(--sp-2);
}
.controls {
display: flex;
align-items: center;
gap: var(--sp-2);
}
.mark {
color: var(--accent);
}
@@ -95,10 +213,6 @@
min-height: 60vh;
}
.placeholder {
color: var(--fg-muted);
}
footer nav {
display: flex;
gap: var(--sp-3);
@@ -113,7 +227,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;
}
+16 -4
View File
@@ -11,7 +11,7 @@
import { browser } from 'wxt/browser';
import type { BookmarkNode } from '../core/model';
import { millisToSeconds } from '../core/timestamps';
import { BmAborted, BmBrowserError } from './errors';
import { BmAborted, BmBrowserError, BmEnvError, BmPartialWrite } from './errors';
/** The live-tree node. Unlike `BookmarkNode` it carries browser identity. */
export interface LiveNode {
@@ -70,7 +70,10 @@ export async function getRoots(): Promise<BookmarkRoots> {
const mobile = byId('3') ?? writable.find((node) => node !== toolbar && node !== other);
if (toolbar === undefined || other === undefined) {
throw new BmBrowserError('bookmarks.getTree', 'no writable bookmark roots found');
// Not a BmBrowserError: nothing refused anything. Every root this profile
// has is policy-managed, so there is nowhere an extension may write, and
// "the browser refused a bookmark operation" would be actively misleading.
throw new BmEnvError('NO_WRITABLE_ROOTS', `${children.length} root(s), none writable`);
}
return {
@@ -210,6 +213,11 @@ export function subscribe(handlers: BookmarkEvents): () => void {
/**
* Delete the CHILDREN of the given roots, never the roots themselves (the API
* forbids that anyway). Managed nodes are skipped — docs/05 §6.
*
* @throws {BmAborted} on cancellation, carrying how many were already removed.
* @throws {BmPartialWrite} when a removal rejects, carrying the same count.
* This is the one path that destroys data, so "how much is gone" is the
* single most useful thing the failure can say.
*/
export async function clearRoots(
roots: readonly LiveNode[],
@@ -222,8 +230,12 @@ export async function clearRoots(
if (child.unmodifiable !== undefined) continue;
// Checked per node so a cancel arriving mid-deletion stops promptly
// rather than running the whole tree to completion.
if (signal?.aborted === true) throw new BmAborted(0);
await removeTree(child.id);
if (signal?.aborted === true) throw new BmAborted(removed);
try {
await removeTree(child.id);
} catch (cause) {
throw new BmPartialWrite('clearing', removed, cause);
}
removed++;
}
}
+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;
}
}
+66
View File
@@ -0,0 +1,66 @@
/**
* Map a thrown value onto an i18n key plus the raw technical detail —
* docs/02 §7.
*
* Purpose: one place that decides how a failure is described, so the
* "localized sentence + separate detail block" contract cannot be got wrong
* in one tab and right in another.
* Inputs: anything thrown by the core, browser or import layers.
* Guarantees: returns a **key**, never a resolved sentence, and never throws.
*
* Two rules this encodes, both learned from real defects:
*
* - The key is not resolved here. The import session store outlives the
* component that wrote to it, and `t()` is only reactive where it is called,
* so a sentence stored at throw time would never follow a language switch.
* - `detail` is a *separate* field, never a substitute for the message.
* Rendering `detail ?? t(key)` makes every translation dead code, because the
* raw browser string is almost always present.
*
* Lives in `browser/` because that is where the error taxonomy lives;
* `browser/` may import `core/`, not the reverse (docs/02 §3).
*/
import { BmParseError } from '../core/model';
import { BmBackupError, BmBrowserError, BmEnvError, BmPartialWrite } from './errors';
export interface DescribedError {
/** Dotted i18n path, e.g. `errors.TOO_DEEP`. */
messageKey: string;
/** Raw, untranslated technical text for the copyable detail block. */
detail?: string | undefined;
/** Nodes written before a partial failure, when the failure knows. */
created?: number;
/** Root children deleted before a partial failure, when the failure knows. */
removed?: number;
}
export function describeError(err: unknown): DescribedError {
if (err instanceof BmParseError) {
return { messageKey: `errors.${err.code}`, detail: err.detail };
}
if (err instanceof BmBackupError) {
return { messageKey: `errors.${err.code}`, detail: err.message };
}
if (err instanceof BmEnvError) {
return {
messageKey: `errors.${err.code}`,
...(err.detail !== undefined && { detail: err.detail }),
};
}
if (err instanceof BmPartialWrite) {
// The phase decides the sentence, because "nothing was deleted, some items
// were added" and "part of your tree is gone" need different advice.
return {
messageKey: err.phase === 'clearing' ? 'errors.PARTIAL_CLEAR' : 'errors.PARTIAL_WRITE',
...(err.detail !== undefined && { detail: err.detail }),
...(err.phase === 'clearing' ? { removed: err.done } : { created: err.done }),
};
}
if (err instanceof BmBrowserError) {
return { messageKey: 'errors.BROWSER', detail: err.detail };
}
return {
messageKey: 'errors.UNKNOWN',
detail: err instanceof Error ? err.message : undefined,
};
}
+55
View File
@@ -46,3 +46,58 @@ export class BmBrowserError extends Error {
this.detail = detail;
}
}
export type BmEnvCode = 'NO_WRITABLE_ROOTS';
/**
* Thrown when the environment cannot support the operation at all.
*
* Distinct from `BmBrowserError` on purpose: an absence is not a refusal.
* Reporting "the browser refused a bookmark operation" to someone whose profile
* simply has no writable root sends them looking for the wrong thing.
*/
export class BmEnvError extends Error {
readonly code: BmEnvCode;
readonly detail: string | undefined;
constructor(code: BmEnvCode, detail?: string) {
super(detail === undefined ? code : `${code}: ${detail}`);
this.name = 'BmEnvError';
this.code = code;
this.detail = detail;
}
}
/** Which destructive step was interrupted. */
export type BmWritePhase = 'clearing' | 'writing';
/**
* Thrown when a destructive step failed part-way through.
*
* Carries exactly what already landed, for the same reason `BmAborted` carries
* `done`: a user whose tree was half-replaced needs a number and the name of
* their backup, not "the browser refused a bookmark operation".
*
* `cause` is deliberately not used — `noImplicitOverride` complicates
* redeclaring it, and the detail is flattened here anyway so the UI never has
* to unwrap a chain.
*/
export class BmPartialWrite extends Error {
readonly phase: BmWritePhase;
readonly done: number;
readonly detail: string | undefined;
constructor(phase: BmWritePhase, done: number, cause: unknown) {
const detail =
cause instanceof BmBrowserError
? cause.detail
: cause instanceof Error
? cause.message
: String(cause);
super(`${phase} failed after ${done} item(s): ${detail}`);
this.name = 'BmPartialWrite';
this.phase = phase;
this.done = done;
this.detail = detail;
}
}
+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;
}
+53 -6
View File
@@ -81,15 +81,21 @@ export async function writeSettings(settings: Settings): Promise<void> {
await browser.storage.local.set({ [SETTINGS_KEY]: settings });
}
/** Keep only a well-formed acceptance record; anything else is "never accepted". */
function coerceLegal(raw: unknown): LegalAcceptance | null {
if (!isRecord(raw) || typeof raw.acceptedVersion !== 'number') return null;
return {
acceptedVersion: raw.acceptedVersion,
// Coerced rather than left missing: `Intl.format(new Date(''))` throws a
// RangeError inside a render, which would blank the About tab.
acceptedAt: typeof raw.acceptedAt === 'string' ? raw.acceptedAt : '',
};
}
export async function readLegal(): Promise<LegalAcceptance | null> {
try {
const stored = await browser.storage.local.get(LEGAL_KEY);
const raw = stored[LEGAL_KEY];
if (!isRecord(raw) || typeof raw.acceptedVersion !== 'number') return null;
return {
acceptedVersion: raw.acceptedVersion,
acceptedAt: typeof raw.acceptedAt === 'string' ? raw.acceptedAt : '',
};
return coerceLegal(stored[LEGAL_KEY]);
} catch {
return null;
}
@@ -106,3 +112,44 @@ export async function writeLegal(acceptedVersion: number, nowIso: string): Promi
[LEGAL_KEY]: { acceptedVersion, acceptedAt: nowIso } satisfies LegalAcceptance,
});
}
/** What changed, already coerced. A key absent from the event stays absent. */
export interface StorageChange {
settings?: Settings;
legal?: LegalAcceptance | null;
}
/**
* Watch for writes made by another extension context — a second Manager tab.
*
* The event fires in *every* context including the one that wrote, so the
* caller has to decide what is an echo of its own write; this layer only
* decodes and hands over. Values are coerced through the same functions the
* read path uses, because a second tab is not a more trustworthy source than
* disk — it is the same disk.
*
* @returns an unsubscribe function.
*/
export function subscribeStorage(handler: (change: StorageChange) => void): () => void {
const onChanged = (changes: Record<string, { newValue?: unknown }>, areaName: string): void => {
// Everything this extension stores is in `local`; `sync` is never used
// (docs/09 §1.3) and a write there is not ours to react to.
if (areaName !== 'local') return;
try {
const change: StorageChange = {};
if (SETTINGS_KEY in changes)
change.settings = coerceSettings(changes[SETTINGS_KEY]?.newValue);
if (LEGAL_KEY in changes) change.legal = coerceLegal(changes[LEGAL_KEY]?.newValue);
if (change.settings !== undefined || 'legal' in change) handler(change);
} catch {
// A throw inside a chrome.* listener surfaces as an extension error in
// chrome://extensions, which the QA pass treats as a failure. Nothing
// here is worth that: the next read will pick up the same value.
}
};
browser.storage.onChanged.addListener(onChanged);
return () => {
browser.storage.onChanged.removeListener(onChanged);
};
}
+18 -6
View File
@@ -12,7 +12,7 @@
*/
import type { BookmarkNode, ImportPlan } from '../core/model';
import { create as createNode, type LiveNode } from './bookmarks';
import { BmAborted } from './errors';
import { BmAborted, BmPartialWrite } from './errors';
/** Emitted every PROGRESS_EVERY creates and once at the end. */
export interface WriteProgress {
@@ -55,6 +55,9 @@ export interface WriteResult {
*
* @throws {BmAborted} when the signal fires — carrying the exact number of
* nodes already created, so the report can tell the user what landed.
* @throws {BmPartialWrite} when a create rejects, carrying the same count. A
* rejection half-way through leaves real bookmarks in the user's tree; a bare
* "the browser refused" gives them no way to know how many.
*/
export async function writeTree(
plan: ImportPlan,
@@ -81,11 +84,20 @@ export async function writeTree(
for (const node of nodes) {
if (signal?.aborted === true) throw new BmAborted(done);
const created = await create({
parentId,
title: node.title,
...(node.url !== undefined && { url: node.url }),
});
let created: LiveNode;
try {
created = await create({
parentId,
title: node.title,
...(node.url !== undefined && { url: node.url }),
});
} catch (cause) {
// Order matters. The abort check above throws from inside this same
// loop, and wrapping it would relabel every user cancellation as a
// failure — making `cancelled` unreachable and its copy dead.
if (cause instanceof BmAborted) throw cause;
throw new BmPartialWrite('writing', done, cause);
}
done++;
sinceYield++;
+129
View File
@@ -0,0 +1,129 @@
<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, STORE_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>
<li><a href={STORE_URL} target="_blank" rel="noopener noreferrer">{t('about.store')} ↗</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)}
+161 -274
View File
@@ -1,19 +1,27 @@
<script lang="ts">
import { onMount } from 'svelte';
import { browser } from 'wxt/browser';
import { onMount, untrack } from 'svelte';
import {
create,
getRootChildren,
type LiveNode,
move,
remove,
removeTree,
subscribe,
update,
} from '../browser/bookmarks';
import { BmBrowserError } from '../browser/errors';
import { copyToClipboard } from '../browser/clipboard';
import { type DescribedError, describeError } from '../browser/describe-error';
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,
@@ -22,29 +30,41 @@
moveNode,
removeNode,
} from '../edit/patch-tree';
import { deleteEach } from '../edit/bulk-delete';
import { canMoveInto, moveTargets } from '../edit/move-target';
import {
collapseSearchExpansion,
forgetSearchExpansion,
mergeSearchExpansion,
} from '../edit/search-expansion';
import { resolveKey, visibleRows } from '../edit/tree-keyboard';
import { t } from '../i18n/index.svelte';
import Button from './Button.svelte';
import Callout from './Callout.svelte';
import { num, t } from '../i18n/index.svelte';
import { pushToast } from '../stores/toast.svelte';
import ErrorCallout from './ErrorCallout.svelte';
import ConfirmDialog from './ConfirmDialog.svelte';
import DuplicatePanel from './DuplicatePanel.svelte';
import TreeRow from './TreeRow.svelte';
import EditToolbar from './EditToolbar.svelte';
import MoveToDialog from './MoveToDialog.svelte';
import TreeList from './TreeList.svelte';
let roots = $state<EditNode[]>([]);
let expanded = $state<Set<string>>(new Set());
let expanded = $state<ReadonlySet<string>>(new Set());
let focusedId = $state<string | undefined>();
let renamingId = $state<string | undefined>();
let query = $state('');
let debounced = $state('');
let showDuplicates = $state(false);
let loadError = $state<string | undefined>();
let loadError = $state<DescribedError | undefined>();
let pendingDelete = $state<EditNode | undefined>();
let pendingKeepFirst = $state(false);
let draggingId = $state<string | undefined>();
let movingNode = $state<EditNode | undefined>();
/** Per-operation failure, shown ABOVE the tree rather than replacing it. */
let actionError = $state<{ message: string; detail: string | undefined } | undefined>();
let actionError = $state<
(DescribedError & { partial?: { done: number; total: number } }) | undefined
>();
/** Folders the search opened, so clearing the search can close them again. */
let searchOpened = $state<ReadonlySet<string>>(new Set());
let searchInput = $state<HTMLInputElement | undefined>();
let treeEl = $state<HTMLElement | undefined>();
@@ -78,23 +98,17 @@
};
});
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 {
roots = (await getRootChildren()).map(toEditNode);
expanded = new Set(roots.map((root) => root.id));
} catch (err) {
loadError = err instanceof BmBrowserError ? err.detail : t('errors.UNKNOWN');
// Was `err.detail` alone: a raw English Chrome string as the entire
// screen, in every language (docs/02 §7).
loadError = describeError(err);
}
}
@@ -112,35 +126,54 @@
// Search-opened ancestors are merged INTO `expanded` rather than unioned at
// render time. Reading from a union that toggle() cannot write to made the
// disclosure button and ArrowLeft dead keys on every search-expanded folder.
//
// The merge is remembered so it can be undone: a one-character query expands
// most of a large tree, and clearing the box used to render every one of
// those rows at once, in a single synchronous pass, with no virtualization.
$effect(() => {
if (search.expand.size === 0) return;
const missing = [...search.expand].filter((id) => !expanded.has(id));
if (missing.length > 0) expanded = new Set([...expanded, ...missing]);
// Depend on the SEARCH only. `expanded` and `searchOpened` are read and
// written here, so tracking them makes the effect its own dependency: every
// write re-invalidates it, and it re-runs against a `search.expand` that has
// not changed. Collapsing a search-opened folder then immediately re-opened
// it — the disclosure arrow looked broken, which is the same class of defect
// the merge-into-`expanded` design was introduced to fix.
const wanted = search.expand;
const active = filtering;
untrack(() => {
if (!active) {
if (searchOpened.size === 0) return;
expanded = collapseSearchExpansion(expanded, searchOpened);
searchOpened = new Set();
return;
}
const merged = mergeSearchExpansion(expanded, wanted, searchOpened);
if (merged.expanded === expanded) return;
expanded = merged.expanded;
searchOpened = merged.opened;
});
});
const rows = $derived(visibleRows(roots, expanded, filtering ? search.visible : undefined));
const duplicateGroups = $derived(
findDuplicateGroups(flatten(roots).filter((node) => node.url !== undefined)),
const partialNote = $derived(
actionError?.partial === undefined
? undefined
: t('edit.keepFirstPartial', {
done: num(actionError.partial.done),
total: num(actionError.partial.total),
}),
);
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);
}
// `isEditable` matters as much as the url check: without it, duplicates
// inside a policy-managed subtree were offered for bulk deletion, and the
// browser rejects every one of them. The single-delete path has always
// filtered; docs/15 makes it normative that unmodifiable nodes offer no
// destructive affordance at all.
const duplicateGroups = $derived(
findDuplicateGroups(
flattenTree(roots).filter((node) => node.url !== undefined && isEditable(node)),
),
);
/**
* Run a mutation, and on failure resync from the browser — the only source of
@@ -152,10 +185,7 @@
try {
await run();
} catch (err) {
actionError =
err instanceof BmBrowserError
? { message: t('errors.BROWSER'), detail: err.detail }
: { message: t('errors.UNKNOWN'), detail: err instanceof Error ? err.message : undefined };
actionError = describeError(err);
await load();
}
}
@@ -165,6 +195,9 @@
if (next.has(id)) next.delete(id);
else next.add(id);
expanded = next;
// Touching a folder makes it the user's, so clearing the search must not
// close it again.
searchOpened = forgetSearchExpansion(searchOpened, id);
}
function onKeydown(event: KeyboardEvent): void {
@@ -207,19 +240,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 +282,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,13 +299,22 @@
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));
await guardEdit(async () => {
for (const id of doomed) {
roots = removeNode(roots, id);
await remove(id);
}
const doomed = extraCopyIds(duplicateGroups);
actionError = undefined;
const outcome = await deleteEach(doomed, remove, (id) => {
roots = removeNode(roots, id);
});
if (outcome.error === undefined) return;
// The dialog promised an exact number. Saying only "the browser refused"
// after deleting some of them leaves the user unable to tell how many
// copies are left, on an action that cannot be undone.
actionError = {
...describeError(outcome.error),
partial: { done: outcome.deleted, total: outcome.total },
};
await load();
}
/** Shared by the drag path and the keyboard "Move to…" path. */
@@ -319,90 +354,54 @@
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>
<ErrorCallout messageKey={loadError.messageKey} detail={loadError.detail} />
{: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">
<Callout tone="danger">{actionError.message}</Callout>
{#if actionError.detail !== undefined}
<pre>{actionError.detail}</pre>
{/if}
</div>
<ErrorCallout
messageKey={actionError.messageKey}
detail={actionError.detail}
note={partialNote}
/>
{/if}
<div class="split" class:with-panel={showDuplicates}>
<!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
<ul
bind:this={treeEl}
class="tree"
role="tree"
aria-label={t('common.edit')}
tabindex="0"
aria-activedescendant={focusedId === undefined ? undefined : `node-${focusedId}`}
<TreeList
bind:element={treeEl}
{rows}
{focusedId}
{renamingId}
{filtering}
{draggingId}
matched={search.matched}
editable={isEditable}
canDropInto={(id) => draggingId !== undefined && canMoveInto(roots, draggingId, id)}
onkeydown={onKeydown}
>
{#each rows as row (row.node.id)}
<li
id="node-{row.node.id}"
data-node-id={row.node.id}
role="treeitem"
aria-level={row.depth}
aria-expanded={row.expandable ? row.expanded : undefined}
aria-selected={focusedId === row.node.id}
>
<TreeRow
node={row.node}
depth={row.depth}
expandable={row.expandable}
expanded={row.expanded}
focused={focusedId === row.node.id}
matched={search.matched.has(row.node.id)}
renaming={renamingId === row.node.id}
ontoggle={() => toggle(row.node.id)}
onfocus={() => (focusedId = row.node.id)}
onstartRename={() => (renamingId = row.node.id)}
onrename={(title) => void commitRename(row.node.id, title)}
oncancelRename={() => (renamingId = undefined)}
ondelete={() => (pendingDelete = row.node)}
onopen={() => void openUrl(row.node.url ?? '')}
onmoveTo={() => (movingNode = row.node)}
ondragstart={() => (draggingId = row.node.id)}
ondropinto={() => onDrop(row.node.id)}
dropTarget={draggingId !== undefined &&
canMoveInto(roots, draggingId, row.node.id)}
draggable={isEditable(row.node)}
editable={isEditable(row.node)}
/>
</li>
{/each}
{#if rows.length === 0}
<li class="empty">{filtering ? t('edit.noMatches') : t('edit.empty')}</li>
{/if}
</ul>
ontoggle={toggle}
onfocusRow={(id) => (focusedId = id)}
onstartRename={(id) => (renamingId = id)}
onrename={(id, title) => void commitRename(id, title)}
oncancelRename={() => (renamingId = undefined)}
ondelete={(node) => (pendingDelete = node)}
onopen={(node) => void openUrl(node.url ?? "")}
oncopyUrl={(node) => void copyUrl(node.url ?? "")}
onmoveTo={(node) => (movingNode = node)}
ondragstart={(id) => (draggingId = id)}
ondropinto={(id) => onDrop(id)}
/>
{#if showDuplicates}
<DuplicatePanel
@@ -416,26 +415,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 +432,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 +445,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 +454,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;
@@ -500,90 +471,6 @@
}
}
.tree {
list-style: none;
margin: 0;
padding: 0;
font-size: var(--fs-1);
max-height: 560px;
overflow: auto;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: var(--sp-2);
}
.tree:focus-visible {
outline: 2px solid var(--accent);
}
.action-error {
margin-bottom: var(--sp-3);
}
.action-error pre {
margin: var(--sp-2) 0 0;
font-size: var(--fs-0);
background: var(--bg-raised);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: var(--sp-2);
overflow: auto;
user-select: all;
}
.empty {
color: var(--fg-muted);
padding: var(--sp-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>
+66
View File
@@ -0,0 +1,66 @@
<script lang="ts">
/**
* A failure, shown the way docs/02 §7 requires: a localized sentence, and the
* raw browser string in a separate, copyable block.
*
* One component owns this because there is one specific way to get it wrong
* and it has been got wrong three times. Writing `detail ?? t(key)` looks
* like a sensible fallback, but the raw string is almost always present — so
* the translation becomes dead code and a Vietnamese or Japanese user sees an
* untranslated Chrome message as the entire explanation. LegalGate carries a
* comment recording that exact defect; #edit and #export still had it.
*
* The detail is `user-select: all` so a reporter can grab it in one click for
* an issue — it is the only part worth pasting.
*/
import { t } from '../i18n/index.svelte';
import Callout from './Callout.svelte';
interface Props {
/** Dotted i18n path. Never a resolved string. */
messageKey: string;
/** Raw, untranslated technical text. Omitted when there is none. */
detail?: string | undefined;
/**
* An already-localized sentence adding what the failure left behind — how
* many of a promised batch actually completed, for instance. Resolved by
* the caller because it interpolates counts they hold.
*/
note?: string | undefined;
}
let { messageKey, detail, note }: Props = $props();
</script>
<div class="error">
<Callout tone="danger">{t(messageKey)}</Callout>
{#if note !== undefined}
<p class="note">{note}</p>
{/if}
{#if detail !== undefined}
<pre>{detail}</pre>
{/if}
</div>
<style>
.error {
margin-bottom: var(--sp-3);
}
.note {
margin: var(--sp-2) 0 0;
color: var(--fg-muted);
font-size: var(--fs-1);
}
pre {
margin: var(--sp-2) 0 0;
font-size: var(--fs-0);
background: var(--bg-raised);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: var(--sp-2);
overflow: auto;
user-select: all;
}
</style>
+35 -24
View File
@@ -1,23 +1,29 @@
<script lang="ts">
import { onMount } from 'svelte';
import { getRootChildren, type LiveNode } from '../browser/bookmarks';
import { BmBrowserError } from '../browser/errors';
import { type DescribedError, describeError } from '../browser/describe-error';
import type { ExportFormat } from '../browser/storage';
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 ErrorCallout from './ErrorCallout.svelte';
import FolderPickTree from './FolderPickTree.svelte';
import FormatSelect from './FormatSelect.svelte';
let roots = $state<LiveNode[]>([]);
let selection = $state<ReadonlySet<string> | undefined>(undefined);
let format = $state<ExportFormat>('netscape-html');
let loadError = $state<string | undefined>();
let toast = $state<string | undefined>();
let loadError = $state<DescribedError | undefined>();
let csvDelimiter = $state<CsvDelimiter>(',');
let markdownStyle = $state<MarkdownStyle>('nested');
@@ -34,7 +40,9 @@
csvDelimiter = settings.csvDelimiter;
markdownStyle = settings.markdownStyle;
} catch (err) {
loadError = err instanceof BmBrowserError ? err.detail : t('errors.UNKNOWN');
// Was `err.detail` alone — a raw English Chrome string as the entire
// screen, in all three languages (docs/02 §7).
loadError = describeError(err);
}
}
@@ -55,16 +63,20 @@
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. The message is the localized
// sentence — a toast has no room for a detail block, which is the same
// reasoning the header's save-failure toast records.
pushToast(t(describeError(err).messageKey), 'danger');
}
})();
}
</script>
{#if loadError !== undefined}
<Callout tone="danger">{loadError}</Callout>
<ErrorCallout messageKey={loadError.messageKey} detail={loadError.detail} />
{:else}
<div class="split">
<section aria-label={t('export.scope')}>
@@ -83,10 +95,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 +112,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 +129,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 +172,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'}
+68 -51
View File
@@ -1,11 +1,13 @@
<script lang="ts">
import { describeError } from '../browser/describe-error';
import { timestampSuffix } from '../browser/download';
import { BmAborted, BmBackupError, BmBrowserError } from '../browser/errors';
import { BmParseError } from '../core/model';
import { t } from '../i18n/index.svelte';
import { BmAborted } from '../browser/errors';
import { num, t } from '../i18n/index.svelte';
import { prepareImport, runImport } from '../import/run-import';
import { getSettings } from '../stores/settings.svelte';
import {
answerAttestation,
awaitAttestation,
beginWrite,
cancelWrite,
getImportOptions,
@@ -20,6 +22,7 @@
import Button from './Button.svelte';
import Callout from './Callout.svelte';
import DropZone from './DropZone.svelte';
import ErrorCallout from './ErrorCallout.svelte';
import ImportOptions from './ImportOptions.svelte';
import ProgressBar from './ProgressBar.svelte';
import StatsCard from './StatsCard.svelte';
@@ -33,27 +36,6 @@
const session = $derived(getImportState());
const options = $derived(getImportOptions());
/** Resolver for the fallback-backup attestation dialog. */
let attestResolve: ((confirmed: boolean) => void) | undefined;
function answerAttest(confirmed: boolean): void {
attestResolve?.(confirmed);
attestResolve = undefined;
}
function describeError(err: unknown): { message: string; detail: string | undefined } {
if (err instanceof BmParseError) {
return { message: t(`errors.${err.code}`), detail: err.detail };
}
if (err instanceof BmBackupError) {
return { message: t(`errors.${err.code}`), detail: err.message };
}
if (err instanceof BmBrowserError) {
return { message: t('errors.BROWSER'), detail: err.detail };
}
return { message: t('errors.UNKNOWN'), detail: err instanceof Error ? err.message : undefined };
}
async function onFile(file: File): Promise<void> {
setImportState({ kind: 'validating', filename: file.name });
try {
@@ -78,6 +60,8 @@
const signal = beginWrite();
const now = new Date();
const backupFilename = `bookmarkmagic-backup-${timestampSuffix(now)}.json`;
/** Set once the backup is on disk. Nothing may point at the file before. */
let backupProven = false;
// runImport opens the save picker as its first statement, so the transient
// activation from this click still holds when the dialog appears.
@@ -102,27 +86,54 @@
// Backup proven; deletion starts now. No Cancel is offered here — the
// button used to stay live through the whole delete, letting a user
// cancel and be told "0 items created" after their tree was wiped.
//
// This callback is also the ONLY signal that the backup exists: it runs
// immediately after `proveBackup` returned, and nothing else does.
onClearing: () => {
backupProven = true;
setImportState({ kind: 'clearing', filename });
},
confirmUnprovenBackup: () => {
setImportState({ kind: 'attesting', filename, backupFilename });
return new Promise<boolean>((resolve) => {
attestResolve = resolve;
});
return awaitAttestation();
},
});
setImportState({ kind: 'done', filename, created: outcome.created, plan: outcome.plan });
} catch (err) {
if (err instanceof BmAborted) {
setImportState({ kind: 'cancelled', filename, created: err.done });
setImportState({
kind: 'cancelled',
filename,
created: err.done,
// A cancel AFTER the clear is not "nothing happened": the tree is
// gone and only `created` of it has been rebuilt. Saying "N items
// created" alone reads as a harmless no-op on an empty browser.
...(backupProven ? { backupFilename } : {}),
});
return;
}
setImportState({ kind: 'error', filename, ...describeError(err) });
setImportState({
kind: 'error',
filename,
...describeError(err),
// `backupProven`, not "mode was replace and this is not a BmBackupError".
// `runImport` resolves the roots BEFORE proving the backup, so a failure
// there — a policy-managed profile raising NO_WRITABLE_ROOTS, say —
// reaches this catch with no file on disk. Telling a frightened user to
// restore a backup that was never written is worse than saying nothing.
...(backupProven ? { backupFilename } : {}),
});
}
}
/** 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 +147,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">
@@ -148,11 +159,12 @@
duplicates={session.duplicates}
onchange={(patch) => setImportOptions(patch)}
/>
<p class="muted">{t('import.dateNotice')}</p>
<Button
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>
@@ -163,8 +175,10 @@
thing standing between the user and an unbacked-up deletion. -->
<Callout tone="danger">{t('import.attest', { name: session.backupFilename })}</Callout>
<div class="actions">
<Button variant="danger" onclick={() => answerAttest(true)}>{t('import.attestConfirm')}</Button>
<Button onclick={() => answerAttest(false)}>{t('common.cancel')}</Button>
<Button variant="danger" onclick={() => answerAttestation(true)}>
{t('import.attestConfirm')}
</Button>
<Button onclick={() => answerAttestation(false)}>{t('common.cancel')}</Button>
</div>
{:else if session.kind === 'clearing'}
<Callout tone="danger">{t('import.clearing')}</Callout>
@@ -176,20 +190,21 @@
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>
<p class="muted">{t('import.dateNotice')}</p>
<div class="actions">
<Button variant="primary" onclick={() => navigate('edit')}>{t('import.openEdit')}</Button>
<Button
@@ -197,14 +212,25 @@
>
</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>
{#if session.backupFilename !== undefined}
<Callout tone="danger">{t('import.cancelledAfterClear')}</Callout>
<p class="muted">{t('import.backupHint', { name: session.backupFilename })}</p>
{/if}
<p class="muted">{t('import.dateNotice')}</p>
<Button
onclick={resetImport}>{t('import.another')}</Button
>
{:else if session.kind === 'error'}
<Callout tone="danger">{session.message}</Callout>
{#if session.detail !== undefined}
<pre class="detail">{session.detail}</pre>
<ErrorCallout messageKey={session.messageKey} detail={session.detail} />
{#if session.created !== undefined && session.created > 0}
<p class="muted">{t('import.partialCreated', { created: num(session.created) })}</p>
{/if}
{#if session.removed !== undefined && session.removed > 0}
<Callout tone="danger">{t('import.partialCleared', { removed: num(session.removed) })}</Callout>
{/if}
{#if session.backupFilename !== undefined}
<p class="muted">{t('import.backupHint', { name: session.backupFilename })}</p>
{/if}
<Button
onclick={resetImport}>{t('import.another')}</Button
@@ -256,13 +282,4 @@
margin-top: var(--sp-3);
}
.detail {
font-size: var(--fs-0);
background: var(--bg-raised);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: var(--sp-2);
overflow: auto;
user-select: all;
}
</style>
@@ -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>
+142
View File
@@ -0,0 +1,142 @@
<script lang="ts">
/**
* The `role="tree"` container and its rows — docs/06 §3.3.
*
* Split out of `EditTab` so the ARIA structure lives in one place rather than
* inside a component that also owns loading, searching, mutation and five
* dialogs. The WAI-ARIA tree pattern is exacting — roving focus expressed
* through `aria-activedescendant`, `aria-level` starting at 1, `aria-expanded`
* present only on expandable rows — and it is easier to keep right when it is
* not surrounded by unrelated state.
*
* The keydown handler lives on this `<ul>`, not on a wrapper: a keydown
* handler on a non-focusable container never fires, and svelte-check flags it.
*/
import type { EditNode } from '../edit/patch-tree';
import type { VisibleRow } from '../edit/tree-keyboard';
import { t } from '../i18n/index.svelte';
import TreeRow from './TreeRow.svelte';
interface Props {
rows: readonly VisibleRow[];
focusedId: string | undefined;
renamingId: string | undefined;
/** Ids matching the current search, highlighted rather than filtered. */
matched: ReadonlySet<string>;
/** True while a search is narrowing the tree — picks the empty message. */
filtering: boolean;
draggingId: string | undefined;
editable: (node: EditNode) => boolean;
canDropInto: (id: string) => boolean;
element?: HTMLElement | undefined;
onkeydown: (event: KeyboardEvent) => void;
ontoggle: (id: string) => void;
onfocusRow: (id: string) => void;
onstartRename: (id: string) => void;
onrename: (id: string, title: string) => void;
oncancelRename: () => void;
ondelete: (node: EditNode) => void;
onopen: (node: EditNode) => void;
oncopyUrl: (node: EditNode) => void;
onmoveTo: (node: EditNode) => void;
ondragstart: (id: string) => void;
ondropinto: (id: string) => void;
}
let {
rows,
focusedId,
renamingId,
matched,
filtering,
draggingId,
editable,
canDropInto,
element = $bindable(),
onkeydown,
ontoggle,
onfocusRow,
onstartRename,
onrename,
oncancelRename,
ondelete,
onopen,
oncopyUrl,
onmoveTo,
ondragstart,
ondropinto,
}: Props = $props();
</script>
<!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
<ul
bind:this={element}
class="tree"
role="tree"
aria-label={t('common.edit')}
tabindex="0"
aria-activedescendant={focusedId === undefined ? undefined : `node-${focusedId}`}
{onkeydown}
>
{#each rows as row (row.node.id)}
<li
id="node-{row.node.id}"
data-node-id={row.node.id}
role="treeitem"
aria-level={row.depth}
aria-expanded={row.expandable ? row.expanded : undefined}
aria-selected={focusedId === row.node.id}
>
<TreeRow
node={row.node}
depth={row.depth}
expandable={row.expandable}
expanded={row.expanded}
focused={focusedId === row.node.id}
matched={matched.has(row.node.id)}
renaming={renamingId === row.node.id}
ontoggle={() => ontoggle(row.node.id)}
onfocus={() => onfocusRow(row.node.id)}
onstartRename={() => onstartRename(row.node.id)}
onrename={(title) => onrename(row.node.id, title)}
{oncancelRename}
ondelete={() => ondelete(row.node)}
onopen={() => onopen(row.node)}
oncopyUrl={() => oncopyUrl(row.node)}
onmoveTo={() => onmoveTo(row.node)}
ondragstart={() => ondragstart(row.node.id)}
ondropinto={() => ondropinto(row.node.id)}
dropTarget={draggingId !== undefined && canDropInto(row.node.id)}
draggable={editable(row.node)}
editable={editable(row.node)}
/>
</li>
{/each}
{#if rows.length === 0}
<li class="empty">{filtering ? t('edit.noMatches') : t('edit.empty')}</li>
{/if}
</ul>
<style>
.tree {
list-style: none;
margin: 0;
padding: var(--sp-2);
font-size: var(--fs-1);
max-height: 560px;
overflow: auto;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
}
.tree:focus-visible {
outline: 2px solid var(--accent);
}
.empty {
color: var(--fg-muted);
padding: var(--sp-4);
text-align: center;
}
</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>
+15 -1
View File
@@ -77,6 +77,20 @@ function writeFlat(roots: readonly BookmarkNode[], out: string[]): void {
}
}
/**
* Drop trailing line feeds in one backward pass.
*
* Replaces `.replace(/\n+$/, '')`, which backtracks: for every newline in a
* long run that is NOT at the end (a title holding thousands of them, say), the
* engine re-scans the rest of the run before failing at `$` — quadratic in the
* run length (SonarCloud S8786).
*/
function trimTrailingNewlines(text: string): string {
let end = text.length;
while (end > 0 && text.charCodeAt(end - 1) === 0x0a) end--;
return text.slice(0, end);
}
/** Serialize a tree to Markdown. */
export function serializeMarkdown(
roots: readonly BookmarkNode[],
@@ -85,5 +99,5 @@ export function serializeMarkdown(
const out: string[] = [`# Bookmarks — ${options.date}`, ''];
if ((options.style ?? 'nested') === 'flat') writeFlat(roots, out);
else writeNested(roots, 0, out);
return `${out.join('\n').replace(/\n+$/, '')}\n`;
return `${trimTrailingNewlines(out.join('\n'))}\n`;
}
+47
View File
@@ -0,0 +1,47 @@
/**
* Delete many nodes, one awaited call at a time, and report what happened —
* docs/03 §3.
*
* Purpose: give the "keep the first of each" bulk delete an outcome the caller
* cannot forget to handle.
* Inputs: the ids to remove, an injected remove, and a per-success callback for
* the optimistic local update.
* Guarantees: **never throws.** It stops at the first rejection and returns how
* far it got.
*
* Not throwing is the point. This is the project's recurring defect shape —
* mutate local state optimistically, await a `chrome.*` call that can reject,
* never handle the rejection — and it lived here in its purest form: the loop
* removed each node locally, awaited the browser, and on the first rejection
* abandoned the rest, leaving the user with a partial delete measured against a
* confirmation dialog that had promised an exact number.
*/
export interface BulkDeleteOutcome {
/** How many the browser actually accepted. */
deleted: number;
/** How many were asked for. */
total: number;
/** The rejection that stopped it, if one did. */
error?: unknown;
}
export async function deleteEach(
ids: readonly string[],
remove: (id: string) => Promise<void>,
onDeleted: (id: string) => void,
): Promise<BulkDeleteOutcome> {
let deleted = 0;
for (const id of ids) {
try {
await remove(id);
} catch (error) {
return { deleted, total: ids.length, error };
}
// Only after the browser has confirmed it. Updating first would leave the
// tree disagreeing with the browser for every id after a failure.
onDeleted(id);
deleted++;
}
return { deleted, total: ids.length };
}
+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));
}
+75
View File
@@ -0,0 +1,75 @@
/**
* Track which folders a *search* opened, separately from the ones the user
* opened — docs/03 §3.
*
* Purpose: let the tree collapse back when the search box is cleared, without
* closing anything the user opened by hand.
* Inputs: the current expanded set, the ids a search wants open, and the ids
* this module opened last time.
* Guarantees: pure, and never returns a new Set when nothing changed, so the
* `$effect` driving it does not thrash.
*
* Why the search merges into `expanded` at all: a render-time union of the two
* sets made the disclosure button and ArrowLeft dead on every search-expanded
* folder, because `toggle()` had nothing it could write to. The merge is
* deliberate; what was missing was the un-merge, so one character typed into
* the search box permanently expanded most of a large tree — and clearing the
* box then rendered every one of those rows at once, with no virtualization.
*/
export interface MergeResult {
expanded: ReadonlySet<string>;
/** Ids this module opened, to be closed again when the search clears. */
opened: ReadonlySet<string>;
}
/**
* Open everything the search needs, remembering what was not already open.
*
* @param expanded ids currently expanded
* @param wanted ids the search needs expanded
* @param opened ids a previous merge opened and has not yet collapsed
*/
export function mergeSearchExpansion(
expanded: ReadonlySet<string>,
wanted: ReadonlySet<string>,
opened: ReadonlySet<string>,
): MergeResult {
const missing = [...wanted].filter((id) => !expanded.has(id));
// Identity is preserved when there is nothing to do — the caller stores these
// in `$state`, and reassigning an equal Set would re-run every dependent.
if (missing.length === 0) return { expanded, opened };
return {
expanded: new Set([...expanded, ...missing]),
opened: new Set([...opened, ...missing]),
};
}
/**
* Close only what the search opened.
*
* A folder the user expanded themselves stays open even if the search also
* needed it — `forget` removes it from the search-owned set the moment they
* touch it, so ownership is decided at the point of interaction rather than
* guessed at collapse time.
*/
export function collapseSearchExpansion(
expanded: ReadonlySet<string>,
opened: ReadonlySet<string>,
): ReadonlySet<string> {
if (opened.size === 0) return expanded;
const next = new Set(expanded);
for (const id of opened) next.delete(id);
return next;
}
/** The user toggled this folder, so the search no longer owns it. */
export function forgetSearchExpansion(
opened: ReadonlySet<string>,
id: string,
): ReadonlySet<string> {
if (!opened.has(id)) return opened;
const next = new Set(opened);
next.delete(id);
return next;
}
Loaded 100 of 149 files, more files were not shown because too many files have changed in this diff. Show more