Compare commits
14
Commits
main
...
ad96b4f0f9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ad96b4f0f9 | ||
|
|
253e7782d0 | ||
|
|
cf0435e7b7 | ||
|
|
6c4c307a25 | ||
|
|
a2c5dc947c | ||
|
|
b1698aca0b | ||
|
|
8882be03cb | ||
|
|
121a5a6957 | ||
|
|
36c39f3185 | ||
|
|
5ce1abe744 | ||
|
|
b210f55e6e | ||
|
|
e0b782a710 | ||
|
|
a232eee253 | ||
|
|
8673173bee |
No files matched your search
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,116 @@
|
||||
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)
|
||||
- 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
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -1,10 +1,16 @@
|
||||
# Caller stub — docs/12 §2.4.
|
||||
#
|
||||
# The reusable already filters to `conclusion == 'failure'` on the default
|
||||
# branch, so this caller needs no `if:`.
|
||||
# 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.
|
||||
#
|
||||
# ⚠️ It declares `DISCORD_CI_WEBHOOK` as `required: true`, so this workflow
|
||||
# fails until that repo secret exists (docs/12 §5).
|
||||
# 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:
|
||||
@@ -18,6 +24,17 @@ permissions:
|
||||
|
||||
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
|
||||
|
||||
@@ -53,12 +53,24 @@ jobs:
|
||||
working-directory: .output
|
||||
run: sha256sum *-chrome.zip > 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 CWS publish below, once CWS_AUTOPUBLISH is on — used to strand the
|
||||
# tag: re-running the workflow could not get past this line, and the only
|
||||
# recovery was deleting the Release and the tag by hand (docs/13 §7).
|
||||
- name: GitHub Release
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
gh release create "$GITHUB_REF_NAME" \
|
||||
.output/*-chrome.zip .output/SHA256SUMS.txt --generate-notes
|
||||
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" \
|
||||
.output/*-chrome.zip .output/SHA256SUMS.txt --clobber
|
||||
else
|
||||
gh release create "$GITHUB_REF_NAME" \
|
||||
.output/*-chrome.zip .output/SHA256SUMS.txt --generate-notes
|
||||
fi
|
||||
|
||||
# v1.0.x is published by hand (docs/12 §3) — first store reviews often
|
||||
# ask questions and want a human in the loop. Flipping the repo variable
|
||||
@@ -78,13 +90,22 @@ jobs:
|
||||
# would silently never fire.
|
||||
announce:
|
||||
needs: release
|
||||
# A Discord notification is not part of the release. The reusable exits 1
|
||||
# on "No webhooks configured" when DISCORD_RELEASES_WEBHOOK and
|
||||
# A Discord notification is not part of the release. The reusable exits 1 on
|
||||
# "No webhooks configured" when DISCORD_RELEASES_WEBHOOK and
|
||||
# DISCORD_REPO_WEBHOOK are both unset (docs/12 §5 lists them as optional),
|
||||
# which turned the v1.0.0 run red even though the Release, the zip and
|
||||
# SHA256SUMS.txt had all published correctly. A red run on a good release
|
||||
# is worse than a missing announcement: it trains you to ignore the colour.
|
||||
continue-on-error: true
|
||||
# SHA256SUMS.txt had all published correctly. A red run on a good release is
|
||||
# worse than a missing announcement: it trains you to ignore the colour.
|
||||
#
|
||||
# ⚠️ This used to say `continue-on-error: true`, which GitHub REJECTS on a
|
||||
# job that calls a reusable workflow — "Property continue-on-error is not
|
||||
# allowed". The whole file is then invalid and the run is a startup_failure
|
||||
# with zero jobs and no log, exactly like the `contents: write` mistake in
|
||||
# 2c8fba9. It was never caught because that fix landed after the v1.0.0 tag
|
||||
# and no tag has been pushed since, so the first v1.0.1 tag would have been
|
||||
# its first execution. Gate on a repo VARIABLE instead — allowed in `if:`,
|
||||
# unlike a secret, and the same idiom as CWS_AUTOPUBLISH above.
|
||||
if: vars.DISCORD_ANNOUNCE == 'true'
|
||||
uses: poli0981/.github/.github/workflows/announce-release.yml@main
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
+46
-2
@@ -13,9 +13,52 @@ breaking format or schema changes (a BM JSON version bump).
|
||||
|
||||
Nothing yet.
|
||||
|
||||
## [1.0.1] — 2026-08-03
|
||||
|
||||
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.
|
||||
First public release. Approved by the Chrome Web Store and available to install
|
||||
from 2026-08-03.
|
||||
|
||||
### Added
|
||||
|
||||
@@ -44,5 +87,6 @@ First public release.
|
||||
- Parsing is bounded: 25 MB per file, 100 000 nodes, 200 levels of nesting.
|
||||
- No network access of any kind at runtime, enforced by a grep gate in CI.
|
||||
|
||||
[Unreleased]: https://github.com/poli0981/bookmarkmagic/compare/v1.0.0...HEAD
|
||||
[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
|
||||
@@ -1,9 +1,25 @@
|
||||
# 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
|
||||
>
|
||||
> **v1.0.0 is published on the Chrome Web Store and has real users** (submitted
|
||||
> 2026-07-26, live by 2026-08-03). Phases 0–5 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 +53,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)
|
||||
|
||||
@@ -88,20 +108,50 @@ performance budgets docs/11 §6, CI workflows per docs/12 §2 (explicit
|
||||
`browser-extension-*` family), CHANGELOG, README (badges, screenshots ⚠,
|
||||
install, privacy summary, donate), full manual QA (docs/11 §5), `wxt zip`
|
||||
clean-install test. Also carried in from the Phase 4 review:
|
||||
- point About's "Changelog" link at `CHANGELOG.md` once it exists
|
||||
(`src/lib/links.ts` currently targets `/releases`);
|
||||
- ✔ `EditTab.svelte` split (589 → 459, under the hard limit). Its script block
|
||||
is still 279 lines against the 150-line guidance; the remainder is the
|
||||
mutation layer, which is genuinely coupled to reactive state and was left
|
||||
whole rather than split behind accessors on the app's delete paths;
|
||||
- ✔ 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 has since
|
||||
grown back to 481** (script block 300) via the Phase 5 review commits — 19
|
||||
lines of headroom against the hard 500. Anything added there now 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.
|
||||
**Exit:** ready for the docs/13 §1 runbook (human performs store submission).
|
||||
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:** `main` tag-ready, docs/11 §5 manual pass green including the
|
||||
**1.0.0 → 1.0.1 upgrade over an existing profile**; the human signs and pushes
|
||||
the tag and performs the store update per docs/13 §1b.
|
||||
|
||||
## 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.
|
||||
@@ -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
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
# 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.
|
||||
|
||||
What it **destroys**: every hostname, path, query value and fragment; every
|
||||
bookmark and folder title; Firefox keywords and tags; favicon data.
|
||||
|
||||
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
|
||||
fixture-driven 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.
|
||||
@@ -88,9 +88,23 @@ code and docs disagree, the docs win. Start with [`CLAUDE.md`](CLAUDE.md), then
|
||||
|
||||
## Contributing
|
||||
|
||||
Bug reports and translation fixes are welcome via
|
||||
[issues](https://github.com/poli0981/bookmarkmagic/issues). A bug report about
|
||||
parsing is far more useful with a sanitized sample of the file that broke.
|
||||
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.
|
||||
|
||||
+37
-3
@@ -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.
|
||||
|
||||
+60
-18
@@ -5,12 +5,18 @@
|
||||
> **Owner:** poli0981 (GitHub) / SkullMute
|
||||
> **Repo:** `poli0981/bookmarkmagic` ✔
|
||||
> **License:** GPL-3.0-or-later
|
||||
> **Status:** **v1.0.0 released and submitted to the Chrome Web Store**
|
||||
> (2026-07-26) — all six build phases complete, awaiting store review. Signed
|
||||
> tag `v1.0.0`, GitHub Release with a checksum-verified zip. Verified working on
|
||||
> real Chrome and Brave. Sequencing lives in `/CLAUDE.md`; what is still open is
|
||||
> in §10 below.
|
||||
> **Doc suite version:** 1.4 (2026-07-26 — v1.0.0 release)
|
||||
> **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.
|
||||
>
|
||||
> 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.5 (2026-08-03 — post-launch reconciliation)
|
||||
|
||||
---
|
||||
|
||||
@@ -87,7 +93,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:
|
||||
@@ -113,6 +123,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) ⚠️
|
||||
|
||||
@@ -123,26 +135,56 @@ Derived identifiers (canonical across docs and code):
|
||||
3. ✔ Icon set (16/32/48/128 px) — the owner adopted the `scripts/gen-icons.mjs`
|
||||
output as final on 2026-07-26, so the generator is the source of truth rather
|
||||
than a placeholder. Regenerate with `npm run icons` after any change.
|
||||
**Still open:** CWS promo images, which the store listing needs but the
|
||||
extension does not.
|
||||
⚠️ **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`).
|
||||
✔ 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 and **submitted
|
||||
2026-07-26 — in review**. Listing copy and the Privacy tab answers come from
|
||||
`13 §3` and `08 §5`. **Still open:** the promo images, and the store URL for
|
||||
the README once the listing is public.
|
||||
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, both
|
||||
optional:** the `DISCORD_*` webhooks — without them the announce job is
|
||||
skipped rather than fatal — and the four `CHROME_*` secrets, which are only
|
||||
needed if `CWS_AUTOPUBLISH` is ever set to `true` for v1.1+.
|
||||
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` against the `overrides` block in
|
||||
`09 §3.1`. Four of those overrides sit under `web-ext-run` and no gate
|
||||
exercises that script. Firefox is a v1.0 non-goal (§7), so this blocks
|
||||
nothing — 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.
|
||||
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. Reading order
|
||||
|
||||
|
||||
+15
-5
@@ -19,12 +19,14 @@
|
||||
|---|---|---|
|
||||
| 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`. |
|
||||
| **WXT** | **^0.21.3** (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** | **~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. |
|
||||
| svelte-check | ^4.7.4 | Type/template authority for `.svelte` files. |
|
||||
| **@types/node** | **^24** (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** (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.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. |
|
||||
@@ -67,7 +69,8 @@
|
||||
"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,8 +80,15 @@
|
||||
`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.
|
||||
|
||||
+15
-3
@@ -165,7 +165,7 @@ 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: **all five** handles from `14 §5` / `.github/FUNDING.yml` — GitHub
|
||||
Sponsors · Ko-fi · Buy Me a Coffee · Patreon · PayPal (platform names are brand
|
||||
@@ -177,8 +177,20 @@ is the version the user **accepted**, from the stored record, not the current
|
||||
a not-yet-accepted state, and a dateless variant for a stored record whose
|
||||
timestamp is missing or unparseable.
|
||||
|
||||
"Changelog" points at the repo's **releases** page until `CHANGELOG.md` exists
|
||||
(Phase 5) — an empty releases page beats a 404 opened from a legal surface.
|
||||
"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/`)
|
||||
|
||||
|
||||
@@ -88,7 +88,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
|
||||
|
||||
@@ -126,7 +126,23 @@ a **minor-version** event at minimum.
|
||||
|
||||
## 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 and title while preserving the structure,
|
||||
encoding, and timestamp magnitudes a parser bug depends on, so the sanitized file
|
||||
still reproduces. 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.
|
||||
+72
-12
@@ -33,18 +33,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)
|
||||
|
||||
@@ -138,12 +151,41 @@ generate-huge.ts # script: emits 100k+1 node file on demand
|
||||
confirms, and a failure says so instead.
|
||||
- [ ] Legal Gate "Close tab" either closes the tab or shows the
|
||||
manual-close message — never appears to do nothing.
|
||||
- [ ] Two Manager tabs open: accepting or changing a setting in one is
|
||||
reflected in the other (or record it as the known limitation it is —
|
||||
`15` decision log).
|
||||
- [ ] 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.
|
||||
@@ -154,7 +196,7 @@ generate-huge.ts # script: emits 100k+1 node file on demand
|
||||
### 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**:
|
||||
folders), timed **under jsdom 29**:
|
||||
|
||||
| Stage | Time |
|
||||
|---|---|
|
||||
@@ -170,7 +212,25 @@ and jsdom's parse5 implementation is roughly an order of magnitude slower than
|
||||
Chrome's native parser. The budget is about the real browser, so the honest
|
||||
reading is "≤ 2.9 s in the slowest environment we can measure from a test".
|
||||
|
||||
The number that decides it has to come from Chrome. Added to the §5 checklist:
|
||||
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.
|
||||
|
||||
- [ ] Generate a 100k-node HTML file, import it in a real browser, and time
|
||||
from drop to preview. Record the number here rather than re-deriving it.
|
||||
**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.
|
||||
+101
-30
@@ -27,6 +27,16 @@ workflows use the `reusable-*` naming family. There is **no
|
||||
|
||||
## 2. Workflows (caller stubs in this repo)
|
||||
|
||||
⚠️ **The YAML below is a copy of live files, and copies drift.** It has already
|
||||
happened twice: a Dependabot bump moved `actions/setup-node` from v6 to v7 in
|
||||
`.github/workflows/` and never touched this doc, and the `check:manifest` step
|
||||
added to the release job in `674ac34` was missing here. Because docs win over
|
||||
code in this project, someone reconciling in the wrong direction would have
|
||||
downgraded a pinned action and deleted a security gate. Both are corrected
|
||||
below (2026-08-03). **When these disagree again, read the workflow file first
|
||||
and fix this doc — that is the one place the docs-win rule inverts, because the
|
||||
running pipeline is the ground truth about itself.**
|
||||
|
||||
### 2.1 `.github/workflows/ci.yml` — every push/PR to `main`
|
||||
|
||||
The local `quality` job exists because the ops reusable workflow performs none
|
||||
@@ -55,7 +65,7 @@ jobs:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/setup-node@v6
|
||||
- uses: actions/setup-node@v7
|
||||
with: { node-version: '24', cache: npm }
|
||||
- run: npm ci
|
||||
- run: npm run lint # biome check .
|
||||
@@ -160,7 +170,7 @@ jobs:
|
||||
contents: write # create the GitHub Release
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/setup-node@v6
|
||||
- uses: actions/setup-node@v7
|
||||
with: { node-version: '24', cache: npm }
|
||||
- run: npm ci
|
||||
|
||||
@@ -172,6 +182,7 @@ jobs:
|
||||
- run: npm run guard
|
||||
|
||||
- run: npm run zip # wxt zip → .output/<name>-<version>-chrome.zip
|
||||
- run: npm run check:manifest # gate the artifact, not the config it came from
|
||||
|
||||
- name: Verify tag matches manifest version
|
||||
run: |
|
||||
@@ -185,12 +196,18 @@ jobs:
|
||||
working-directory: .output
|
||||
run: sha256sum *-chrome.zip > SHA256SUMS.txt
|
||||
|
||||
- name: GitHub Release
|
||||
- name: GitHub Release # idempotent — see below
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
gh release create "$GITHUB_REF_NAME" \
|
||||
.output/*-chrome.zip .output/SHA256SUMS.txt --generate-notes
|
||||
set -euo pipefail
|
||||
if gh release view "$GITHUB_REF_NAME" >/dev/null 2>&1; then
|
||||
gh release upload "$GITHUB_REF_NAME" \
|
||||
.output/*-chrome.zip .output/SHA256SUMS.txt --clobber
|
||||
else
|
||||
gh release create "$GITHUB_REF_NAME" \
|
||||
.output/*-chrome.zip .output/SHA256SUMS.txt --generate-notes
|
||||
fi
|
||||
|
||||
- name: Publish to Chrome Web Store
|
||||
if: vars.CWS_AUTOPUBLISH == 'true'
|
||||
@@ -203,7 +220,7 @@ jobs:
|
||||
|
||||
announce:
|
||||
needs: release
|
||||
continue-on-error: true # see below
|
||||
if: vars.DISCORD_ANNOUNCE == 'true' # see below — NOT continue-on-error
|
||||
uses: poli0981/.github/.github/workflows/announce-release.yml@main
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -212,11 +229,32 @@ jobs:
|
||||
secrets: inherit
|
||||
```
|
||||
|
||||
`continue-on-error` because the reusable exits 1 on "No webhooks configured"
|
||||
when both Discord secrets are unset — which §5 lists as optional. 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.
|
||||
**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 CWS publish step, 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.
|
||||
|
||||
The announcement is gated because the reusable exits 1 on "No webhooks
|
||||
configured" when both Discord secrets are unset — which §5 lists as optional. 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.
|
||||
|
||||
⚠️ **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, it makes the whole run a `startup_failure` with zero jobs and no log.
|
||||
That is the same silent shape as the `contents: write` mistake in §2.1, and it
|
||||
sat undetected in this repo from `5f4c6e7` until 2026-08-03 precisely because
|
||||
that commit landed *after* the `v1.0.0` tag and no tag was pushed in between —
|
||||
the first v1.0.1 tag would have been its first execution.
|
||||
|
||||
A **variable** and not a secret: secrets cannot be referenced in a job-level
|
||||
`if:`. `vars.DISCORD_ANNOUNCE` defaults to unset, so the announcement is skipped
|
||||
and the release stays green until the owner opts in — the same idiom as
|
||||
`CWS_AUTOPUBLISH`. Set the variable only once the webhook secrets exist.
|
||||
|
||||
`tag_override` is **required here**, and for the same reason the announcement
|
||||
is a job rather than a caller. The reusable resolves
|
||||
@@ -245,6 +283,7 @@ permissions:
|
||||
|
||||
jobs:
|
||||
notify:
|
||||
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
|
||||
@@ -252,8 +291,24 @@ jobs:
|
||||
secrets: inherit
|
||||
```
|
||||
|
||||
The reusable already filters to `conclusion == 'failure'` on the default
|
||||
branch, so the caller needs no `if:`.
|
||||
The reusable filters to `conclusion == 'failure'` on the default branch
|
||||
internally, so the caller's `if:` is redundant *for behaviour* — but not for
|
||||
cost, and not for the failure below.
|
||||
|
||||
⚠️ **The reusable declares `DISCORD_CI_WEBHOOK` as `required: true`**, which
|
||||
GitHub validates before any of the reusable's own logic runs. With the secret
|
||||
unset (`00 §10.6`), the caller therefore failed on **every** CI completion —
|
||||
success or failure — from the first push after this file landed.
|
||||
|
||||
Both halves of the condition earn their place: the conclusion check stops it
|
||||
running on green CI at all, and `vars.DISCORD_CI_NOTIFY` keeps it off entirely
|
||||
until the secret actually exists. **Not `continue-on-error`** — see §2.3: GitHub
|
||||
rejects that keyword on a reusable-workflow caller and invalidates the file.
|
||||
|
||||
Same reasoning as §2.3's announce gate, learned the same way: a notification
|
||||
must never be able to change the colour of the thing it is reporting on, because
|
||||
a run that is red for a reason nobody acts on teaches everyone to stop reading
|
||||
the colour.
|
||||
|
||||
## 3. Chrome Web Store publishing automation
|
||||
|
||||
@@ -266,7 +321,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
|
||||
@@ -287,19 +342,35 @@ 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".
|
||||
|
||||
- [ ] ⚠️ 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. (Both strings match `ci.yml`.)
|
||||
- [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.
|
||||
- [ ] ⚠️ Actions secrets for Discord notifications. **`DISCORD_CI_WEBHOOK` is
|
||||
not optional in practice** — see §2.4. The rest are:
|
||||
`DISCORD_RELEASES_WEBHOOK`, `DISCORD_REPO_WEBHOOK`, `DISCORD_PING_ROLE_ID`.
|
||||
- [ ] ⚠️ 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`. Leave both
|
||||
unset until the matching webhook secrets exist — the reusables declare
|
||||
those secrets required, so calling them without one fails the job, and a
|
||||
reusable-workflow caller cannot use `continue-on-error` to absorb it
|
||||
(§2.3). Unset means skipped, which is the safe default.
|
||||
- [x] Dependabot: npm weekly, grouped dev minor+patch, `github-actions` too —
|
||||
`.github/dependabot.yml`. Note it has no awareness of the `package.json`
|
||||
`overrides` block, so those six pins must be reviewed by hand (`09 §3.1`).
|
||||
- [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.
|
||||
@@ -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
@@ -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
|
||||
|
||||
+61
-10
@@ -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).
|
||||
|
||||
@@ -18,7 +19,9 @@ Build-phase breakdown lives in `CLAUDE.md` (single source for sequencing).
|
||||
| 3 — #export + #edit | ✔ 2026-07-25 | tri-state picker, tree CRUD, search, duplicates, DnD + keyboard parity |
|
||||
| 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 — **in review** |
|
||||
| **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 |
|
||||
|
||||
**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
|
||||
@@ -70,11 +73,43 @@ 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
|
||||
## v1.0.x — stabilization (**the live workstream since 2026-08-03**)
|
||||
|
||||
- Parser-tolerance fixes from real user files (fixture + test per report).
|
||||
- Translation polish (JA review pass).
|
||||
- Listing copy tweaks from early reviews.
|
||||
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
|
||||
fixture-driven suite — **in the same PR** as the parser fix (`11 §2`).
|
||||
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
|
||||
|
||||
@@ -144,10 +179,10 @@ attestation resolver, deadlocking it until reload.
|
||||
| 2026-07-26 | Language labels are endonyms, duplicated identically across the three dicts (the `common.appName` precedent) | 07 §4 |
|
||||
| 2026-07-26 | Theme control is a three-way segmented control in both header and `#settings`, not a cycling `◐` | 06 §3 |
|
||||
| 2026-07-26 | Version comes from the manifest at runtime; three hardcoded `0.1.0` literals removed (footer, `run-export`, `run-import`) | 06 §3.5 |
|
||||
| 2026-07-26 | About's "Changelog" points at GitHub Releases until `CHANGELOG.md` exists in Phase 5 | 06 §3.5 |
|
||||
| 2026-07-26 | ~~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 | 03 §4 |
|
||||
| 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 |
|
||||
@@ -155,3 +190,19 @@ attestation resolver, deadlocking it until reload.
|
||||
| 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 |
|
||||
+24
-1
@@ -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,11 +34,34 @@ 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
|
||||
|
||||
Email: contact@poli0981.dev — or open an issue at
|
||||
|
||||
Generated
+135
-3259
File diff suppressed because it is too large.
Load diff
+7
-5
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "bookmarkmagic",
|
||||
"private": true,
|
||||
"version": "1.0.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",
|
||||
@@ -33,20 +33,22 @@
|
||||
"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",
|
||||
"@types/node": "^24.13.3",
|
||||
"@vitest/coverage-v8": "^4.1.10",
|
||||
"@wxt-dev/module-svelte": "^2.0.5",
|
||||
"jsdom": "^29.1.1",
|
||||
"jsdom": "^30.0.1",
|
||||
"knip": "^6.29.0",
|
||||
"svelte": "^5.56.8",
|
||||
"svelte-check": "^4.7.3",
|
||||
"svelte-check": "^4.7.4",
|
||||
"typescript": "~6.0.3",
|
||||
"vitest": "^4.1.10",
|
||||
"wxt": "^0.20.27"
|
||||
"wxt": "^0.21.3"
|
||||
},
|
||||
"overrides": {
|
||||
"shell-quote": "^1.9.0",
|
||||
|
||||
@@ -20,6 +20,32 @@ const MANIFEST = join(process.cwd(), '.output', 'chrome-mv3', 'manifest.json');
|
||||
/** Exactly this, in any order. Adding one is a minor-version event (docs/09 §4). */
|
||||
const ALLOWED_PERMISSIONS = ['bookmarks', 'storage'];
|
||||
|
||||
/**
|
||||
* 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, and the unit test over `wxt.config.ts` is structurally blind to it:
|
||||
* a WXT upgrade cannot change that file.
|
||||
*
|
||||
* Adding a key here is a deliberate act. Check docs/08 §1 first.
|
||||
*/
|
||||
const EXPECTED_KEYS = [
|
||||
'action',
|
||||
'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',
|
||||
@@ -60,6 +86,17 @@ for (const key of FORBIDDEN_KEYS) {
|
||||
if (key in manifest) problems.push(`declares "${key}": ${JSON.stringify(manifest[key])}`);
|
||||
}
|
||||
|
||||
const actualKeys = Object.keys(manifest).sort();
|
||||
const expectedKeys = [...EXPECTED_KEYS].sort();
|
||||
const unexpected = actualKeys.filter((key) => !expectedKeys.includes(key));
|
||||
const missing = expectedKeys.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 (problems.length > 0) {
|
||||
for (const problem of problems) {
|
||||
console.error(`::error::check-manifest: ${problem}`);
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* 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. */
|
||||
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;
|
||||
};
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
const out = { nodes: 10_000, perFolder: 50, seed: 1, out: undefined };
|
||||
for (let i = 0; i < argv.length; i += 2) {
|
||||
const key = argv[i];
|
||||
const value = argv[i + 1];
|
||||
if (key === '--nodes') out.nodes = Number(value);
|
||||
else if (key === '--per-folder') out.perFolder = Number(value);
|
||||
else if (key === '--seed') out.seed = Number(value);
|
||||
else if (key === '--out') out.out = value;
|
||||
}
|
||||
return 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 "here"',
|
||||
'Ampersand & more',
|
||||
'Angle <brackets>',
|
||||
'ブックマーク',
|
||||
'Thư mục quan trọng',
|
||||
'🌸 emoji title',
|
||||
'A rather long bookmark title that wraps in most reasonable window widths',
|
||||
];
|
||||
|
||||
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 written = 0;
|
||||
let folderIndex = 0;
|
||||
const indent = (depth) => ' '.repeat(depth);
|
||||
|
||||
// Depth 3 so the walk is exercised, but nowhere near the 200 cap — this file
|
||||
// is for measuring the common case, not the limit.
|
||||
const emitFolder = (depth) => {
|
||||
if (written >= nodes) return;
|
||||
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>`,
|
||||
);
|
||||
written++;
|
||||
|
||||
const count = Math.min(perFolder, nodes - written);
|
||||
for (let i = 0; i < count; i++) {
|
||||
const title = TITLE_POOL[Math.floor(rand() * TITLE_POOL.length)];
|
||||
const stampB = 1700000000 + written;
|
||||
lines.push(
|
||||
`${indent(depth + 1)}<DT><A HREF="https://host${written % 997}.example/p${written}?q=${written}" ` +
|
||||
`ADD_DATE="${stampB}">${title}</A>`,
|
||||
);
|
||||
written++;
|
||||
}
|
||||
|
||||
if (depth < 3 && written < nodes) emitFolder(depth + 1);
|
||||
lines.push(`${indent(depth)}</DL><p>`);
|
||||
};
|
||||
|
||||
while (written < nodes) emitFolder(1);
|
||||
lines.push('</DL><p>', '');
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
|
||||
if (options.out === undefined || !Number.isFinite(options.nodes) || options.nodes < 1) {
|
||||
console.error(
|
||||
'usage: node scripts/gen-fixture.mjs --nodes <n> --out <path> [--per-folder <n>] [--seed <n>]',
|
||||
);
|
||||
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`);
|
||||
}
|
||||
@@ -0,0 +1,627 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* 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, BookmarkMagic JSON, or CSV bookmark file.
|
||||
* Guarantees: every byte outside a replaced address or title is untouched —
|
||||
* including the BOM, the doctype, line endings, tag and attribute case,
|
||||
* quoting style, indentation, and every timestamp. Replacements are stable
|
||||
* per distinct input value, so "how many distinct hosts" and "which two
|
||||
* bookmarks are duplicates" survive.
|
||||
*
|
||||
* Zero dependencies, Node stdlib only, no network. It has to run from a fresh
|
||||
* clone with nothing installed, which is also why it re-implements a three-line
|
||||
* format sniff rather than importing `src/lib/core/detect-format.ts`.
|
||||
*
|
||||
* 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, writeFileSync } from 'node:fs';
|
||||
import { basename, extname } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
/** Matches docs/09's parse cap. A 25 MB attachment helps nobody anyway. */
|
||||
const MAX_BYTES = 25 * 1024 * 1024;
|
||||
|
||||
/** 1×1 transparent PNG. Keeps ICON= present, which is what the parser reacts to. */
|
||||
const BLANK_ICON =
|
||||
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=';
|
||||
|
||||
// ---------------------------------------------------------------- format sniff
|
||||
|
||||
/** 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'];
|
||||
|
||||
/**
|
||||
* Identify the format, or refuse.
|
||||
*
|
||||
* @param {string} text
|
||||
* @returns {'html' | 'json' | 'csv' | null} `null` when nothing matched.
|
||||
*
|
||||
* Returning `null` rather than guessing is load-bearing. Every sanitizer below
|
||||
* 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 to the user as
|
||||
* "sanitized". The old `return 'csv'` fallback did exactly that for a truncated
|
||||
* JSON export, an HTML excerpt with no doctype, or a CSV with foreign headers:
|
||||
* byte-identical output, exit code 0, real hostnames intact.
|
||||
*
|
||||
* 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, not
|
||||
* an edge case. `src/lib/core/detect-format.ts` refuses these same inputs with
|
||||
* `UNKNOWN_FORMAT`; this must not be weaker than the parser it fronts.
|
||||
*/
|
||||
export function detectKind(text) {
|
||||
const body = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
|
||||
if (/NETSCAPE-Bookmark-file-1/i.test(body.slice(0, 512))) return 'html';
|
||||
const trimmed = body.trimStart();
|
||||
if (trimmed.startsWith('{')) {
|
||||
try {
|
||||
JSON.parse(trimmed);
|
||||
return 'json';
|
||||
} catch {
|
||||
// Not JSON after all; fall through.
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------- mappers
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
function makeUrlMapper() {
|
||||
const seen = new Map();
|
||||
const hosts = new Map();
|
||||
|
||||
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;
|
||||
};
|
||||
|
||||
const escapesIn = (segment) => (segment.match(/%[0-9a-fA-F]{2}/g) ?? []).join('');
|
||||
|
||||
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 ? '/' : ''}`;
|
||||
};
|
||||
|
||||
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 scheme (javascript:, data:, mailto:). The scheme is the whole
|
||||
// point for the T1/T3 threat cases; the payload is not ours to keep.
|
||||
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.
|
||||
*/
|
||||
function makeTitleMapper() {
|
||||
const seen = new Map();
|
||||
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;
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ span rewriting
|
||||
|
||||
/**
|
||||
* Apply replacements by character span, right to left.
|
||||
*
|
||||
* Everything this tool does is expressed as spans so that the bytes between
|
||||
* them are provably untouched — that is the property the whole exercise rests
|
||||
* on, and rebuilding the file from a parsed model would quietly lose it.
|
||||
*
|
||||
* @param {string} text
|
||||
* @param {{start: number, end: number, value: string}[]} spans
|
||||
*/
|
||||
function replaceSpans(text, spans) {
|
||||
// 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,
|
||||
// silently eating or stranding bytes. The widest span sanitizes the most.
|
||||
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: the old loop rebuilt the whole
|
||||
// string for every replacement, which is O(spans x file) and takes minutes on
|
||||
// a large export.
|
||||
return out.join('');
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect spans for one capture group of a global regex. `map` receives the
|
||||
* captured text.
|
||||
*
|
||||
* The group's offset is computed by re-scanning the match, so the regex must
|
||||
* capture a span that appears only once within it — true for every pattern
|
||||
* here, since each captures an attribute value or an element's text.
|
||||
*
|
||||
* @param {string} text
|
||||
* @param {RegExp} re
|
||||
* @param {(captured: string) => string} map
|
||||
* @param {number} [group]
|
||||
*/
|
||||
function spansFrom(text, re, map, group = 1) {
|
||||
// The `d` flag gives exact per-group offsets. The previous version searched
|
||||
// the match text for the captured substring, which lands on the wrong copy
|
||||
// whenever the capture also appears earlier in the match — e.g. a bookmark
|
||||
// whose title equals part of its own URL.
|
||||
const indexed = new RegExp(re.source, re.flags.includes('d') ? re.flags : `${re.flags}d`);
|
||||
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 and appears in the T1/T3
|
||||
* fixtures. A naive `[^>]*` stops inside it, silently leaving that bookmark's
|
||||
* title unsanitized — which is the one failure mode this tool must not have.
|
||||
*/
|
||||
const TAG_INNARDS = '(?:"[^"]*"|\'[^\']*\'|[^>"\'])*';
|
||||
|
||||
// ------------------------------------------------------------------ formats
|
||||
|
||||
/**
|
||||
* Decode an HTML attribute value, then re-encode the result the way the source
|
||||
* file encoded it.
|
||||
*
|
||||
* Netscape exports write `&` inside HREF, but not all of them do, and
|
||||
* whether a parser unescapes attribute values is itself something people report
|
||||
* bugs about. Emitting a bare `&` where the source had `&` would silently
|
||||
* repair the file being reported.
|
||||
*/
|
||||
function attrRewriter(map) {
|
||||
return (captured) => {
|
||||
const decoded = captured
|
||||
.replace(/&/gi, '&')
|
||||
.replace(/</gi, '<')
|
||||
.replace(/>/gi, '>')
|
||||
.replace(/"/gi, '"');
|
||||
const mapped = map(decoded);
|
||||
const escapesAmp = /&/i.test(captured) || !captured.includes('&');
|
||||
return escapesAmp ? mapped.replace(/&/g, '&') : 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 — real exports in the wild use
|
||||
* single quotes, and that one is a straight leak.
|
||||
*/
|
||||
const ANY_ATTR = /\b([a-z_][a-z0-9_-]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'<>=`]+))/dgi;
|
||||
|
||||
/**
|
||||
* Spans for every attribute whose name matches, at any quoting.
|
||||
*
|
||||
* @param {string} text
|
||||
* @param {RegExp} nameRe tested against the lower-cased attribute name
|
||||
* @param {(value: string) => string} map
|
||||
*/
|
||||
function attrSpans(text, nameRe, map) {
|
||||
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;
|
||||
}
|
||||
|
||||
/** 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 a URL with a host.
|
||||
*
|
||||
* Firefox alone writes `ICON_URI`, and `FEEDURL` and friends exist in the wild.
|
||||
* Enumerating them was already wrong once — `ICON_URI` leaked a real hostname
|
||||
* through a file that had passed every other check — so this sweeps by value
|
||||
* shape instead, and covers attributes nobody has thought of yet.
|
||||
*/
|
||||
function urlAttrSpans(text, mapUrl) {
|
||||
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 === '') continue;
|
||||
try {
|
||||
if (new URL(value).host === '') continue;
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
const at = m.indices?.[2] ?? m.indices?.[3] ?? m.indices?.[4];
|
||||
if (at === undefined) continue;
|
||||
spans.push({ start: at[0], end: at[1], value: rewrite(value) });
|
||||
}
|
||||
return spans;
|
||||
}
|
||||
|
||||
function sanitizeHtml(text, mapUrl, mapTitle) {
|
||||
let descriptions = 0;
|
||||
let keywords = 0;
|
||||
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 titles: the text between <A …> and </A>.
|
||||
// `[\s\S]*?` and not `[^<]*`: a title containing a raw `<` made the whole
|
||||
// match fail, so that bookmark's title was left in the output untouched.
|
||||
...spansFrom(text, new RegExp(`<a\\b${TAG_INNARDS}>([\\s\\S]*?)</a>`, 'gi'), mapTitle),
|
||||
// Folder titles.
|
||||
...spansFrom(text, new RegExp(`<h3\\b${TAG_INNARDS}>([\\s\\S]*?)</h3>`, 'gi'), mapTitle),
|
||||
// Folder/bookmark descriptions.
|
||||
// Runs to the next element, not to the end of the line: a description that
|
||||
// wrapped onto a second line left everything after the first newline in
|
||||
// place, and a `<DD>` is exactly where someone writes a private note.
|
||||
...spansFrom(
|
||||
text,
|
||||
// The `\s*` belongs in the lookahead, not the capture: leaving it inside
|
||||
// eats the newline and indentation before the next tag, which is exactly
|
||||
// the byte-level shape this tool promises not to touch.
|
||||
/<dd>([\s\S]*?)(?=\s*<\s*(?:dt|dd|dl|\/dl)\b|\s*$)/gi,
|
||||
() => `Description ${++descriptions}`,
|
||||
),
|
||||
];
|
||||
return replaceSpans(text, spans);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rewrite only the *values* of `url` and `title` string properties, by walking
|
||||
* the raw text. Parsing and re-stringifying would normalize the indentation and
|
||||
* line endings, which is exactly what a whitespace-sensitive report needs kept.
|
||||
*/
|
||||
function sanitizeJson(text, mapUrl, mapTitle) {
|
||||
const spans = [];
|
||||
const re = /"(url|title)"\s*:\s*"((?:[^"\\]|\\.)*)"/g;
|
||||
for (const m of text.matchAll(re)) {
|
||||
const key = m[1];
|
||||
const rawValue = m[2] ?? '';
|
||||
const start = m.index + m[0].length - 1 - rawValue.length;
|
||||
let decoded;
|
||||
try {
|
||||
decoded = JSON.parse(`"${rawValue}"`);
|
||||
} catch {
|
||||
decoded = rawValue;
|
||||
}
|
||||
const mapped = key === 'url' ? mapUrl(decoded) : mapTitle(decoded);
|
||||
spans.push({ start, end: start + rawValue.length, value: JSON.stringify(mapped).slice(1, -1) });
|
||||
}
|
||||
return replaceSpans(text, spans);
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk the CSV with 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
|
||||
* untouched — which matters, because CSV quoting is itself a common bug.
|
||||
*/
|
||||
function sanitizeCsv(text, mapUrl, mapTitle) {
|
||||
const delimiter = (text.split('\n', 1)[0] ?? '').includes(';') ? ';' : ',';
|
||||
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 === '"') {
|
||||
if (text[i + 1] === '"') {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === delimiter || ch === '\n' || ch === '\r') break;
|
||||
i++;
|
||||
}
|
||||
fields.push({ row, col, start, end: i, quoted });
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
// 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());
|
||||
const at = (name) => header.findIndex((h) => h.toLowerCase().replace(/^/, '') === name);
|
||||
const [folderCol, titleCol, urlCol] = [at('folder_path'), at('title'), at('url')];
|
||||
|
||||
const spans = [];
|
||||
for (const f of fields) {
|
||||
if (f.row === 0 || f.start === f.end) continue;
|
||||
const raw = text.slice(f.start, f.end);
|
||||
const value = raw.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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 survives into the output. Without that, `Escaped\/slash` sanitizes to
|
||||
* a plain name and the escape branch of the CSV path parser — a real reason
|
||||
* someone would file a report — stops being exercised by the sample.
|
||||
*/
|
||||
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++;
|
||||
continue;
|
||||
}
|
||||
if (ch === '/') {
|
||||
segments.push(current);
|
||||
current = '';
|
||||
continue;
|
||||
}
|
||||
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('/');
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------- entry points
|
||||
|
||||
/**
|
||||
* Everything in the OUTPUT that still looks like a real address.
|
||||
*
|
||||
* This is the backstop, and it is the only reason the rules above can be
|
||||
* trusted. They are regexes 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>` that wraps onto a second line. Every one of
|
||||
* those is a silent leak, and the only way to find them all by inspection is to
|
||||
* be sure you have thought of every one, which nobody is.
|
||||
*
|
||||
* So instead of trusting the rules, the output is checked: any host that is not
|
||||
* one of our own `*.example` aliases means something got through, and the file
|
||||
* is refused rather than handed over. A rule this misses degrades into a
|
||||
* refusal — annoying — instead of into a published browsing history.
|
||||
*
|
||||
* @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];
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize a bookmark file's text.
|
||||
*
|
||||
* @param {string} text
|
||||
* @returns {{ text: string | null, kind: 'html' | 'json' | 'csv' | 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();
|
||||
const out =
|
||||
kind === 'html'
|
||||
? sanitizeHtml(text, mapUrl, mapTitle)
|
||||
: kind === 'json'
|
||||
? sanitizeJson(text, mapUrl, mapTitle)
|
||||
: sanitizeCsv(text, mapUrl, mapTitle);
|
||||
|
||||
const leaked = findLeakedHosts(out);
|
||||
return { text: leaked.length > 0 ? null : out, kind, leaked };
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
const raw = readFileSync(input);
|
||||
if (raw.byteLength > MAX_BYTES) {
|
||||
console.error(
|
||||
`${input} is ${(raw.byteLength / 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 = raw.toString('utf8');
|
||||
const { text: out, kind, leaked } = sanitize(text);
|
||||
|
||||
if (kind === null) {
|
||||
console.error(
|
||||
`${basename(input)} is not a bookmark file this tool recognises, so NOTHING WAS WRITTEN.\n` +
|
||||
' Expected: a Netscape HTML export (the usual bookmarks.html), a BookmarkMagic JSON\n' +
|
||||
' export, 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;
|
||||
}
|
||||
|
||||
if (out === null) {
|
||||
console.error(
|
||||
`${basename(input)}: NOTHING WAS WRITTEN — the result still contained ${leaked.length} real ` +
|
||||
`address(es), so this file is not safe to attach.\n Leaked: ${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 address above is enough.',
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
|
||||
const eol = text.includes('\r\n') ? 'CRLF' : 'LF';
|
||||
const bom = text.charCodeAt(0) === 0xfeff ? ', BOM' : '';
|
||||
console.error(`${basename(input)}: ${kind}, ${eol}${bom} — ${out.length} 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}`;
|
||||
writeFileSync(target, out);
|
||||
console.error(`wrote ${target}`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (process.argv[1] !== undefined && process.argv[1] === fileURLToPath(import.meta.url)) {
|
||||
process.exitCode = main(process.argv.slice(2));
|
||||
}
|
||||
@@ -21,7 +21,14 @@
|
||||
isGateRequired,
|
||||
} from '@/lib/stores/legal.svelte';
|
||||
import { getRoute, navigate, startRouting } from '@/lib/stores/route.svelte';
|
||||
import { flushSettings, getSettings, updateSettings } 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.
|
||||
@@ -33,7 +40,14 @@
|
||||
let mainEl: HTMLElement | undefined = $state();
|
||||
|
||||
onMount(() => {
|
||||
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 => {
|
||||
@@ -48,11 +62,22 @@
|
||||
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);
|
||||
};
|
||||
|
||||
@@ -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++;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
};
|
||||
}
|
||||
@@ -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++;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { getAppVersion } from '../browser/app-info';
|
||||
import { dateTime, t } from '../i18n/index.svelte';
|
||||
import { CHANGELOG_URL, DONATE_LINKS, ISSUES_URL, LEGAL_URLS, REPO_URL } from '../links';
|
||||
import { CHANGELOG_URL, DONATE_LINKS, ISSUES_URL, LEGAL_URLS, REPO_URL, STORE_URL } from '../links';
|
||||
import { getAcceptance } from '../stores/legal.svelte';
|
||||
|
||||
const version = getAppVersion();
|
||||
@@ -33,6 +33,7 @@
|
||||
{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>
|
||||
|
||||
+107
-112
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { onMount, untrack } from 'svelte';
|
||||
import {
|
||||
create,
|
||||
getRootChildren,
|
||||
@@ -10,7 +10,7 @@
|
||||
update,
|
||||
} from '../browser/bookmarks';
|
||||
import { copyToClipboard } from '../browser/clipboard';
|
||||
import { BmBrowserError } from '../browser/errors';
|
||||
import { type DescribedError, describeError } from '../browser/describe-error';
|
||||
import { openBookmarkUrl } from '../browser/open-url';
|
||||
import { findDuplicateGroups } from '../core/dedupe';
|
||||
import { searchTree } from '../core/search';
|
||||
@@ -30,31 +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 { num, t } from '../i18n/index.svelte';
|
||||
import { pushToast } from '../stores/toast.svelte';
|
||||
import Callout from './Callout.svelte';
|
||||
import ErrorCallout from './ErrorCallout.svelte';
|
||||
import ConfirmDialog from './ConfirmDialog.svelte';
|
||||
import DuplicatePanel from './DuplicatePanel.svelte';
|
||||
import EditToolbar from './EditToolbar.svelte';
|
||||
import MoveToDialog from './MoveToDialog.svelte';
|
||||
import TreeRow from './TreeRow.svelte';
|
||||
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>();
|
||||
|
||||
@@ -96,7 +106,9 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,16 +126,53 @@
|
||||
// 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 partialNote = $derived(
|
||||
actionError?.partial === undefined
|
||||
? undefined
|
||||
: t('edit.keepFirstPartial', {
|
||||
done: num(actionError.partial.done),
|
||||
total: num(actionError.partial.total),
|
||||
}),
|
||||
);
|
||||
|
||||
// `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)),
|
||||
findDuplicateGroups(
|
||||
flattenTree(roots).filter((node) => node.url !== undefined && isEditable(node)),
|
||||
),
|
||||
);
|
||||
|
||||
/**
|
||||
@@ -136,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();
|
||||
}
|
||||
}
|
||||
@@ -149,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 {
|
||||
@@ -251,12 +300,21 @@
|
||||
// Snapshot the ids first: duplicateGroups is $derived from `roots`, so
|
||||
// reading it inside the loop would recompute mid-iteration.
|
||||
const doomed = extraCopyIds(duplicateGroups);
|
||||
await guardEdit(async () => {
|
||||
for (const id of doomed) {
|
||||
roots = removeNode(roots, id);
|
||||
await remove(id);
|
||||
}
|
||||
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. */
|
||||
@@ -300,7 +358,7 @@
|
||||
</script>
|
||||
|
||||
{#if loadError !== undefined}
|
||||
<Callout tone="danger">{loadError}</Callout>
|
||||
<ErrorCallout messageKey={loadError.messageKey} detail={loadError.detail} />
|
||||
{:else}
|
||||
<EditToolbar
|
||||
bind:input={searchInput}
|
||||
@@ -313,65 +371,37 @@
|
||||
/>
|
||||
|
||||
{#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 ?? '')}
|
||||
oncopyUrl={() => void copyUrl(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
|
||||
@@ -441,41 +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;
|
||||
}
|
||||
|
||||
</style>
|
||||
@@ -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>
|
||||
@@ -1,7 +1,7 @@
|
||||
<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';
|
||||
@@ -16,13 +16,14 @@
|
||||
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 loadError = $state<DescribedError | undefined>();
|
||||
let csvDelimiter = $state<CsvDelimiter>(',');
|
||||
let markdownStyle = $state<MarkdownStyle>('nested');
|
||||
|
||||
@@ -39,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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,15 +66,17 @@
|
||||
pushToast(t('export.saved', { name: result.filename }), 'success');
|
||||
} catch (err) {
|
||||
// Tone matters: this used to share a variable with the success message
|
||||
// and rendered failures in success-green.
|
||||
pushToast(err instanceof BmBrowserError ? err.detail : t('errors.UNKNOWN'), 'danger');
|
||||
// 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')}>
|
||||
|
||||
@@ -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 { 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,36 +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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map an error onto an i18n KEY plus a raw detail — never a resolved string.
|
||||
* The session store outlives this component, and `t()` only re-runs where it
|
||||
* is called, so a translated sentence stored here would never follow a
|
||||
* language switch.
|
||||
*/
|
||||
function describeError(err: unknown): { messageKey: string; detail: string | undefined } {
|
||||
if (err instanceof BmParseError) {
|
||||
return { messageKey: `errors.${err.code}`, detail: err.detail };
|
||||
}
|
||||
if (err instanceof BmBackupError) {
|
||||
return { messageKey: `errors.${err.code}`, detail: err.message };
|
||||
}
|
||||
if (err instanceof BmBrowserError) {
|
||||
return { messageKey: 'errors.BROWSER', detail: err.detail };
|
||||
}
|
||||
return {
|
||||
messageKey: 'errors.UNKNOWN',
|
||||
detail: err instanceof Error ? err.message : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
async function onFile(file: File): Promise<void> {
|
||||
setImportState({ kind: 'validating', filename: file.name });
|
||||
try {
|
||||
@@ -87,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.
|
||||
@@ -111,23 +86,43 @@
|
||||
// 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 } : {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,6 +159,7 @@
|
||||
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)}
|
||||
@@ -179,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>
|
||||
@@ -206,6 +204,7 @@
|
||||
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
|
||||
@@ -214,13 +213,24 @@
|
||||
</div>
|
||||
{:else if session.kind === 'cancelled'}
|
||||
<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">{t(session.messageKey)}</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
|
||||
@@ -272,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,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>
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -45,6 +45,19 @@ const dict = {
|
||||
doneSummary: 'Done — {created} items created.',
|
||||
skipped: 'Skipped {existing} already in this browser and {inFile} repeated in the file.',
|
||||
cancelledSummary: 'Cancelled — {created} items were already created and were left in place.',
|
||||
// docs/05 §6 and docs/00 §8 both require saying this, and nothing did.
|
||||
// chrome.bookmarks.create takes no dateAdded, so every imported bookmark is
|
||||
// stamped with the import time — indistinguishable from corruption to
|
||||
// someone migrating a decade-old archive.
|
||||
cancelledAfterClear:
|
||||
'You cancelled after your existing bookmarks had already been deleted, so what is left is only the part that was rebuilt.',
|
||||
dateNotice:
|
||||
'Imported bookmarks are dated today. Chrome does not let an extension set a bookmark’s original date — your exported files keep the real ones.',
|
||||
partialCreated:
|
||||
'{created} items had already been created before this failed, and were left in place.',
|
||||
partialCleared:
|
||||
'{removed} top-level items had already been deleted before this failed. Restore them from your backup.',
|
||||
backupHint: 'Your safety backup was saved as {name}. Restore it by importing that JSON file.',
|
||||
openEdit: 'Open Edit tab',
|
||||
another: 'Import another file',
|
||||
dedupe: 'Skip duplicates already in this browser ({n} found)',
|
||||
@@ -131,6 +144,10 @@ const dict = {
|
||||
keepFirstTitle: 'Delete duplicate copies?',
|
||||
keepFirstBody:
|
||||
'Keep the first copy of each link and delete the other {n}? This cannot be undone.',
|
||||
// The dialog promises an exact number, so a partial delete has to reconcile
|
||||
// against it — the action cannot be undone.
|
||||
keepFirstPartial:
|
||||
'Deleted {done} of {total} copies before this failed. Nothing else was removed.',
|
||||
},
|
||||
settings: {
|
||||
autosave: 'Changes are saved as you make them.',
|
||||
@@ -175,6 +192,7 @@ const dict = {
|
||||
repo: 'GitHub repository',
|
||||
issues: 'Report an issue',
|
||||
changelog: 'Releases and changelog',
|
||||
store: 'Chrome Web Store listing',
|
||||
thirdParty: 'Third-party dependencies: None',
|
||||
thirdPartyNote: 'BookmarkMagic ships no runtime libraries at all.',
|
||||
donate: 'Support development',
|
||||
@@ -256,6 +274,10 @@ const dict = {
|
||||
BACKUP_CANCELLED: 'You cancelled the safety backup, so nothing was deleted.',
|
||||
BACKUP_WRITE_FAILED: 'The safety backup could not be saved, so nothing was deleted.',
|
||||
BROWSER: 'The browser refused a bookmark operation.',
|
||||
NO_WRITABLE_ROOTS:
|
||||
'This browser profile has no bookmark folder BookmarkMagic is allowed to write to. Bookmarks managed by an organisation cannot be changed.',
|
||||
PARTIAL_WRITE: 'The browser stopped accepting bookmarks part-way through the import.',
|
||||
PARTIAL_CLEAR: 'The browser stopped part-way through replacing your bookmarks.',
|
||||
UNKNOWN: 'Something went wrong.',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -38,6 +38,15 @@ export default {
|
||||
skipped:
|
||||
'このブラウザに既にある {existing} 件と、ファイル内で重複する {inFile} 件をスキップしました。',
|
||||
cancelledSummary: 'キャンセルしました — 既に作成された {created} 件はそのまま残されています。',
|
||||
cancelledAfterClear:
|
||||
'既存のブックマークが削除された後にキャンセルされたため、残っているのは再作成された分だけです。',
|
||||
dateNotice:
|
||||
'インポートしたブックマークの日付は本日になります。拡張機能がブックマークの元の作成日を設定することを Chrome が許可していないためです。エクスポートしたファイルには本来の日付が残ります。',
|
||||
partialCreated: 'エラーが発生する前に作成された {created} 件はそのまま残されています。',
|
||||
partialCleared:
|
||||
'エラーが発生する前に、最上位の {removed} 件が既に削除されています。バックアップから復元してください。',
|
||||
backupHint:
|
||||
'安全のためのバックアップは {name} として保存されています。その JSON ファイルをインポートすると復元できます。',
|
||||
openEdit: '編集タブを開く',
|
||||
another: '別のファイルをインポート',
|
||||
dedupe: 'このブラウザに既にあるものをスキップする({n} 件見つかりました)',
|
||||
@@ -123,6 +132,8 @@ export default {
|
||||
keeps: '保持',
|
||||
keepFirstTitle: '重複したコピーを削除しますか?',
|
||||
keepFirstBody: '各リンクの最初のコピーを残し、他の {n} 件を削除しますか?元に戻せません。',
|
||||
keepFirstPartial:
|
||||
'エラーが発生する前に {total} 件中 {done} 件を削除しました。それ以外は削除されていません。',
|
||||
},
|
||||
settings: {
|
||||
autosave: '変更は自動的に保存されます。',
|
||||
@@ -166,6 +177,7 @@ export default {
|
||||
repo: 'GitHub リポジトリ',
|
||||
issues: '問題を報告',
|
||||
changelog: 'リリースと変更履歴',
|
||||
store: 'Chrome ウェブストアのページ',
|
||||
thirdParty: 'サードパーティ依存: なし',
|
||||
thirdPartyNote: 'BookmarkMagic は実行時ライブラリを一切同梱していません。',
|
||||
donate: '開発を支援する',
|
||||
@@ -241,6 +253,10 @@ export default {
|
||||
BACKUP_CANCELLED: 'バックアップがキャンセルされたため、何も削除していません。',
|
||||
BACKUP_WRITE_FAILED: 'バックアップを保存できなかったため、何も削除していません。',
|
||||
BROWSER: 'ブラウザがブックマークの操作を拒否しました。',
|
||||
NO_WRITABLE_ROOTS:
|
||||
'このブラウザプロファイルには、BookmarkMagic が書き込みを許可されているブックマークフォルダがありません。組織によって管理されているブックマークは変更できません。',
|
||||
PARTIAL_WRITE: 'インポートの途中で、ブラウザがブックマークの受け付けを停止しました。',
|
||||
PARTIAL_CLEAR: 'ブックマークを置き換えている途中で、ブラウザが停止しました。',
|
||||
UNKNOWN: '問題が発生しました。',
|
||||
},
|
||||
} satisfies Dict;
|
||||
@@ -33,6 +33,15 @@ export default {
|
||||
doneSummary: 'Hoàn tất — đã tạo {created} mục.',
|
||||
skipped: 'Đã bỏ qua {existing} mục đã có trong trình duyệt và {inFile} mục lặp trong tệp.',
|
||||
cancelledSummary: 'Đã hủy — {created} mục đã được tạo trước đó và vẫn được giữ lại.',
|
||||
cancelledAfterClear:
|
||||
'Bạn đã hủy sau khi bookmark cũ đã bị xóa, nên những gì còn lại chỉ là phần đã được tạo lại.',
|
||||
dateNotice:
|
||||
'Bookmark được nhập vào sẽ mang ngày hôm nay. Chrome không cho phép tiện ích đặt lại ngày tạo gốc của bookmark — các tệp bạn xuất ra vẫn giữ ngày thật.',
|
||||
partialCreated: '{created} mục đã được tạo trước khi lỗi xảy ra và vẫn được giữ lại.',
|
||||
partialCleared:
|
||||
'{removed} mục ở cấp cao nhất đã bị xóa trước khi lỗi xảy ra. Hãy khôi phục chúng từ tệp sao lưu của bạn.',
|
||||
backupHint:
|
||||
'Tệp sao lưu an toàn đã được lưu với tên {name}. Nhập lại tệp JSON đó để khôi phục.',
|
||||
openEdit: 'Mở thẻ Chỉnh sửa',
|
||||
another: 'Nhập tệp khác',
|
||||
dedupe: 'Bỏ qua mục đã có trong trình duyệt này (tìm thấy {n})',
|
||||
@@ -122,6 +131,8 @@ export default {
|
||||
keeps: 'giữ lại',
|
||||
keepFirstTitle: 'Xóa các bản trùng?',
|
||||
keepFirstBody: 'Giữ bản đầu tiên của mỗi liên kết và xóa {n} bản còn lại? Không thể hoàn tác.',
|
||||
keepFirstPartial:
|
||||
'Đã xóa {done} trong số {total} bản trước khi lỗi xảy ra. Không có gì khác bị xóa.',
|
||||
},
|
||||
settings: {
|
||||
autosave: 'Thay đổi được lưu ngay khi bạn chỉnh.',
|
||||
@@ -165,6 +176,7 @@ export default {
|
||||
repo: 'Kho mã trên GitHub',
|
||||
issues: 'Báo lỗi',
|
||||
changelog: 'Bản phát hành và nhật ký thay đổi',
|
||||
store: 'Trang trên Chrome Web Store',
|
||||
thirdParty: 'Thư viện bên thứ ba: Không có',
|
||||
thirdPartyNote: 'BookmarkMagic không đi kèm bất kỳ thư viện chạy nào.',
|
||||
donate: 'Ủng hộ dự án',
|
||||
@@ -239,6 +251,10 @@ export default {
|
||||
BACKUP_CANCELLED: 'Bạn đã hủy bản sao lưu, nên không có gì bị xóa.',
|
||||
BACKUP_WRITE_FAILED: 'Không thể lưu bản sao lưu, nên không có gì bị xóa.',
|
||||
BROWSER: 'Trình duyệt đã từ chối một thao tác bookmark.',
|
||||
NO_WRITABLE_ROOTS:
|
||||
'Hồ sơ trình duyệt này không có thư mục bookmark nào mà BookmarkMagic được phép ghi vào. Bookmark do tổ chức quản lý thì không thể thay đổi.',
|
||||
PARTIAL_WRITE: 'Trình duyệt đã ngừng nhận bookmark khi quá trình nhập đang diễn ra.',
|
||||
PARTIAL_CLEAR: 'Trình duyệt đã dừng lại giữa chừng khi đang thay thế bookmark của bạn.',
|
||||
UNKNOWN: 'Đã xảy ra lỗi.',
|
||||
},
|
||||
} satisfies Dict;
|
||||
@@ -19,6 +19,22 @@ export const ISSUES_URL = `${REPO_URL}/issues`;
|
||||
|
||||
export const CHANGELOG_URL = `${REPO_URL}/blob/main/CHANGELOG.md`;
|
||||
|
||||
/**
|
||||
* The published Chrome Web Store listing (item id — docs/00 §9).
|
||||
*
|
||||
* The only route from inside the product to rating or reviewing it, which
|
||||
* docs/13 §6 lists as a post-launch channel.
|
||||
*
|
||||
* There is deliberately **no support email here.** Putting an address on an
|
||||
* in-product surface invites users to mail their real bookmarks file, which is
|
||||
* a browsing history and exactly the receipt of personal data that
|
||||
* `legal/PRIVACY.md` and docs/09 §6 are written to bound. The address lives in
|
||||
* SECURITY.md, CONTRIBUTING.md and the privacy policy, where it arrives with
|
||||
* the instruction to sanitize first (docs/15 decision log, 2026-08-03).
|
||||
*/
|
||||
export const STORE_URL =
|
||||
'https://chromewebstore.google.com/detail/bookmarkmagic/eghnciphhegekmnofffpgbdfefckdhmg';
|
||||
|
||||
export interface LabelledLink {
|
||||
labelKey: string;
|
||||
url: string;
|
||||
|
||||
@@ -31,7 +31,12 @@ export type ImportState =
|
||||
// begun, and nothing in the progress UI needs it.
|
||||
| { kind: 'writing'; filename: string; progress: WriteProgress }
|
||||
| { kind: 'done'; filename: string; created: number; plan: ImportPlan }
|
||||
| { kind: 'cancelled'; filename: string; created: number }
|
||||
/**
|
||||
* `backupFilename` is present only when the cancel landed AFTER the Replace
|
||||
* clear, i.e. the tree really was deleted and only `created` of it rebuilt.
|
||||
* Without it the report reads as a harmless no-op on an empty browser.
|
||||
*/
|
||||
| { kind: 'cancelled'; filename: string; created: number; backupFilename?: string }
|
||||
/**
|
||||
* `messageKey` is a dotted i18n path, NOT a resolved string.
|
||||
*
|
||||
@@ -40,7 +45,31 @@ export type ImportState =
|
||||
* was active when the error happened, so switching language left the error
|
||||
* message behind in the old one.
|
||||
*/
|
||||
| { kind: 'error'; filename: string; messageKey: string; detail: string | undefined };
|
||||
| {
|
||||
kind: 'error';
|
||||
filename: string;
|
||||
messageKey: string;
|
||||
/**
|
||||
* Raw technical text, absent when there is none.
|
||||
*
|
||||
* Optional rather than `string | undefined` so it matches `DescribedError`
|
||||
* exactly — under `exactOptionalPropertyTypes` those are different types,
|
||||
* and a spread of one into the other is a compile error.
|
||||
*/
|
||||
detail?: string | undefined;
|
||||
/** Nodes created before a partial failure, when the failure knows. */
|
||||
created?: number;
|
||||
/** Root children deleted before a partial failure, when it knows. */
|
||||
removed?: number;
|
||||
/**
|
||||
* The safety backup's filename, on a Replace that got past the backup.
|
||||
*
|
||||
* Carried onto the failure deliberately: `attesting` knew it and `error`
|
||||
* used to throw it away, so the one string that lets a user restore a
|
||||
* half-deleted tree was the one thing not on screen.
|
||||
*/
|
||||
backupFilename?: string;
|
||||
};
|
||||
|
||||
let state = $state<ImportState>({ kind: 'idle' });
|
||||
let options = $state<ImportOptionsState>({ mode: 'new-folder', dedupe: true });
|
||||
@@ -102,7 +131,41 @@ export function cancelWrite(): void {
|
||||
controller?.abort();
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolver for the fallback-backup attestation — held HERE, not in `ImportTab`.
|
||||
*
|
||||
* As a component-local `let` it died with the component. Pressing Back during
|
||||
* `attesting` unmounted the tab, 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.
|
||||
*/
|
||||
let attestResolve: ((confirmed: boolean) => void) | undefined;
|
||||
|
||||
/** Wait for the user to confirm they have the fallback backup. */
|
||||
export function awaitAttestation(): Promise<boolean> {
|
||||
// A resolver that is still live fails CLOSED. An unanswered attestation is
|
||||
// not consent, and this is the gate in front of deleting every bookmark.
|
||||
attestResolve?.(false);
|
||||
return new Promise<boolean>((resolve) => {
|
||||
attestResolve = resolve;
|
||||
});
|
||||
}
|
||||
|
||||
export function answerAttestation(confirmed: boolean): void {
|
||||
attestResolve?.(confirmed);
|
||||
attestResolve = undefined;
|
||||
}
|
||||
|
||||
export function hasPendingAttestation(): boolean {
|
||||
return attestResolve !== undefined;
|
||||
}
|
||||
|
||||
export function resetImport(): void {
|
||||
// Before clearing state, not after: otherwise "Import another file" during an
|
||||
// attestation moves the deadlock out of a component and into this store,
|
||||
// where nothing renders it and nobody would find it.
|
||||
answerAttestation(false);
|
||||
controller = undefined;
|
||||
prepared = undefined;
|
||||
state = { kind: 'idle' };
|
||||
|
||||
@@ -94,6 +94,28 @@ export async function loadLegal(): Promise<void> {
|
||||
status = decideLegalStatus(await readLegal(), LEGAL_VERSION);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adopt an acceptance recorded by another Manager tab — **one way only**.
|
||||
*
|
||||
* Accepting in one tab drops the gate in the other. The reverse is deliberately
|
||||
* unreachable: `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, exactly the
|
||||
* deadlock the routing guard and the store-held attestation resolver exist to
|
||||
* close. Clearing storage in another tab therefore does nothing here; a reload
|
||||
* is what re-evaluates the gate downward, and that is a fresh page with no
|
||||
* in-flight work to strand.
|
||||
*
|
||||
* @returns whether the gate was dropped.
|
||||
*/
|
||||
export function adoptExternalLegal(acceptance: LegalAcceptance | null): boolean {
|
||||
if (status.kind === 'accepted') return false;
|
||||
const next = decideLegalStatus(acceptance, LEGAL_VERSION);
|
||||
if (next.kind !== 'accepted') return false;
|
||||
status = next;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Record acceptance.
|
||||
*
|
||||
|
||||
@@ -22,19 +22,61 @@ export function getRoute(): Route {
|
||||
return current;
|
||||
}
|
||||
|
||||
export function navigate(route: Route): void {
|
||||
current = route;
|
||||
if (globalThis.location !== undefined) globalThis.location.hash = `#${route}`;
|
||||
/**
|
||||
* Refuses to leave while work would be orphaned. Injected rather than imported,
|
||||
* so this module keeps knowing nothing about the import session.
|
||||
*/
|
||||
export interface RoutingOptions {
|
||||
/** True while leaving the current route would strand in-flight work. */
|
||||
isBlocked?: () => boolean;
|
||||
/** Called when a navigation was refused, so the UI can explain itself. */
|
||||
onBlocked?: () => void;
|
||||
}
|
||||
|
||||
/** Sync from the URL and follow it. Returns a cleanup function. */
|
||||
export function startRouting(): () => void {
|
||||
let blocked: (() => boolean) | undefined;
|
||||
|
||||
/**
|
||||
* Navigate, unless a write is in flight.
|
||||
*
|
||||
* @returns whether the navigation actually happened. Callers that ignore this
|
||||
* turn a refusal into a button that appears to do nothing.
|
||||
*/
|
||||
export function navigate(route: Route): boolean {
|
||||
if (route !== current && blocked?.() === true) return false;
|
||||
current = route;
|
||||
if (globalThis.location !== undefined) globalThis.location.hash = `#${route}`;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync from the URL and follow it. Returns a cleanup function.
|
||||
*
|
||||
* The `hashchange` listener is also the thing that made Back dangerous. Every
|
||||
* `navigate()` writes a history entry, so during an import the user could press
|
||||
* Back, unmount `ImportTab`, and strand the write it was driving — the same
|
||||
* dead end Phase 4 closed for the footer and the tab bar, reachable through a
|
||||
* door nobody had guarded.
|
||||
*/
|
||||
export function startRouting(options: RoutingOptions = {}): () => void {
|
||||
current = parse(globalThis.location?.hash ?? '');
|
||||
blocked = options.isBlocked;
|
||||
|
||||
const onHashChange = (): void => {
|
||||
current = parse(globalThis.location.hash);
|
||||
const next = parse(globalThis.location.hash);
|
||||
// Terminates the restore below: putting the hash back fires this handler a
|
||||
// second time, and that time the parsed route already equals `current`.
|
||||
if (next === current) return;
|
||||
if (options.isBlocked?.() === true) {
|
||||
globalThis.location.hash = `#${current}`;
|
||||
options.onBlocked?.();
|
||||
return;
|
||||
}
|
||||
current = next;
|
||||
};
|
||||
|
||||
globalThis.addEventListener('hashchange', onHashChange);
|
||||
return () => {
|
||||
globalThis.removeEventListener('hashchange', onHashChange);
|
||||
blocked = undefined;
|
||||
};
|
||||
}
|
||||
@@ -50,6 +50,43 @@ export async function loadSettings(): Promise<void> {
|
||||
loaded = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adopt settings written by another Manager tab.
|
||||
*
|
||||
* Two rules, and between them they solve the echo problem and the debounce
|
||||
* problem at once:
|
||||
*
|
||||
* 1. **If this context has an unflushed write, ignore the change entirely.**
|
||||
* `save()` writes the whole object, not a patch, so this tab is about to
|
||||
* overwrite the incoming value anyway — and adopting it first would clobber
|
||||
* the choice the user just made, in the UI *and* in what gets persisted 200
|
||||
* ms later. Ignoring is last-write-wins, which is the semantic docs/15
|
||||
* already documented, and it converges because our write fires this 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 `{...proxy}` and `coerceSettings` do not
|
||||
* agree on anyway.
|
||||
*
|
||||
* Deliberately does not schedule a save: adopting a value that is already on
|
||||
* disk and writing it straight back would make two tabs ping-pong forever.
|
||||
*
|
||||
* @returns whether anything changed.
|
||||
*/
|
||||
export function adoptExternalSettings(next: Settings): boolean {
|
||||
if (saveTimer !== undefined || pending !== undefined) return false;
|
||||
|
||||
const keys = Object.keys(DEFAULT_SETTINGS) as (keyof Settings)[];
|
||||
if (keys.every((key) => settings[key] === next[key])) return false;
|
||||
|
||||
// In place, never replaced — see updateSettings.
|
||||
Object.assign(settings, next);
|
||||
applyLocale();
|
||||
applyTheme(settings.theme);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a patch now, persist it shortly.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
# Store listing copy
|
||||
|
||||
The canonical source for the Chrome Web Store listing text, per `docs/13 §4`.
|
||||
|
||||
**Edit these files first, then paste into the dashboard** — a listing edit made
|
||||
straight into the dashboard has no diff, no history and no reviewer.
|
||||
|
||||
⚠️ These files were reconstructed from `docs/13 §3` *after* the listing went
|
||||
live on 2026-08-03. They are a faithful copy of the specified copy, not a
|
||||
transcript of what the dashboard currently shows. Until someone diffs the two,
|
||||
treat the dashboard as authoritative and correct these files, not the listing.
|
||||
|
||||
| File | Field |
|
||||
|---|---|
|
||||
| `listing.en.md` | Name, summary, description — English is required by CWS and is the canonical version |
|
||||
| `listing.vi.md` | Vietnamese localized fields |
|
||||
| `listing.ja.md` | Japanese localized fields |
|
||||
|
||||
The summary field is capped at **132 characters** by the dashboard. Each file
|
||||
records its own count; re-check after any edit, because the limit is enforced at
|
||||
submission time and a rejection there costs a round trip.
|
||||
|
||||
Legal documents are English-only by design (`docs/07 §5`, `docs/14`), so there
|
||||
is no localized privacy policy to keep in step — the privacy-policy URL is the
|
||||
same in all three listings.
|
||||
@@ -0,0 +1,56 @@
|
||||
# Chrome Web Store listing — English (canonical)
|
||||
|
||||
**Name:** `BookmarkMagic`
|
||||
|
||||
**Category:** Productivity → Tools
|
||||
|
||||
**Summary** (117 / 132 characters):
|
||||
|
||||
```
|
||||
Import, export & edit bookmarks between browsers — offline, no account, no cloud. Your data never leaves your device.
|
||||
```
|
||||
|
||||
**Description:**
|
||||
|
||||
```
|
||||
Move your bookmarks between browsers the simple way: with a file. No account.
|
||||
No cloud sync. 100% offline.
|
||||
|
||||
WHAT IT DOES
|
||||
• Import bookmark files (HTML, JSON, CSV) with a full preview before anything
|
||||
is written — see counts, folders, and duplicates first.
|
||||
• Choose how to import: into a new dated folder (safe default), merge into
|
||||
your existing folders, or replace everything (with an automatic safety
|
||||
backup downloaded first).
|
||||
• Skip duplicates automatically.
|
||||
• Export everything — or just the folders you pick — to HTML (works with
|
||||
Chrome, Edge, Brave, Firefox, Safari, Vivaldi, Opera), JSON, CSV, or
|
||||
Markdown.
|
||||
• Edit your bookmark tree: search, rename, drag & drop, create folders,
|
||||
delete, and find duplicate links.
|
||||
|
||||
PRIVACY BY DESIGN
|
||||
• Works entirely on your device. No servers, no analytics, no tracking.
|
||||
• Only two permissions: "bookmarks" (the whole point) and "storage" (your
|
||||
settings). Nothing else.
|
||||
• Free & open source (GPL-3.0) — read the code on GitHub.
|
||||
|
||||
LANGUAGES
|
||||
English · Tiếng Việt · 日本語
|
||||
|
||||
LIMITATIONS (HONESTY CORNER)
|
||||
• Favicons can't be imported — the extensions API for bookmarks has no
|
||||
favicon field.
|
||||
• Imported bookmarks get today's date — Chrome doesn't let extensions set a
|
||||
bookmark's original creation date. Your exported files keep the real dates.
|
||||
• CSV is a flattened view: empty folders and "which folder is the toolbar"
|
||||
aren't preserved. Use HTML or JSON for a faithful backup.
|
||||
|
||||
Source code, issue tracker & privacy policy:
|
||||
https://github.com/poli0981/bookmarkmagic
|
||||
```
|
||||
|
||||
**Privacy policy URL:**
|
||||
`https://github.com/poli0981/bookmarkmagic/blob/main/legal/PRIVACY.md`
|
||||
|
||||
**Distribution:** Public, all regions.
|
||||
@@ -0,0 +1,60 @@
|
||||
# Chrome Web Store listing — 日本語
|
||||
|
||||
Translated from `listing.en.md`, keeping its structure. Register: です/ます,
|
||||
katakana loanwords (ブックマーク, インポート, エクスポート, フォルダ), per
|
||||
`docs/07 §4`.
|
||||
|
||||
⚠️ `TODO(review-ja)` — like the in-app dictionary, this is best-effort until a
|
||||
native pass (`docs/00 §10.9`). Review before relying on it for a listing edit.
|
||||
|
||||
**Name:** `BookmarkMagic` (brand name — never translated)
|
||||
|
||||
**Summary** (63 / 132 characters — CJK counts by character, so this is short):
|
||||
|
||||
```
|
||||
ブラウザ間でブックマークをインポート・エクスポート・編集。オフライン、アカウント不要、クラウド不要。データは端末から出ません。
|
||||
```
|
||||
|
||||
**Description:**
|
||||
|
||||
```
|
||||
ブックマークをブラウザ間で移すいちばん簡単な方法は、ファイルを使うことです。
|
||||
アカウント不要、クラウド同期なし、完全オフラインで動作します。
|
||||
|
||||
できること
|
||||
• ブックマークファイル(HTML、JSON、CSV)をインポートします。書き込む前に
|
||||
必ずプレビューを表示し、件数・フォルダ・重複を先に確認できます。
|
||||
• インポート方法を選べます。日付付きの新しいフォルダに入れる(安全な既定
|
||||
値)、既存のフォルダに統合する、またはすべて置き換える(この場合は安全
|
||||
のためのバックアップを先にダウンロードします)。
|
||||
• 重複したブックマークは自動でスキップできます。
|
||||
• すべて、または選んだフォルダだけを HTML(Chrome、Edge、Brave、Firefox、
|
||||
Safari、Vivaldi、Opera で利用できます)、JSON、CSV、Markdown に
|
||||
エクスポートできます。
|
||||
• ブックマークツリーを編集できます。検索、名前の変更、ドラッグ&ドロップ、
|
||||
フォルダの作成、削除、重複リンクの検出。
|
||||
|
||||
設計としてのプライバシー
|
||||
• すべて端末上で動作します。サーバーも、分析も、トラッキングもありません。
|
||||
• 権限は 2 つだけです。「bookmarks」(本来の目的)と「storage」(設定の
|
||||
保存)。それ以外は要求しません。
|
||||
• 無料・オープンソース(GPL-3.0)です。コードは GitHub で確認できます。
|
||||
|
||||
対応言語
|
||||
English · Tiếng Việt · 日本語
|
||||
|
||||
制限事項(正直に)
|
||||
• ファビコンはインポートできません。ブラウザのブックマーク API に
|
||||
ファビコンの項目がないためです。
|
||||
• インポートしたブックマークの日付は本日の日付になります。拡張機能が
|
||||
ブックマークの元の作成日を設定することを Chrome が許可していないためです。
|
||||
エクスポートしたファイルには本来の日付が残ります。
|
||||
• CSV はフラットな形式です。空のフォルダや「どれがブックマークバーか」は
|
||||
保持されません。忠実なバックアップには HTML か JSON をお使いください。
|
||||
|
||||
ソースコード、問題の報告、プライバシーポリシー:
|
||||
https://github.com/poli0981/bookmarkmagic
|
||||
```
|
||||
|
||||
法的文書は英語のみです(`docs/14`)。プライバシーポリシーの URL は EN 版と
|
||||
同じものを使います。
|
||||
@@ -0,0 +1,56 @@
|
||||
# Chrome Web Store listing — Tiếng Việt
|
||||
|
||||
Translated from `listing.en.md`, keeping its structure. Register: neutral and
|
||||
friendly, "bạn"; established loanwords kept in English where that is what people
|
||||
actually say (bookmark, import, export), per `docs/07 §4`.
|
||||
|
||||
**Name:** `BookmarkMagic` (brand name — never translated)
|
||||
|
||||
**Summary** (125 / 132 characters — only 7 to spare, check after any edit):
|
||||
|
||||
```
|
||||
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.
|
||||
```
|
||||
|
||||
**Description:**
|
||||
|
||||
```
|
||||
Chuyển bookmark giữa các trình duyệt theo cách đơn giản nhất: bằng một tệp.
|
||||
Không tài khoản. Không đồng bộ đám mây. Hoàn toàn offline.
|
||||
|
||||
TIỆN ÍCH NÀY LÀM GÌ
|
||||
• Nhập tệp bookmark (HTML, JSON, CSV) và xem trước đầy đủ trước khi ghi bất
|
||||
cứ thứ gì — số lượng, thư mục và các mục trùng lặp đều hiện ra trước.
|
||||
• Chọn cách nhập: vào một thư mục mới theo ngày (mặc định an toàn), gộp vào
|
||||
các thư mục sẵn có, hoặc thay thế toàn bộ (tệp sao lưu an toàn sẽ được tải
|
||||
về trước).
|
||||
• Tự động bỏ qua các mục trùng lặp.
|
||||
• Xuất toàn bộ — hoặc chỉ những thư mục bạn chọn — ra HTML (dùng được với
|
||||
Chrome, Edge, Brave, Firefox, Safari, Vivaldi, Opera), JSON, CSV hoặc
|
||||
Markdown.
|
||||
• Chỉnh sửa cây bookmark: tìm kiếm, đổi tên, kéo thả, tạo thư mục, xoá và tìm
|
||||
các liên kết trùng lặp.
|
||||
|
||||
RIÊNG TƯ NGAY TỪ THIẾT KẾ
|
||||
• Chạy hoàn toàn trên máy bạn. Không máy chủ, không phân tích, không theo dõi.
|
||||
• Chỉ hai quyền: "bookmarks" (chính là mục đích của tiện ích) và "storage"
|
||||
(thiết lập của bạn). Không gì khác.
|
||||
• Miễn phí & mã nguồn mở (GPL-3.0) — bạn có thể đọc mã trên GitHub.
|
||||
|
||||
NGÔN NGỮ
|
||||
English · Tiếng Việt · 日本語
|
||||
|
||||
GIỚI HẠN (NÓI THẲNG)
|
||||
• Không thể nhập favicon — API bookmark của trình duyệt không có trường
|
||||
favicon.
|
||||
• Bookmark được nhập vào sẽ mang ngày hôm nay — Chrome không cho phép tiện ích
|
||||
đặt lại ngày tạo gốc của một bookmark. Các tệp bạn xuất ra vẫn giữ ngày thật.
|
||||
• CSV là dạng phẳng: thư mục rỗng và thông tin "thư mục nào là thanh bookmark"
|
||||
sẽ không được giữ lại. Hãy dùng HTML hoặc JSON nếu muốn sao lưu trung thực.
|
||||
|
||||
Mã nguồn, nơi báo lỗi & chính sách riêng tư:
|
||||
https://github.com/poli0981/bookmarkmagic
|
||||
```
|
||||
|
||||
Lưu ý: các tài liệu pháp lý chỉ có bản tiếng Anh (`docs/14`), nên URL chính sách
|
||||
riêng tư giống hệt bản EN.
|
||||
@@ -11,6 +11,8 @@ import type { LiveNode } from '@/lib/browser/bookmarks';
|
||||
export interface FakeBookmarksOptions {
|
||||
/** Throw on the Nth create (1-based), to test partial-failure reporting. */
|
||||
failOnCreate?: number;
|
||||
/** Throw on the Nth removeTree (1-based) — the Replace path's equivalent. */
|
||||
failOnRemoveTree?: number;
|
||||
}
|
||||
|
||||
export class FakeBookmarks {
|
||||
@@ -18,6 +20,7 @@ export class FakeBookmarks {
|
||||
private readonly nodes = new Map<string, LiveNode>();
|
||||
private nextId = 100;
|
||||
private createCount = 0;
|
||||
private removeCount = 0;
|
||||
// An explicit field, not a constructor parameter property: the latter emits
|
||||
// runtime code and is rejected by `erasableSyntaxOnly` (docs/10 §2).
|
||||
private readonly options: FakeBookmarksOptions;
|
||||
@@ -110,7 +113,11 @@ export class FakeBookmarks {
|
||||
};
|
||||
|
||||
removeTree = async (id: string): Promise<void> => {
|
||||
this.removeCount++;
|
||||
this.calls.push(`removeTree:${id}`);
|
||||
if (this.options.failOnRemoveTree === this.removeCount) {
|
||||
throw new Error(`injected failure on removeTree #${this.removeCount}`);
|
||||
}
|
||||
const node = this.nodes.get(id);
|
||||
if (node === undefined) throw new Error(`no such node: ${id}`);
|
||||
if (node.unmodifiable !== undefined) throw new Error("Can't modify managed bookmarks");
|
||||
|
||||
@@ -151,4 +151,37 @@ describe('clearRoots', () => {
|
||||
});
|
||||
expect(current.countCalls('removeTree')).toBe(0);
|
||||
});
|
||||
|
||||
it('reports how much was already deleted when a removal rejects', async () => {
|
||||
// This is the only path in the product that destroys data. A failure that
|
||||
// says nothing but "the browser refused" leaves the user unable to tell
|
||||
// whether they lost two bookmarks or all of them.
|
||||
current = new FakeBookmarks({ failOnRemoveTree: 3 });
|
||||
for (let i = 0; i < 5; i++) {
|
||||
current.seed('2', { title: `b${i}`, url: `https://e${i}.example/` });
|
||||
}
|
||||
|
||||
const roots = await getRoots();
|
||||
const err = await clearRoots(roots.writable).catch((e: unknown) => e);
|
||||
|
||||
expect(err).toMatchObject({ name: 'BmPartialWrite', phase: 'clearing', done: 2 });
|
||||
});
|
||||
|
||||
it('carries the removed count on an abort too, not a hardcoded zero', async () => {
|
||||
for (let i = 0; i < 4; i++) {
|
||||
current.seed('2', { title: `b${i}`, url: `https://e${i}.example/` });
|
||||
}
|
||||
const controller = new AbortController();
|
||||
let seen = 0;
|
||||
|
||||
const roots = await getRoots();
|
||||
const original = current.removeTree;
|
||||
current.removeTree = async (id: string): Promise<void> => {
|
||||
await original(id);
|
||||
if (++seen === 2) controller.abort();
|
||||
};
|
||||
|
||||
const err = await clearRoots(roots.writable, controller.signal).catch((e: unknown) => e);
|
||||
expect(err).toMatchObject({ name: 'BmAborted', done: 2 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { describeError } from '@/lib/browser/describe-error';
|
||||
import {
|
||||
BmAborted,
|
||||
BmBackupError,
|
||||
BmBrowserError,
|
||||
BmEnvError,
|
||||
BmPartialWrite,
|
||||
} from '@/lib/browser/errors';
|
||||
import { BmParseError } from '@/lib/core/model';
|
||||
|
||||
/**
|
||||
* `describeError` — docs/02 §7.
|
||||
*
|
||||
* Two properties matter more than the individual mappings, and both have been
|
||||
* defects in this codebase before:
|
||||
*
|
||||
* - the result is a **key**, never a resolved sentence, because the import
|
||||
* session outlives the component and `t()` is only reactive where it is
|
||||
* called;
|
||||
* - `detail` is *absent* when there is none, not `undefined`. Under
|
||||
* `exactOptionalPropertyTypes` those are different types, and only a runtime
|
||||
* `'detail' in result` check catches the difference.
|
||||
*/
|
||||
describe('describeError', () => {
|
||||
it('maps a parse error to its own code', () => {
|
||||
const result = describeError(new BmParseError('TOO_DEEP', 'nesting deeper than 200 levels'));
|
||||
expect(result.messageKey).toBe('errors.TOO_DEEP');
|
||||
expect(result.detail).toBe('nesting deeper than 200 levels');
|
||||
});
|
||||
|
||||
it('maps a backup error to its own code', () => {
|
||||
const result = describeError(new BmBackupError('BACKUP_CANCELLED'));
|
||||
expect(result.messageKey).toBe('errors.BACKUP_CANCELLED');
|
||||
});
|
||||
|
||||
it('maps a missing writable root to its own key, not to BROWSER', () => {
|
||||
// The browser refused nothing — every root is policy-managed. Reporting a
|
||||
// refusal sends the user looking for a permission problem that is not there.
|
||||
const result = describeError(new BmEnvError('NO_WRITABLE_ROOTS', '1 root(s), none writable'));
|
||||
expect(result.messageKey).toBe('errors.NO_WRITABLE_ROOTS');
|
||||
expect(result.detail).toBe('1 root(s), none writable');
|
||||
});
|
||||
|
||||
it('carries the created count off a partial write', () => {
|
||||
const result = describeError(new BmPartialWrite('writing', 42, new Error('quota')));
|
||||
expect(result.messageKey).toBe('errors.PARTIAL_WRITE');
|
||||
expect(result.created).toBe(42);
|
||||
expect(result.removed).toBeUndefined();
|
||||
expect(result.detail).toBe('quota');
|
||||
});
|
||||
|
||||
it('carries the removed count off a partial clear, and says something different', () => {
|
||||
// "some items were added" and "part of your tree is gone" need different
|
||||
// advice, so the phase picks the sentence rather than a shared one.
|
||||
const result = describeError(new BmPartialWrite('clearing', 7, new Error('boom')));
|
||||
expect(result.messageKey).toBe('errors.PARTIAL_CLEAR');
|
||||
expect(result.removed).toBe(7);
|
||||
expect(result.created).toBeUndefined();
|
||||
});
|
||||
|
||||
it('unwraps a BmBrowserError cause rather than nesting the message', () => {
|
||||
const cause = new BmBrowserError('bookmarks.create', new Error('Invalid URL'));
|
||||
const result = describeError(new BmPartialWrite('writing', 1, cause));
|
||||
expect(result.detail).toBe('Invalid URL');
|
||||
});
|
||||
|
||||
it('maps a raw browser rejection to BROWSER', () => {
|
||||
const result = describeError(new BmBrowserError('bookmarks.move', new Error('nope')));
|
||||
expect(result.messageKey).toBe('errors.BROWSER');
|
||||
expect(result.detail).toBe('nope');
|
||||
});
|
||||
|
||||
it('falls back to UNKNOWN for anything else, including non-Errors', () => {
|
||||
expect(describeError(new Error('plain')).messageKey).toBe('errors.UNKNOWN');
|
||||
expect(describeError('a string').messageKey).toBe('errors.UNKNOWN');
|
||||
expect(describeError(undefined).messageKey).toBe('errors.UNKNOWN');
|
||||
});
|
||||
|
||||
it('omits detail entirely rather than setting it to undefined', () => {
|
||||
const result = describeError('not an Error');
|
||||
expect('detail' in result).toBe(true);
|
||||
expect(result.detail).toBeUndefined();
|
||||
|
||||
// The env-error path uses a conditional spread, so the key is genuinely
|
||||
// absent — this is the assertion that catches a regression to
|
||||
// `detail: undefined`, which the type system alone would let through.
|
||||
const env = describeError(new BmEnvError('NO_WRITABLE_ROOTS'));
|
||||
expect('detail' in env).toBe(false);
|
||||
});
|
||||
|
||||
it('does not claim to describe an abort — cancellation is not a failure', () => {
|
||||
// BmAborted is handled by the caller before it ever reaches here. If that
|
||||
// ever changed, the user's own cancellation would be reported as an error.
|
||||
const result = describeError(new BmAborted(5));
|
||||
expect(result.messageKey).toBe('errors.UNKNOWN');
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { fakeBrowser } from 'wxt/testing';
|
||||
import { fakeBrowser } from 'wxt/testing/fake-browser';
|
||||
import { openBookmarkUrl } from '@/lib/browser/open-url';
|
||||
|
||||
/**
|
||||
@@ -8,18 +8,24 @@ import { openBookmarkUrl } from '@/lib/browser/open-url';
|
||||
* `javascript:` bookmark and the browser acting on it. It had no test.
|
||||
*/
|
||||
|
||||
let created: { url?: string }[] = [];
|
||||
/**
|
||||
* Recorded `tabs.create` calls.
|
||||
*
|
||||
* `url?: string | undefined` rather than `url?: string`: the API's own
|
||||
* `CreateProperties` declares it that way, and under
|
||||
* `exactOptionalPropertyTypes` the two are different types.
|
||||
*/
|
||||
let created: { url?: string | undefined }[] = [];
|
||||
|
||||
beforeEach(() => {
|
||||
fakeBrowser.reset();
|
||||
vi.restoreAllMocks();
|
||||
created = [];
|
||||
// fakeBrowser stubs tabs.* with "not implemented" throws.
|
||||
// fakeBrowser stubs tabs.* with "not implemented" throws. The mock resolves
|
||||
// with nothing because the API's return type is void — the caller ignores it,
|
||||
// and only the recorded call matters.
|
||||
vi.spyOn(fakeBrowser.tabs, 'create').mockImplementation(async (props) => {
|
||||
created.push(props);
|
||||
// SAFETY: the caller ignores the return value; only the recorded call
|
||||
// matters, and building a full Tab here would assert nothing.
|
||||
return {} as Awaited<ReturnType<typeof fakeBrowser.tabs.create>>;
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,19 +1,28 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { fakeBrowser } from 'wxt/testing';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { fakeBrowser } from 'wxt/testing/fake-browser';
|
||||
import {
|
||||
DEFAULT_SETTINGS,
|
||||
readLegal,
|
||||
readSettings,
|
||||
type StorageChange,
|
||||
subscribeStorage,
|
||||
writeLegal,
|
||||
writeSettings,
|
||||
} from '@/lib/browser/storage';
|
||||
|
||||
// fakeBrowser DOES implement storage.local, so no hand-rolled mock is needed
|
||||
// here (unlike bookmarks — docs/11 §4).
|
||||
// fakeBrowser DOES implement storage.local — and, verified before this suite
|
||||
// was written, storage.onChanged too. No hand-rolled mock is needed here
|
||||
// (unlike bookmarks — docs/11 §4).
|
||||
beforeEach(() => {
|
||||
fakeBrowser.reset();
|
||||
// reset() clears stored data but leaves spies in place, so one test that
|
||||
// mocks a storage call would otherwise leak into every later test.
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
/** Let the storage event dispatch. */
|
||||
const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve));
|
||||
|
||||
describe('settings', () => {
|
||||
it('returns the documented defaults on a fresh profile', async () => {
|
||||
expect(await readSettings()).toEqual(DEFAULT_SETTINGS);
|
||||
@@ -80,3 +89,84 @@ describe('legal acceptance', () => {
|
||||
expect(Object.keys(all).sort()).toEqual(['legal', 'settings']);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* `subscribeStorage` — docs/03 §4.
|
||||
*
|
||||
* The event fires in every extension context including the one that wrote, so
|
||||
* this layer only decodes and hands over; deciding what is an echo belongs to
|
||||
* the store, which is the only thing that knows what it was about to write.
|
||||
*/
|
||||
describe('subscribeStorage', () => {
|
||||
it('reports a settings write made elsewhere, already coerced', async () => {
|
||||
const seen: StorageChange[] = [];
|
||||
const stop = subscribeStorage((change) => seen.push(change));
|
||||
|
||||
await fakeBrowser.storage.local.set({ settings: { ...DEFAULT_SETTINGS, theme: 'dark' } });
|
||||
await settle();
|
||||
|
||||
expect(seen).toHaveLength(1);
|
||||
expect(seen[0]?.settings?.theme).toBe('dark');
|
||||
stop();
|
||||
});
|
||||
|
||||
it('coerces a malformed value field by field rather than passing it through', async () => {
|
||||
// A second tab is not a more trustworthy source than disk. It is the disk.
|
||||
const seen: StorageChange[] = [];
|
||||
const stop = subscribeStorage((change) => seen.push(change));
|
||||
|
||||
await fakeBrowser.storage.local.set({ settings: { theme: 'chartreuse', locale: 'vi' } });
|
||||
await settle();
|
||||
|
||||
expect(seen[0]?.settings).toEqual({ ...DEFAULT_SETTINGS, locale: 'vi' });
|
||||
stop();
|
||||
});
|
||||
|
||||
it('reports a legal acceptance, and a cleared one as null', async () => {
|
||||
const seen: StorageChange[] = [];
|
||||
const stop = subscribeStorage((change) => seen.push(change));
|
||||
|
||||
await writeLegal(1, '2026-08-03T00:00:00.000Z');
|
||||
await settle();
|
||||
expect(seen.at(-1)?.legal?.acceptedVersion).toBe(1);
|
||||
|
||||
await fakeBrowser.storage.local.remove('legal');
|
||||
await settle();
|
||||
expect(seen.at(-1)?.legal).toBeNull();
|
||||
stop();
|
||||
});
|
||||
|
||||
it('ignores keys this extension does not own', async () => {
|
||||
const seen: StorageChange[] = [];
|
||||
const stop = subscribeStorage((change) => seen.push(change));
|
||||
|
||||
await fakeBrowser.storage.local.set({ somethingElse: 1 });
|
||||
await settle();
|
||||
|
||||
expect(seen).toHaveLength(0);
|
||||
stop();
|
||||
});
|
||||
|
||||
it('stops delivering once unsubscribed', async () => {
|
||||
const seen: StorageChange[] = [];
|
||||
const stop = subscribeStorage((change) => seen.push(change));
|
||||
stop();
|
||||
|
||||
await writeSettings({ ...DEFAULT_SETTINGS, theme: 'dark' });
|
||||
await settle();
|
||||
|
||||
expect(seen).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('swallows a throwing handler', async () => {
|
||||
// An exception inside a chrome.* listener surfaces as an extension error in
|
||||
// chrome://extensions, which docs/11 §5 treats as a failed QA pass.
|
||||
const stop = subscribeStorage(() => {
|
||||
throw new Error('handler blew up');
|
||||
});
|
||||
|
||||
await expect(writeSettings({ ...DEFAULT_SETTINGS })).resolves.toBeUndefined();
|
||||
await settle();
|
||||
stop();
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { BmAborted } from '@/lib/browser/errors';
|
||||
import { BmAborted, BmPartialWrite } from '@/lib/browser/errors';
|
||||
import { type WriteProgress, writeTree } from '@/lib/browser/write-queue';
|
||||
import type { BookmarkNode, ImportPlan } from '@/lib/core/model';
|
||||
import { FakeBookmarks } from '../../helpers/fake-bookmarks';
|
||||
@@ -196,19 +196,55 @@ describe('writeTree — abort', () => {
|
||||
});
|
||||
|
||||
describe('writeTree — API failure', () => {
|
||||
const sixNodes = (): { title: string; url: string }[] =>
|
||||
Array.from({ length: 6 }, (_, i) => ({ title: `b${i}`, url: `https://e${i}.example/` }));
|
||||
|
||||
it('propagates a create failure with the earlier successes already written', async () => {
|
||||
const fake = new FakeBookmarks({ failOnCreate: 4 });
|
||||
const nodes = Array.from({ length: 6 }, (_, i) => ({
|
||||
title: `b${i}`,
|
||||
url: `https://e${i}.example/`,
|
||||
}));
|
||||
|
||||
await expect(
|
||||
writeTree(planOf([{ rootId: '2', nodes }]), { create: fake.create }),
|
||||
writeTree(planOf([{ rootId: '2', nodes: sixNodes() }]), { create: fake.create }),
|
||||
).rejects.toThrow(/injected failure/);
|
||||
|
||||
expect(fake.childTitles('2')).toEqual(['b0', 'b1', 'b2']);
|
||||
});
|
||||
|
||||
it('reports how many nodes landed, because they are still in the user tree', async () => {
|
||||
// Without this the report says only "the browser refused a bookmark
|
||||
// operation" — while three real bookmarks sit in the tree, and the user has
|
||||
// no way to learn how many. BmAborted has always carried this; a failure
|
||||
// needs it at least as much, because nobody chose it.
|
||||
const fake = new FakeBookmarks({ failOnCreate: 4 });
|
||||
|
||||
const err = await writeTree(planOf([{ rootId: '2', nodes: sixNodes() }]), {
|
||||
create: fake.create,
|
||||
}).catch((e: unknown) => e);
|
||||
|
||||
expect(err).toBeInstanceOf(BmPartialWrite);
|
||||
const partial = err as BmPartialWrite;
|
||||
expect(partial.phase).toBe('writing');
|
||||
expect(partial.done).toBe(3);
|
||||
expect(partial.detail).toMatch(/injected failure/);
|
||||
});
|
||||
|
||||
it('lets a cancellation stay a cancellation', async () => {
|
||||
// The abort check throws from inside the same loop as the create. Wrapping
|
||||
// it would relabel every user cancellation as a failure and make the
|
||||
// `cancelled` state — and its copy in three languages — unreachable.
|
||||
const fake = new FakeBookmarks();
|
||||
const controller = new AbortController();
|
||||
|
||||
const err = await writeTree(planOf([{ rootId: '2', nodes: sixNodes() }]), {
|
||||
create: async (details) => {
|
||||
controller.abort();
|
||||
return fake.create(details);
|
||||
},
|
||||
signal: controller.signal,
|
||||
}).catch((e: unknown) => e);
|
||||
|
||||
expect(err).toBeInstanceOf(BmAborted);
|
||||
expect(err).not.toBeInstanceOf(BmPartialWrite);
|
||||
});
|
||||
});
|
||||
|
||||
describe('writeTree — responsiveness', () => {
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { deleteEach } from '@/lib/edit/bulk-delete';
|
||||
|
||||
/**
|
||||
* Bulk delete — docs/03 §3.
|
||||
*
|
||||
* `deleteEach` exists to make the project's recurring defect shape impossible
|
||||
* here: mutate local state optimistically, await a `chrome.*` call that can
|
||||
* reject, never handle the rejection. It never throws, so the caller cannot
|
||||
* forget the failure case, and it reports how far it got — the confirmation
|
||||
* dialog promised an exact number and the action cannot be undone.
|
||||
*/
|
||||
describe('deleteEach', () => {
|
||||
it('deletes every id and reports a clean run', async () => {
|
||||
const removed: string[] = [];
|
||||
const outcome = await deleteEach(
|
||||
['a', 'b', 'c'],
|
||||
async () => {},
|
||||
(id) => removed.push(id),
|
||||
);
|
||||
|
||||
expect(outcome).toEqual({ deleted: 3, total: 3 });
|
||||
expect(removed).toEqual(['a', 'b', 'c']);
|
||||
});
|
||||
|
||||
it('stops at the first rejection and says how many landed', async () => {
|
||||
const remove = vi.fn(async (id: string) => {
|
||||
if (id === 'c') throw new Error('nope');
|
||||
});
|
||||
const outcome = await deleteEach(['a', 'b', 'c', 'd'], remove, () => {});
|
||||
|
||||
expect(outcome.deleted).toBe(2);
|
||||
expect(outcome.total).toBe(4);
|
||||
expect(outcome.error).toBeInstanceOf(Error);
|
||||
// 'd' is never attempted — one refusal usually means the rest will refuse
|
||||
// too, and hammering the API would just lengthen a frozen tab.
|
||||
expect(remove).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('never throws, whatever the remove does', async () => {
|
||||
await expect(
|
||||
deleteEach(
|
||||
['a'],
|
||||
() => Promise.reject(new Error('boom')),
|
||||
() => {},
|
||||
),
|
||||
).resolves.toMatchObject({ deleted: 0 });
|
||||
|
||||
await expect(
|
||||
deleteEach(
|
||||
['a'],
|
||||
() => Promise.reject('a string'),
|
||||
() => {},
|
||||
),
|
||||
).resolves.toMatchObject({ deleted: 0, error: 'a string' });
|
||||
});
|
||||
|
||||
it('confirms locally only after the browser accepted', async () => {
|
||||
// The other order is the defect: updating first leaves the tree claiming a
|
||||
// node is gone that the browser still has, for every id after a failure.
|
||||
const confirmed: string[] = [];
|
||||
await deleteEach(
|
||||
['a', 'b'],
|
||||
async (id) => {
|
||||
if (id === 'a') throw new Error('refused');
|
||||
},
|
||||
(id) => confirmed.push(id),
|
||||
);
|
||||
expect(confirmed).toEqual([]);
|
||||
});
|
||||
|
||||
it('handles an empty list', async () => {
|
||||
expect(
|
||||
await deleteEach(
|
||||
[],
|
||||
async () => {},
|
||||
() => {},
|
||||
),
|
||||
).toEqual({ deleted: 0, total: 0 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
collapseSearchExpansion,
|
||||
forgetSearchExpansion,
|
||||
mergeSearchExpansion,
|
||||
} from '@/lib/edit/search-expansion';
|
||||
|
||||
/**
|
||||
* Search-driven expansion — docs/03 §3.
|
||||
*
|
||||
* The bug this closes: a one-character query expands most of a large tree, and
|
||||
* clearing the box then rendered every one of those rows at once in a single
|
||||
* synchronous pass, with no virtualization behind it. The 150 ms debounce
|
||||
* delayed that; it never bounded it.
|
||||
*/
|
||||
const set = (...ids: string[]): ReadonlySet<string> => new Set(ids);
|
||||
|
||||
describe('mergeSearchExpansion', () => {
|
||||
it('opens what the search needs and remembers only what it opened', () => {
|
||||
const result = mergeSearchExpansion(set('a'), set('a', 'b', 'c'), set());
|
||||
expect([...result.expanded].sort()).toEqual(['a', 'b', 'c']);
|
||||
// 'a' was already open, so the search does not own it and must not close it.
|
||||
expect([...result.opened].sort()).toEqual(['b', 'c']);
|
||||
});
|
||||
|
||||
it('accumulates across successive queries', () => {
|
||||
const first = mergeSearchExpansion(set(), set('a'), set());
|
||||
const second = mergeSearchExpansion(first.expanded, set('b'), first.opened);
|
||||
expect([...second.opened].sort()).toEqual(['a', 'b']);
|
||||
});
|
||||
|
||||
it('returns the SAME set objects when nothing is missing', () => {
|
||||
// Identity, not equality: the caller stores these in `$state`, so returning
|
||||
// an equal-but-new Set would re-run every dependent on every keystroke.
|
||||
const expanded = set('a', 'b');
|
||||
const opened = set('b');
|
||||
const result = mergeSearchExpansion(expanded, set('a'), opened);
|
||||
expect(result.expanded).toBe(expanded);
|
||||
expect(result.opened).toBe(opened);
|
||||
});
|
||||
|
||||
it('is a no-op for an empty search', () => {
|
||||
const expanded = set('a');
|
||||
expect(mergeSearchExpansion(expanded, set(), set()).expanded).toBe(expanded);
|
||||
});
|
||||
});
|
||||
|
||||
describe('collapseSearchExpansion', () => {
|
||||
it('closes only what the search opened', () => {
|
||||
const result = collapseSearchExpansion(set('a', 'b', 'c'), set('b', 'c'));
|
||||
expect([...result]).toEqual(['a']);
|
||||
});
|
||||
|
||||
it('leaves a folder the user opened themselves alone', () => {
|
||||
// The whole point: a user who expanded a folder while searching keeps it.
|
||||
const merged = mergeSearchExpansion(set(), set('a', 'b'), set());
|
||||
const owned = forgetSearchExpansion(merged.opened, 'a');
|
||||
expect([...collapseSearchExpansion(merged.expanded, owned)]).toEqual(['a']);
|
||||
});
|
||||
|
||||
it('returns the same set when the search opened nothing', () => {
|
||||
const expanded = set('a');
|
||||
expect(collapseSearchExpansion(expanded, set())).toBe(expanded);
|
||||
});
|
||||
|
||||
it('tolerates an id that is no longer expanded', () => {
|
||||
expect([...collapseSearchExpansion(set('a'), set('gone'))]).toEqual(['a']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('forgetSearchExpansion', () => {
|
||||
it('drops the id, transferring ownership to the user', () => {
|
||||
expect([...forgetSearchExpansion(set('a', 'b'), 'a')]).toEqual(['b']);
|
||||
});
|
||||
|
||||
it('returns the same set for an id it never owned', () => {
|
||||
const opened = set('a');
|
||||
expect(forgetSearchExpansion(opened, 'zzz')).toBe(opened);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the whole cycle', () => {
|
||||
it('search, then clear, returns exactly to the starting state', () => {
|
||||
const start = set('root');
|
||||
const merged = mergeSearchExpansion(start, set('root', 'x', 'y', 'z'), set());
|
||||
expect(merged.expanded.size).toBe(4);
|
||||
|
||||
const cleared = collapseSearchExpansion(merged.expanded, merged.opened);
|
||||
expect([...cleared]).toEqual(['root']);
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,17 @@
|
||||
import { existsSync } from 'node:fs';
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { basename, join } from 'node:path';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { getAppVersion } from '@/lib/browser/app-info';
|
||||
import { setLocale, t } from '@/lib/i18n/index.svelte';
|
||||
import type { Locale } from '@/lib/i18n/resolve-locale';
|
||||
import { CHANGELOG_URL, DONATE_LINKS, ISSUES_URL, LEGAL_URLS, REPO_URL } from '@/lib/links';
|
||||
import {
|
||||
CHANGELOG_URL,
|
||||
DONATE_LINKS,
|
||||
ISSUES_URL,
|
||||
LEGAL_URLS,
|
||||
REPO_URL,
|
||||
STORE_URL,
|
||||
} from '@/lib/links';
|
||||
|
||||
const LOCALES: Locale[] = ['en', 'vi', 'ja'];
|
||||
/** Vitest runs with cwd at the project root, which is where `legal/` lives. */
|
||||
@@ -83,6 +90,29 @@ describe('outbound links', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('store listing', () => {
|
||||
it('is the published item, and is the only in-product route to a review', () => {
|
||||
// docs/13 §6 counts store ratings as a post-launch channel; before this
|
||||
// there was no way to reach the listing from inside the extension at all.
|
||||
expect(STORE_URL.startsWith('https://chromewebstore.google.com/detail/')).toBe(true);
|
||||
// The item id doubles as the CHROME_EXTENSION_ID secret (docs/00 §9), so a
|
||||
// typo here is a typo in two places.
|
||||
expect(STORE_URL).toContain('eghnciphhegekmnofffpgbdfefckdhmg');
|
||||
});
|
||||
|
||||
it('puts no email address on any in-product surface', () => {
|
||||
// Deliberate — docs/15 decision log, 2026-08-03. An address inside the
|
||||
// extension invites users to mail their real bookmarks file, which is the
|
||||
// receipt of personal data legal/PRIVACY.md exists to bound. The address
|
||||
// belongs in SECURITY.md and CONTRIBUTING.md, where it arrives alongside
|
||||
// the instruction to sanitize first.
|
||||
const source = readFileSync(join(REPO_ROOT, 'src', 'lib', 'links.ts'), 'utf8');
|
||||
const code = source.replace(/\/\*\*[\s\S]*?\*\//g, '');
|
||||
expect(code).not.toMatch(/mailto:/);
|
||||
expect(code).not.toMatch(/@poli0981\.dev/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAppVersion', () => {
|
||||
it('returns an empty string rather than throwing when the manifest is unreadable', () => {
|
||||
// fakeBrowser has no packaged manifest, so this exercises the fallback.
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { join, relative } from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { detectFormat } from '@/lib/core/detect-format';
|
||||
import { type BookmarkNode, computeStats, type ParseResult, walkTree } from '@/lib/core/model';
|
||||
import { parseBmJson } from '@/lib/core/parse/bm-json';
|
||||
import { parseCsv } from '@/lib/core/parse/csv';
|
||||
import { parseNetscapeHtml } from '@/lib/core/parse/netscape-html';
|
||||
|
||||
/**
|
||||
* `scripts/sanitize-bookmarks.mjs` — docs/11 §2, docs/09 §6.
|
||||
*
|
||||
* The script makes exactly one promise: after sanitizing, the bug still
|
||||
* reproduces. That is directly assertable against the committed corpus — parse
|
||||
* both versions and require the parser to see the same thing — so this suite
|
||||
* asserts the promise rather than the implementation.
|
||||
*
|
||||
* The script is invoked as a subprocess rather than imported. It is a `.mjs`
|
||||
* with no type declarations, and it has to keep running from a fresh clone with
|
||||
* nothing installed; spawning it also exercises the real entry point, argument
|
||||
* parsing included.
|
||||
*/
|
||||
const root = process.cwd();
|
||||
const script = join(root, 'scripts', 'sanitize-bookmarks.mjs');
|
||||
const fixtures = join(root, 'tests', 'fixtures');
|
||||
|
||||
/**
|
||||
* Run the CLI. `text` is null when it refused — which is a supported outcome,
|
||||
* not a failure: refusing is what it does with anything it cannot positively
|
||||
* identify, or whose output still contains a real address.
|
||||
*/
|
||||
function sanitize(absPath: string): { text: string | null; status: number } {
|
||||
try {
|
||||
const text = execFileSync(process.execPath, [script, absPath, '--stdout'], {
|
||||
encoding: 'utf8',
|
||||
stdio: ['ignore', 'pipe', 'ignore'],
|
||||
maxBuffer: 64 * 1024 * 1024,
|
||||
});
|
||||
return { text, status: 0 };
|
||||
} catch (err) {
|
||||
const status = (err as { status?: number }).status ?? 1;
|
||||
return { text: null, status };
|
||||
}
|
||||
}
|
||||
|
||||
/** Hosts that appear anywhere in the raw text, however the file is structured. */
|
||||
function hostsInText(text: string): string[] {
|
||||
const out = new Set<string>();
|
||||
for (const m of text.matchAll(/\b[a-z][a-z0-9+.-]*:\/\/([^\s"'<>)\]}\\]+)/gi)) {
|
||||
const authority = (m[1] ?? '').split(/[/?#]/, 1)[0] ?? '';
|
||||
const host = authority.split('@').pop()?.replace(/:\d+$/, '').toLowerCase() ?? '';
|
||||
if (host !== '') out.add(host);
|
||||
}
|
||||
return [...out];
|
||||
}
|
||||
|
||||
/**
|
||||
* Every committed fixture file, as paths relative to `tests/fixtures/`.
|
||||
*
|
||||
* Discovered rather than listed, so a fixture added by a future bug report is
|
||||
* covered without anyone remembering to add it here. `generated/` is skipped:
|
||||
* it is git-ignored `gen-fixture.mjs` output, so it exists on some machines and
|
||||
* not others, and a suite whose corpus depends on that is not reproducible.
|
||||
*/
|
||||
function corpus(): string[] {
|
||||
const out: string[] = [];
|
||||
const walk = (dir: string): void => {
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||
if (entry.name === 'generated') continue;
|
||||
const full = join(dir, entry.name);
|
||||
if (entry.isDirectory()) walk(full);
|
||||
else if (/\.(html|json|csv)$/.test(entry.name)) out.push(relative(fixtures, full));
|
||||
}
|
||||
};
|
||||
walk(fixtures);
|
||||
return out.sort();
|
||||
}
|
||||
|
||||
const FIXTURES = corpus();
|
||||
|
||||
/** Parse with whichever parser the sniffed format selects. */
|
||||
function parseAny(text: string): ParseResult {
|
||||
const format = detectFormat(text);
|
||||
if (format === 'netscape-html') return parseNetscapeHtml(text);
|
||||
if (format === 'bm-json') return parseBmJson(text);
|
||||
return parseCsv(text);
|
||||
}
|
||||
|
||||
/** Structure only: folder/bookmark shape and nesting, with no titles or URLs. */
|
||||
function topology(roots: readonly BookmarkNode[]): string {
|
||||
const render = (nodes: readonly BookmarkNode[]): string =>
|
||||
nodes.map((n) => (n.url === undefined ? `F(${render(n.children ?? [])})` : 'B')).join(',');
|
||||
return render(roots);
|
||||
}
|
||||
|
||||
it('the corpus is non-empty, so a broken walk cannot pass vacuously', () => {
|
||||
expect(FIXTURES.length).toBeGreaterThan(10);
|
||||
});
|
||||
|
||||
describe.each(FIXTURES)('sanitize %s', (name) => {
|
||||
const original = readFileSync(join(fixtures, name), 'utf8');
|
||||
const { text: cleaned, status } = sanitize(join(fixtures, name));
|
||||
|
||||
it('either sanitizes, or refuses — and refuses exactly what the parser rejects', () => {
|
||||
// The two must agree. A file the extension itself cannot read is one this
|
||||
// tool cannot promise to have cleaned, and the old fallback guessed "csv",
|
||||
// matched no columns, and emitted the input verbatim while reporting
|
||||
// success — publishing a real bookmark set to a public issue.
|
||||
let parserAccepts = true;
|
||||
try {
|
||||
detectFormat(original);
|
||||
} catch {
|
||||
parserAccepts = false;
|
||||
}
|
||||
if (parserAccepts) {
|
||||
expect(status).toBe(0);
|
||||
expect(cleaned).not.toBeNull();
|
||||
} else {
|
||||
expect(status).toBe(1);
|
||||
expect(cleaned).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it('leaks no hostname from the original', () => {
|
||||
// Asserted on the raw TEXT, not on a parse. The previous version returned
|
||||
// early whenever the original failed to parse, so it passed vacuously on
|
||||
// precisely the inputs that leaked.
|
||||
if (cleaned === null) return;
|
||||
const before = hostsInText(original);
|
||||
expect(before.filter((host) => cleaned.includes(host))).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps the file recognisable as the same format', () => {
|
||||
if (cleaned === null) return;
|
||||
expect(detectFormat(cleaned)).toBe(detectFormat(original));
|
||||
});
|
||||
|
||||
it('parses to the same stats, warnings and structure', () => {
|
||||
if (cleaned === null) return;
|
||||
const before = parseAny(original);
|
||||
const after = parseAny(cleaned);
|
||||
expect(after.stats).toEqual(before.stats);
|
||||
expect(computeStats(after.roots)).toEqual(computeStats(before.roots));
|
||||
expect(topology(after.roots)).toBe(topology(before.roots));
|
||||
expect(after.warnings.map((w) => w.code).sort()).toEqual(
|
||||
before.warnings.map((w) => w.code).sort(),
|
||||
);
|
||||
});
|
||||
|
||||
it('preserves byte-level shape: BOM, line endings and line count', () => {
|
||||
if (cleaned === null) return;
|
||||
expect(cleaned.charCodeAt(0) === 0xfeff).toBe(original.charCodeAt(0) === 0xfeff);
|
||||
expect(cleaned.includes('\r\n')).toBe(original.includes('\r\n'));
|
||||
expect(cleaned.split('\n').length).toBe(original.split('\n').length);
|
||||
});
|
||||
|
||||
it('preserves every timestamp exactly', () => {
|
||||
if (cleaned === null) return;
|
||||
const stamps = (text: string): string[] =>
|
||||
(text.match(/(?:ADD_DATE|LAST_MODIFIED)="(\d*)"/gi) ?? []).sort();
|
||||
expect(stamps(cleaned)).toEqual(stamps(original));
|
||||
});
|
||||
|
||||
it('keeps distinct URLs distinct, so dedupe behaviour is unchanged', () => {
|
||||
if (cleaned === null) return;
|
||||
const urls = (text: string): number => {
|
||||
const set = new Set<string>();
|
||||
for (const { node } of walkTree(parseAny(text).roots)) {
|
||||
if (node.url !== undefined) set.add(node.url);
|
||||
}
|
||||
return set.size;
|
||||
};
|
||||
expect(urls(cleaned)).toBe(urls(original));
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* The refusal paths — every one of these was a silent leak found by review.
|
||||
*
|
||||
* The shared property: when a rule does not reach some byte, the tool must
|
||||
* refuse rather than hand over a file the user has been told is clean. The
|
||||
* rules are regexes over untrusted markup, so "we thought of every shape" is
|
||||
* not a claim anyone can make honestly; the output check is what makes that
|
||||
* survivable.
|
||||
*/
|
||||
describe('refuses rather than leaking', () => {
|
||||
const tmp = join(root, 'tests', 'fixtures', 'generated');
|
||||
|
||||
const run = (name: string, content: string): { text: string | null; status: number } => {
|
||||
mkdirSync(tmp, { recursive: true });
|
||||
const path = join(tmp, name);
|
||||
writeFileSync(path, content);
|
||||
try {
|
||||
return sanitize(path);
|
||||
} finally {
|
||||
rmSync(path, { force: true });
|
||||
}
|
||||
};
|
||||
|
||||
it.each([
|
||||
[
|
||||
'a truncated JSON export',
|
||||
'broken.json',
|
||||
'{"format":"bookmarkmagic","roots":[{"title":"x","url":"https://clinic.internal/a"',
|
||||
],
|
||||
[
|
||||
'an HTML excerpt with no doctype and no <DL>',
|
||||
'excerpt.html',
|
||||
'<DT><A HREF="https://clinic.internal/a">Appointment</A>',
|
||||
],
|
||||
[
|
||||
'a CSV with foreign headers',
|
||||
'foreign.csv',
|
||||
'folder,name,link\n"m","x","https://clinic.internal/a"\n',
|
||||
],
|
||||
])('refuses %s', (_label, name, content) => {
|
||||
const { text, status } = run(name, content);
|
||||
expect(status).toBe(1);
|
||||
expect(text).toBeNull();
|
||||
});
|
||||
|
||||
it('catches a leak the rewriting rules missed, instead of emitting it', () => {
|
||||
// Single-quoted attributes were not matched at all. The rule is fixed, but
|
||||
// the point of this test is the backstop: even with the rule removed, the
|
||||
// output check would refuse rather than publish `clinic.internal`.
|
||||
const { text, status } = run(
|
||||
'quoted.html',
|
||||
"<!DOCTYPE NETSCAPE-Bookmark-file-1>\n<DL><p>\n<DT><A HREF='https://clinic.internal/a'>x</A>\n</DL><p>\n",
|
||||
);
|
||||
expect(status).toBe(0);
|
||||
expect(text).not.toBeNull();
|
||||
expect(text).not.toContain('clinic.internal');
|
||||
});
|
||||
|
||||
it('sanitizes a bookmark whose title contains a raw <', () => {
|
||||
// `[^<]*` made the whole match fail, so the title was left in place.
|
||||
const { text } = run(
|
||||
'angle.html',
|
||||
'<!DOCTYPE NETSCAPE-Bookmark-file-1>\n<DL><p>\n<DT><A HREF="https://a.invalid/">Dr Smith < oncology</A>\n</DL><p>\n',
|
||||
);
|
||||
expect(text).not.toBeNull();
|
||||
expect(text).not.toContain('oncology');
|
||||
});
|
||||
|
||||
it('sanitizes a <DD> description that wraps onto a second line', () => {
|
||||
// The capture stopped at the first newline, publishing the rest.
|
||||
const { text } = run(
|
||||
'dd.html',
|
||||
'<!DOCTYPE NETSCAPE-Bookmark-file-1>\n<DL><p>\n<DT><H3>F</H3>\n<DD>first line\nsecond line with dr-smith\n<DL><p></DL><p>\n</DL><p>\n',
|
||||
);
|
||||
expect(text).not.toBeNull();
|
||||
expect(text).not.toContain('dr-smith');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,148 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import {
|
||||
answerAttestation,
|
||||
awaitAttestation,
|
||||
beginWrite,
|
||||
cancelWrite,
|
||||
getImportState,
|
||||
hasPendingAttestation,
|
||||
isWriting,
|
||||
resetImport,
|
||||
setImportState,
|
||||
} from '@/lib/stores/import-session.svelte';
|
||||
|
||||
/**
|
||||
* Import session store — docs/03 §5.
|
||||
*
|
||||
* The attestation half of this file exists because of a real dead end: the
|
||||
* resolver used to be a component-local `let`, so pressing browser Back during
|
||||
* `attesting` 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. Closing the tab was the only way out.
|
||||
*/
|
||||
beforeEach(() => {
|
||||
resetImport();
|
||||
});
|
||||
|
||||
describe('isWriting', () => {
|
||||
it.each([
|
||||
['backing-up', true],
|
||||
['attesting', true],
|
||||
['clearing', true],
|
||||
['writing', true],
|
||||
['idle', false],
|
||||
['validating', false],
|
||||
['parsed', false],
|
||||
['done', false],
|
||||
['cancelled', false],
|
||||
['error', false],
|
||||
])('%s → %s', (kind, expected) => {
|
||||
// Only the shape of `kind` is under test; the rest of each variant is
|
||||
// filled with whatever satisfies the union.
|
||||
const states: Record<string, Parameters<typeof setImportState>[0]> = {
|
||||
idle: { kind: 'idle' },
|
||||
validating: { kind: 'validating', filename: 'f' },
|
||||
parsed: {
|
||||
kind: 'parsed',
|
||||
filename: 'f',
|
||||
result: { roots: [], warnings: [], stats: { bookmarks: 0, folders: 0, maxDepth: 0 } },
|
||||
duplicates: 0,
|
||||
},
|
||||
'backing-up': { kind: 'backing-up', filename: 'f' },
|
||||
attesting: { kind: 'attesting', filename: 'f', backupFilename: 'b.json' },
|
||||
clearing: { kind: 'clearing', filename: 'f' },
|
||||
writing: {
|
||||
kind: 'writing',
|
||||
filename: 'f',
|
||||
progress: { done: 0, total: 1, currentPath: '' },
|
||||
},
|
||||
done: {
|
||||
kind: 'done',
|
||||
filename: 'f',
|
||||
created: 1,
|
||||
plan: {
|
||||
mode: 'new-folder',
|
||||
dedupe: false,
|
||||
segments: [],
|
||||
stats: { toCreate: 0, bookmarkCount: 0, skippedExisting: 0, skippedInFile: 0 },
|
||||
},
|
||||
},
|
||||
cancelled: { kind: 'cancelled', filename: 'f', created: 1 },
|
||||
error: { kind: 'error', filename: 'f', messageKey: 'errors.UNKNOWN' },
|
||||
};
|
||||
const state = states[kind];
|
||||
if (state === undefined) throw new Error(`unmapped kind: ${kind}`);
|
||||
setImportState(state);
|
||||
expect(isWriting()).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('attestation', () => {
|
||||
it('settles true when the user confirms', async () => {
|
||||
const pending = awaitAttestation();
|
||||
expect(hasPendingAttestation()).toBe(true);
|
||||
answerAttestation(true);
|
||||
await expect(pending).resolves.toBe(true);
|
||||
expect(hasPendingAttestation()).toBe(false);
|
||||
});
|
||||
|
||||
it('settles false when the user cancels', async () => {
|
||||
const pending = awaitAttestation();
|
||||
answerAttestation(false);
|
||||
await expect(pending).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('survives the component that started it — the deadlock this replaced', async () => {
|
||||
// The resolver lives in the store, so an unmount and remount of ImportTab
|
||||
// leaves the promise settleable. As a component-local `let` this hung.
|
||||
const pending = awaitAttestation();
|
||||
// …component unmounts and remounts here; nothing in the store changes…
|
||||
expect(hasPendingAttestation()).toBe(true);
|
||||
answerAttestation(true);
|
||||
await expect(pending).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it('resetImport settles a pending attestation as NOT confirmed', async () => {
|
||||
// "Import another file" pressed mid-attestation must not leave a resolver
|
||||
// behind — that would move the deadlock from a component, where it is
|
||||
// visible, into a store, where nothing renders it.
|
||||
const pending = awaitAttestation();
|
||||
resetImport();
|
||||
await expect(pending).resolves.toBe(false);
|
||||
expect(hasPendingAttestation()).toBe(false);
|
||||
expect(getImportState().kind).toBe('idle');
|
||||
});
|
||||
|
||||
it('a second attestation settles the first as NOT confirmed, never drops it', async () => {
|
||||
// Failing closed matters here more than anywhere: this promise is the last
|
||||
// gate before deleting every bookmark the user has.
|
||||
const first = awaitAttestation();
|
||||
const second = awaitAttestation();
|
||||
await expect(first).resolves.toBe(false);
|
||||
|
||||
answerAttestation(true);
|
||||
await expect(second).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it('answering with nothing pending is a no-op, not a throw', () => {
|
||||
expect(() => answerAttestation(true)).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('write control', () => {
|
||||
it('beginWrite hands out a signal that cancelWrite aborts', () => {
|
||||
const signal = beginWrite();
|
||||
expect(signal.aborted).toBe(false);
|
||||
cancelWrite();
|
||||
expect(signal.aborted).toBe(true);
|
||||
});
|
||||
|
||||
it('each write gets a fresh signal, so a past cancel cannot poison the next', () => {
|
||||
const first = beginWrite();
|
||||
cancelWrite();
|
||||
const second = beginWrite();
|
||||
expect(first.aborted).toBe(true);
|
||||
expect(second.aborted).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,9 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { fakeBrowser } from 'wxt/testing';
|
||||
import { fakeBrowser } from 'wxt/testing/fake-browser';
|
||||
import { LEGAL_VERSION } from '@/lib/core/limits';
|
||||
import {
|
||||
acceptLegal,
|
||||
adoptExternalLegal,
|
||||
decideLegalStatus,
|
||||
getAcceptance,
|
||||
getBlockedRoutes,
|
||||
@@ -159,3 +160,54 @@ describe('acceptLegal', () => {
|
||||
expect(Object.keys(all)).not.toContain('legal');
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Cross-tab adoption — docs/03 §4, docs/14 §2.
|
||||
*
|
||||
* Deliberately one-way. `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 — the same deadlock the routing guard and
|
||||
* the store-held attestation resolver exist to close, reached through a third
|
||||
* door. These tests exist so a future "simplification" that makes it
|
||||
* symmetrical fails loudly rather than shipping.
|
||||
*/
|
||||
describe('adoptExternalLegal', () => {
|
||||
it('drops the gate when another tab accepts', async () => {
|
||||
await loadLegal();
|
||||
expect(isGateRequired()).toBe(true);
|
||||
|
||||
expect(adoptExternalLegal({ acceptedVersion: LEGAL_VERSION, acceptedAt: 'x' })).toBe(true);
|
||||
expect(isGateRequired()).toBe(false);
|
||||
});
|
||||
|
||||
it('does NOT re-gate when another tab clears the acceptance', async () => {
|
||||
await fakeBrowser.storage.local.set({
|
||||
legal: { acceptedVersion: LEGAL_VERSION, acceptedAt: 'x' },
|
||||
});
|
||||
await loadLegal();
|
||||
expect(isGateRequired()).toBe(false);
|
||||
|
||||
expect(adoptExternalLegal(null)).toBe(false);
|
||||
expect(isGateRequired()).toBe(false);
|
||||
});
|
||||
|
||||
it('does NOT re-gate on a superseded record either', async () => {
|
||||
await fakeBrowser.storage.local.set({
|
||||
legal: { acceptedVersion: LEGAL_VERSION, acceptedAt: 'x' },
|
||||
});
|
||||
await loadLegal();
|
||||
|
||||
expect(adoptExternalLegal({ acceptedVersion: LEGAL_VERSION - 1, acceptedAt: 'old' })).toBe(
|
||||
false,
|
||||
);
|
||||
expect(isGateRequired()).toBe(false);
|
||||
});
|
||||
|
||||
it('ignores a stale record while the gate is up, rather than accepting it', async () => {
|
||||
await loadLegal();
|
||||
expect(adoptExternalLegal({ acceptedVersion: LEGAL_VERSION - 1, acceptedAt: 'old' })).toBe(
|
||||
false,
|
||||
);
|
||||
expect(isGateRequired()).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -52,3 +52,92 @@ describe('route store', () => {
|
||||
expect(getRoute()).toBe('about');
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* The guard exists because browser Back was the one route out of #import that
|
||||
* nothing checked. During the backup attestation it unmounted `ImportTab` and
|
||||
* stranded the promise `runImport` was awaiting — a Manager that could only be
|
||||
* escaped by closing the tab.
|
||||
*/
|
||||
describe('route store — blocked while a write is in flight', () => {
|
||||
const settle = (): Promise<void> =>
|
||||
new Promise((resolve) => {
|
||||
setTimeout(() => setTimeout(() => resolve()));
|
||||
});
|
||||
|
||||
it('refuses an external hashchange and puts the hash back', async () => {
|
||||
const stop = startRouting({ isBlocked: () => true });
|
||||
globalThis.location.hash = '#export';
|
||||
await settle();
|
||||
|
||||
expect(getRoute()).toBe('import');
|
||||
expect(globalThis.location.hash).toBe('#import');
|
||||
stop();
|
||||
});
|
||||
|
||||
it('restoring the hash does not recurse', async () => {
|
||||
// Putting the hash back fires `hashchange` a second time. Without the
|
||||
// `next === current` early return that is an infinite loop, in a released
|
||||
// extension, on the one path a panicking user is most likely to take.
|
||||
let blockedCalls = 0;
|
||||
const stop = startRouting({
|
||||
isBlocked: () => {
|
||||
blockedCalls++;
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
globalThis.location.hash = '#edit';
|
||||
await settle();
|
||||
|
||||
expect(blockedCalls).toBe(1);
|
||||
stop();
|
||||
});
|
||||
|
||||
it('reports the refusal exactly once, so the UI can explain itself', async () => {
|
||||
let notified = 0;
|
||||
const stop = startRouting({ isBlocked: () => true, onBlocked: () => notified++ });
|
||||
|
||||
globalThis.location.hash = '#about';
|
||||
await settle();
|
||||
|
||||
expect(notified).toBe(1);
|
||||
stop();
|
||||
});
|
||||
|
||||
it('navigate() returns false and writes nothing while blocked', () => {
|
||||
const stop = startRouting({ isBlocked: () => true });
|
||||
expect(navigate('export')).toBe(false);
|
||||
expect(getRoute()).toBe('import');
|
||||
expect(globalThis.location.hash === '#export').toBe(false);
|
||||
stop();
|
||||
});
|
||||
|
||||
it('navigating to the route you are already on is never refused', () => {
|
||||
// Otherwise ImportTab could not re-assert its own route mid-write.
|
||||
const stop = startRouting({ isBlocked: () => true });
|
||||
expect(navigate('import')).toBe(true);
|
||||
stop();
|
||||
});
|
||||
|
||||
it('follows again as soon as the write finishes', async () => {
|
||||
let writing = true;
|
||||
const stop = startRouting({ isBlocked: () => writing });
|
||||
|
||||
globalThis.location.hash = '#edit';
|
||||
await settle();
|
||||
expect(getRoute()).toBe('import');
|
||||
|
||||
writing = false;
|
||||
globalThis.location.hash = '#edit';
|
||||
await settle();
|
||||
expect(getRoute()).toBe('edit');
|
||||
stop();
|
||||
});
|
||||
|
||||
it('leaves the guard behind on cleanup, so a stale predicate cannot lock the app', () => {
|
||||
const stop = startRouting({ isBlocked: () => true });
|
||||
stop();
|
||||
expect(navigate('export')).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,9 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { fakeBrowser } from 'wxt/testing';
|
||||
import { fakeBrowser } from 'wxt/testing/fake-browser';
|
||||
import { DEFAULT_SETTINGS } from '@/lib/browser/storage';
|
||||
import { getLocale } from '@/lib/i18n/index.svelte';
|
||||
import {
|
||||
adoptExternalSettings,
|
||||
applyTheme,
|
||||
flushSettings,
|
||||
getSettings,
|
||||
@@ -200,3 +201,72 @@ describe('settings store', () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Cross-tab adoption — docs/03 §4.
|
||||
*
|
||||
* Two Manager tabs used to silently overwrite each other, because `save()`
|
||||
* writes the whole settings object rather than a patch: a tab holding a stale
|
||||
* locale reverted the other tab's language change the moment its own theme
|
||||
* toggle fired. From the user's side that is "I changed it and it didn't
|
||||
* stick", which is unfalsifiable and reads as a bug in the extension.
|
||||
*/
|
||||
describe('adoptExternalSettings', () => {
|
||||
it('applies a change from another tab, including locale and theme', async () => {
|
||||
await updateSettings({ theme: 'light' });
|
||||
const changed = adoptExternalSettings({ ...DEFAULT_SETTINGS, theme: 'dark', locale: 'vi' });
|
||||
|
||||
expect(changed).toBe(true);
|
||||
expect(getSettings().theme).toBe('dark');
|
||||
expect(document.documentElement.getAttribute('data-theme')).toBe('dark');
|
||||
expect(getLocale()).toBe('vi');
|
||||
});
|
||||
|
||||
it('mutates in place, so a component that captured the object still sees it', () => {
|
||||
const captured = getSettings();
|
||||
adoptExternalSettings({ ...DEFAULT_SETTINGS, theme: 'dark' });
|
||||
expect(getSettings()).toBe(captured);
|
||||
expect(captured.theme).toBe('dark');
|
||||
});
|
||||
|
||||
it('ignores an identical value — which is what our own write looks like', () => {
|
||||
// Echo suppression falls out of field equality: no snapshot to keep in step,
|
||||
// and no dependence on key order.
|
||||
expect(adoptExternalSettings({ ...getSettings() })).toBe(false);
|
||||
});
|
||||
|
||||
it('does NOT clobber an edit this tab has not persisted yet', async () => {
|
||||
// The hazard the whole design exists for. Writes are debounced 200 ms; a
|
||||
// change arriving inside that window must lose, because this tab is about
|
||||
// to write its entire object over it anyway — adopting first would revert
|
||||
// the user's choice in the UI *and* in what gets saved.
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
void updateSettings({ theme: 'dark' });
|
||||
const changed = adoptExternalSettings({ ...DEFAULT_SETTINGS, theme: 'light' });
|
||||
|
||||
expect(changed).toBe(false);
|
||||
expect(getSettings().theme).toBe('dark');
|
||||
|
||||
await vi.advanceTimersByTimeAsync(250);
|
||||
const stored = await fakeBrowser.storage.local.get('settings');
|
||||
expect((stored.settings as { theme: string }).theme).toBe('dark');
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('adopts again once the pending write has flushed', async () => {
|
||||
await updateSettings({ theme: 'dark' });
|
||||
await flushSettings();
|
||||
expect(adoptExternalSettings({ ...DEFAULT_SETTINGS, theme: 'light' })).toBe(true);
|
||||
});
|
||||
|
||||
it('does not write back what it just adopted', async () => {
|
||||
// Otherwise two tabs ping-pong the same value forever.
|
||||
const spy = vi.spyOn(fakeBrowser.storage.local, 'set');
|
||||
adoptExternalSettings({ ...DEFAULT_SETTINGS, theme: 'dark' });
|
||||
await flushSettings();
|
||||
expect(spy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import { svelte } from '@sveltejs/vite-plugin-svelte';
|
||||
import { defineConfig } from 'vitest/config';
|
||||
import { WxtVitest } from 'wxt/testing';
|
||||
import { WxtVitest } from 'wxt/testing/vitest-plugin';
|
||||
|
||||
/**
|
||||
* jsdom, not happy-dom (docs/02 §3). The Netscape parser walk depends on
|
||||
|
||||
Reference in new issue
Block a user